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 const char * const ipp_states
[] =
40 { /* IPP state strings */
52 static int check_if_modified(cupsd_client_t
*con
,
53 struct stat
*filestats
);
54 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
56 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
57 char *filename
, int len
);
58 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
59 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
60 struct stat
*filestats
, mime_type_t
*type
);
61 static int is_path_absolute(const char *path
);
62 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
63 char *command
, char *options
, int root
);
64 static int valid_host(cupsd_client_t
*con
);
65 static int write_file(cupsd_client_t
*con
, http_status_t code
,
66 char *filename
, char *type
,
67 struct stat
*filestats
);
68 static void write_pipe(cupsd_client_t
*con
);
72 * 'cupsdAcceptClient()' - Accept a new client.
76 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
78 const char *hostname
; /* Hostname of client */
79 char name
[256]; /* Hostname of client */
80 int count
; /* Count of connections on a host */
81 cupsd_client_t
*con
, /* New client pointer */
82 *tempcon
; /* Temporary client pointer */
83 socklen_t addrlen
; /* Length of address */
84 http_addr_t temp
; /* Temporary address variable */
85 static time_t last_dos
= 0; /* Time of last DoS attack */
87 struct request_info wrap_req
; /* TCP wrappers request information */
88 #endif /* HAVE_TCPD_H */
91 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
92 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
93 lis
, lis
->fd
, cupsArrayCount(Clients
));
96 * Make sure we don't have a full set of clients already...
99 if (cupsArrayCount(Clients
) == MaxClients
)
103 * Get a pointer to the next available client...
107 Clients
= cupsArrayNew(NULL
, NULL
);
111 cupsdLogMessage(CUPSD_LOG_ERROR
,
112 "Unable to allocate memory for clients array!");
113 cupsdPauseListening();
118 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
122 cupsdLogMessage(CUPSD_LOG_ERROR
,
123 "Unable to allocate memory for active clients array!");
124 cupsdPauseListening();
128 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
130 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
131 cupsdPauseListening();
136 * Accept the client and get the remote address...
139 con
->number
= ++ LastClientNumber
;
142 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
144 if (errno
== ENFILE
|| errno
== EMFILE
)
145 cupsdPauseListening();
147 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
155 * Save the connected address and port number...
158 con
->clientaddr
= lis
->address
;
160 #if 0 /* ifdef AF_INET6 */
161 /* FIXME: I don't believe this is recommended any longer, and we specifically
162 * disable IPv4-over-IPv6 when we listen...
165 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
166 * can more easily use...
169 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
170 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
171 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
172 ntohl(httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
173 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
174 #endif /* AF_INET6 */
177 * Check the number of clients on the same address...
180 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
182 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
183 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
186 if (count
>= MaxClientsPerHost
)
190 if (count
>= MaxClientsPerHost
)
192 if ((time(NULL
) - last_dos
) >= 60)
194 last_dos
= time(NULL
);
195 cupsdLogMessage(CUPSD_LOG_WARN
,
196 "Possible DoS attack - more than %d clients connecting "
199 httpGetHostname(con
->http
, name
, sizeof(name
)));
202 httpClose(con
->http
);
208 * Get the hostname or format the IP address as needed...
212 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
214 hostname
= httpGetHostname(con
->http
, NULL
, 0);
216 if (hostname
== NULL
&& HostNameLookups
== 2)
219 * Can't have an unresolved IP address with double-lookups enabled...
222 httpClose(con
->http
);
224 cupsdLogClient(con
, CUPSD_LOG_WARN
,
225 "Name lookup failed - connection from %s closed!",
226 httpGetHostname(con
->http
, NULL
, 0));
232 if (HostNameLookups
== 2)
235 * Do double lookups as needed...
238 http_addrlist_t
*addrlist
, /* List of addresses */
239 *addr
; /* Current address */
241 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
244 * See if the hostname maps to the same IP address...
247 for (addr
= addrlist
; addr
; addr
= addr
->next
)
248 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
254 httpAddrFreeList(addrlist
);
259 * Can't have a hostname that doesn't resolve to the same IP address
260 * with double-lookups enabled...
263 httpClose(con
->http
);
265 cupsdLogClient(con
, CUPSD_LOG_WARN
,
266 "IP lookup failed - connection from %s closed!",
267 httpGetHostname(con
->http
, NULL
, 0));
275 * See if the connection is denied by TCP wrappers...
278 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
282 if (!hosts_access(&wrap_req
))
284 httpClose(con
->http
);
286 cupsdLogClient(con
, CUPSD_LOG_WARN
,
287 "Connection from %s refused by /etc/hosts.allow and "
288 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
292 #endif /* HAVE_TCPD_H */
295 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
298 socklen_t peersize
; /* Size of peer credentials */
299 pid_t peerpid
; /* Peer process ID */
300 char peername
[256]; /* Name of process */
302 peersize
= sizeof(peerpid
);
303 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
306 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
307 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
308 "Accepted from %s (Domain ???[%d])",
309 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
311 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
312 "Accepted from %s (Domain %s[%d])",
313 httpGetHostname(con
->http
, NULL
, 0), name
, (int)peerpid
);
316 # endif /* __APPLE__ */
318 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
319 httpGetHostname(con
->http
, NULL
, 0));
322 #endif /* AF_LOCAL */
323 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
324 httpGetHostname(con
->http
, NULL
, 0),
325 httpAddrPort(httpGetAddress(con
->http
)),
326 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
329 * Get the local address the client connected to...
332 addrlen
= sizeof(temp
);
333 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
335 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
338 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
339 con
->serverport
= LocalPort
;
342 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
344 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
345 con
->serverport
= LocalPort
;
347 #endif /* AF_LOCAL */
350 if (httpAddrLocalhost(&temp
))
351 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
352 else if (HostNameLookups
)
353 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
355 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
357 con
->serverport
= httpAddrPort(&(lis
->address
));
361 * Add the connection to the array of active clients...
364 cupsArrayAdd(Clients
, con
);
367 * Add the socket to the server select.
370 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
373 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
376 * Temporarily suspend accept()'s until we lose a client...
379 if (cupsArrayCount(Clients
) == MaxClients
)
380 cupsdPauseListening();
384 * See if we are connecting on a secure port...
387 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
390 * https connection; go secure...
393 if (!cupsdStartTLS(con
))
394 cupsdCloseClient(con
);
398 #endif /* HAVE_SSL */
403 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
407 cupsdCloseAllClients(void)
409 cupsd_client_t
*con
; /* Current client */
412 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
413 cupsArrayCount(Clients
));
415 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
417 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
418 if (cupsdCloseClient(con
))
419 cupsdCloseClient(con
);
424 * 'cupsdCloseClient()' - Close a remote client.
427 int /* O - 1 if partial close, 0 if fully closed */
428 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
430 int partial
; /* Do partial close for SSL? */
432 #elif defined(HAVE_GNUTLS)
433 # elif defined(HAVE_CDSASSL)
434 #endif /* HAVE_LIBSSL */
437 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
440 * Flush pending writes before closing...
443 httpFlushWrite(con
->http
);
447 if (con
->pipe_pid
!= 0)
450 * Stop any CGI process...
453 cupsdEndProcess(con
->pipe_pid
, 1);
459 cupsdRemoveSelect(con
->file
);
466 * Close the socket and clear the file from the input set for select()...
469 if (httpGetFd(con
->http
) >= 0)
471 cupsArrayRemove(ActiveClients
, con
);
476 * Shutdown encryption as needed...
479 if (httpIsEncrypted(con
->http
))
481 #endif /* HAVE_SSL */
486 * Only do a partial close so that the encrypted client gets everything.
489 httpShutdown(con
->http
);
490 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
493 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
498 * Shut the socket down fully...
501 cupsdRemoveSelect(httpGetFd(con
->http
));
502 httpClose(con
->http
);
513 cupsdRemoveSelect(httpGetFd(con
->http
));
515 httpClose(con
->http
);
517 cupsdClearString(&con
->filename
);
518 cupsdClearString(&con
->command
);
519 cupsdClearString(&con
->options
);
520 cupsdClearString(&con
->query_string
);
524 ippDelete(con
->request
);
530 ippDelete(con
->response
);
531 con
->response
= NULL
;
536 cupsLangFree(con
->language
);
537 con
->language
= NULL
;
540 #ifdef HAVE_AUTHORIZATION_H
543 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
546 #endif /* HAVE_AUTHORIZATION_H */
549 * Re-enable new client connections if we are going back under the
553 if (cupsArrayCount(Clients
) == MaxClients
)
554 cupsdResumeListening();
557 * Compact the list of clients as necessary...
560 cupsArrayRemove(Clients
, con
);
571 * 'cupsdFlushHeader()' - Flush the header fields to the client.
574 int /* I - Bytes written or -1 on error */
575 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
577 int bytes
= httpFlushWrite(con
->http
);
579 // TODO: Need to use httpSendResponse
580 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
588 * 'cupsdReadClient()' - Read data from a client.
592 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
594 char line
[32768], /* Line from client... */
595 operation
[64], /* Operation code from socket */
596 locale
[64], /* Locale */
597 *ptr
; /* Pointer into strings */
598 http_status_t status
; /* Transfer status */
599 ipp_state_t ipp_state
; /* State of IPP transfer */
600 int bytes
; /* Number of bytes to POST */
601 char *filename
; /* Name of file for GET/HEAD */
602 char buf
[1024]; /* Buffer for real filename */
603 struct stat filestats
; /* File information */
604 mime_type_t
*type
; /* MIME type of file */
605 cupsd_printer_t
*p
; /* Printer */
606 static unsigned request_id
= 0; /* Request ID for temp files */
609 status
= HTTP_STATUS_CONTINUE
;
611 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
616 "data_encoding=HTTP_ENCODING_%s, "
617 "data_remaining=" CUPS_LLFMT
", "
620 httpError(con
->http
), (int)httpGetReady(con
->http
),
621 httpStateString(httpGetState(con
->http
)),
622 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
623 CUPS_LLCAST
httpGetRemaining(con
->http
),
625 con
->request
? ipp_states
[con
->request
->state
] : "",
632 * Automatically check for a SSL/TLS handshake...
637 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
638 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
641 * Encrypt this connection...
644 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
645 "Saw first byte %02X, auto-negotiating "
646 "SSL/TLS session.", buf
[0] & 255);
648 if (!cupsdStartTLS(con
))
649 cupsdCloseClient(con
);
654 #endif /* HAVE_SSL */
656 switch (httpGetState(con
->http
))
658 case HTTP_STATE_WAITING
:
660 * See if we've received a request line...
663 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
664 if (con
->operation
== HTTP_STATE_ERROR
||
665 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
666 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
668 if (httpError(con
->http
))
669 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
670 "HTTP_STATE_WAITING Closing for error %d (%s)",
671 httpError(con
->http
), strerror(httpError(con
->http
)));
673 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
674 "HTTP_STATE_WAITING Closing on error: %s",
675 cupsLastErrorString());
677 cupsdCloseClient(con
);
682 * Ignore blank request lines...
685 if (con
->operation
== HTTP_STATE_WAITING
)
689 * Clear other state variables...
696 con
->username
[0] = '\0';
697 con
->password
[0] = '\0';
699 cupsdClearString(&con
->command
);
700 cupsdClearString(&con
->options
);
701 cupsdClearString(&con
->query_string
);
705 ippDelete(con
->request
);
711 ippDelete(con
->response
);
712 con
->response
= NULL
;
717 cupsLangFree(con
->language
);
718 con
->language
= NULL
;
724 #endif /* HAVE_GSSAPI */
727 * Handle full URLs in the request line...
730 if (strcmp(con
->uri
, "*"))
732 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
733 userpass
[HTTP_MAX_URI
], /* Username:password */
734 hostname
[HTTP_MAX_URI
], /* Hostname */
735 resource
[HTTP_MAX_URI
]; /* Resource path */
736 int port
; /* Port number */
739 * Separate the URI into its components...
742 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
743 scheme
, sizeof(scheme
),
744 userpass
, sizeof(userpass
),
745 hostname
, sizeof(hostname
), &port
,
746 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
748 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
750 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
751 cupsdCloseClient(con
);
756 * Only allow URIs with the servername, localhost, or an IP
760 if (strcmp(scheme
, "file") &&
761 _cups_strcasecmp(hostname
, ServerName
) &&
762 _cups_strcasecmp(hostname
, "localhost") &&
763 !cupsArrayFind(ServerAlias
, hostname
) &&
764 !isdigit(hostname
[0]) && hostname
[0] != '[')
767 * Nope, we don't do proxies...
770 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
772 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
773 cupsdCloseClient(con
);
778 * Copy the resource portion back into the URI; both resource and
779 * con->uri are HTTP_MAX_URI bytes in size...
782 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
786 * Process the request...
789 gettimeofday(&(con
->start
), NULL
);
791 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
793 httpGetVersion(con
->http
) / 100,
794 httpGetVersion(con
->http
) % 100);
796 if (!cupsArrayFind(ActiveClients
, con
))
798 cupsArrayAdd(ActiveClients
, con
);
802 case HTTP_STATE_OPTIONS
:
803 case HTTP_STATE_DELETE
:
804 case HTTP_STATE_GET
:
805 case HTTP_STATE_HEAD
:
806 case HTTP_STATE_POST
:
807 case HTTP_STATE_PUT
:
808 case HTTP_STATE_TRACE
:
810 * Parse incoming parameters until the status changes...
813 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
814 if (!httpGetReady(con
->http
))
817 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
819 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
820 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
821 "Closing for error %d (%s) while reading headers.",
822 httpError(con
->http
), strerror(httpError(con
->http
)));
824 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
825 "Closing on EOF while reading headers.");
827 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
828 cupsdCloseClient(con
);
834 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
837 * Connection closed...
840 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
841 cupsdCloseClient(con
);
844 break; /* Anti-compiler-warning-code */
848 * Handle new transfers...
851 if (status
== HTTP_STATUS_OK
)
853 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
856 * Figure out the locale from the Accept-Language and Content-Type
860 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
864 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
868 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
869 "charset=")) != NULL
)
872 * Combine language and charset, and trim any extra params in the
876 snprintf(locale
, sizeof(locale
), "%s.%s",
877 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
879 if ((ptr
= strchr(locale
, ',')) != NULL
)
883 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
884 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
886 con
->language
= cupsLangGet(locale
);
889 con
->language
= cupsLangGet(DefaultLocale
);
893 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
894 "Keep-Alive", 10) && KeepAlive
)
895 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
896 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
898 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
900 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
901 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
904 * HTTP/1.1 and higher require the "Host:" field...
907 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
909 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
910 cupsdCloseClient(con
);
914 else if (!valid_host(con
))
917 * Access to localhost must use "localhost" or the corresponding IPv4
918 * or IPv6 values in the Host: field.
921 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
922 "Request from \"%s\" using invalid Host: field \"%s\".",
923 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
925 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
927 cupsdCloseClient(con
);
931 else if (con
->operation
== HTTP_STATE_OPTIONS
)
934 * Do OPTIONS command...
937 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
939 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
941 cupsdCloseClient(con
);
946 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
947 !httpIsEncrypted(con
->http
))
951 * Do encryption stuff...
954 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
956 cupsdCloseClient(con
);
960 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
961 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
962 httpPrintf(con
->http
, "Content-Length: 0\r\n");
963 httpPrintf(con
->http
, "\r\n");
965 if (cupsdFlushHeader(con
) < 0)
967 cupsdCloseClient(con
);
971 if (!cupsdStartTLS(con
))
973 cupsdCloseClient(con
);
977 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
979 cupsdCloseClient(con
);
982 #endif /* HAVE_SSL */
985 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
987 cupsdCloseClient(con
);
991 httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
992 httpPrintf(con
->http
, "Content-Length: 0\r\n");
993 httpPrintf(con
->http
, "\r\n");
995 if (cupsdFlushHeader(con
) < 0)
997 cupsdCloseClient(con
);
1001 else if (!is_path_absolute(con
->uri
))
1004 * Protect against malicious users!
1007 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1008 "Request for non-absolute resource \"%s\".", con
->uri
);
1010 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1012 cupsdCloseClient(con
);
1018 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
1019 "Upgrade") && !httpIsEncrypted(con
->http
))
1023 * Do encryption stuff...
1026 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1029 cupsdCloseClient(con
);
1033 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1034 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1035 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1036 httpPrintf(con
->http
, "\r\n");
1038 if (cupsdFlushHeader(con
) < 0)
1040 cupsdCloseClient(con
);
1044 if (!cupsdStartTLS(con
))
1046 cupsdCloseClient(con
);
1050 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1052 cupsdCloseClient(con
);
1055 #endif /* HAVE_SSL */
1058 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1060 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1061 cupsdCloseClient(con
);
1065 if (httpGetExpect(con
->http
) &&
1066 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1068 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1071 * Send 100-continue header...
1074 if (!cupsdSendHeader(con
, HTTP_STATUS_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1076 cupsdCloseClient(con
);
1083 * Send 417-expectation-failed header...
1086 if (!cupsdSendHeader(con
, HTTP_STATUS_EXPECTATION_FAILED
, NULL
,
1089 cupsdCloseClient(con
);
1093 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1094 httpPrintf(con
->http
, "\r\n");
1096 if (cupsdFlushHeader(con
) < 0)
1098 cupsdCloseClient(con
);
1104 switch (httpGetState(con
->http
))
1106 case HTTP_STATE_GET_SEND
:
1107 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1108 !strncmp(con
->uri
, "/printers/", 10) ||
1109 !strncmp(con
->uri
, "/classes/", 9)) &&
1110 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1113 * Send PPD file - get the real printer name since printer
1114 * names are not case sensitive but filenames can be...
1117 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1119 if (!strncmp(con
->uri
, "/ppd/", 5))
1120 p
= cupsdFindPrinter(con
->uri
+ 5);
1121 else if (!strncmp(con
->uri
, "/printers/", 10))
1122 p
= cupsdFindPrinter(con
->uri
+ 10);
1125 p
= cupsdFindClass(con
->uri
+ 9);
1129 int i
; /* Looping var */
1131 for (i
= 0; i
< p
->num_printers
; i
++)
1133 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1135 char ppdname
[1024];/* PPD filename */
1137 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1138 ServerRoot
, p
->printers
[i
]->name
);
1139 if (!access(ppdname
, 0))
1147 if (i
>= p
->num_printers
)
1154 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1158 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1160 cupsdCloseClient(con
);
1167 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1168 !strncmp(con
->uri
, "/printers/", 10) ||
1169 !strncmp(con
->uri
, "/classes/", 9)) &&
1170 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1173 * Send icon file - get the real queue name since queue names are
1174 * not case sensitive but filenames can be...
1177 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1179 if (!strncmp(con
->uri
, "/icons/", 7))
1180 p
= cupsdFindPrinter(con
->uri
+ 7);
1181 else if (!strncmp(con
->uri
, "/printers/", 10))
1182 p
= cupsdFindPrinter(con
->uri
+ 10);
1185 p
= cupsdFindClass(con
->uri
+ 9);
1189 int i
; /* Looping var */
1191 for (i
= 0; i
< p
->num_printers
; i
++)
1193 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1195 char ppdname
[1024];/* PPD filename */
1197 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1198 ServerRoot
, p
->printers
[i
]->name
);
1199 if (!access(ppdname
, 0))
1207 if (i
>= p
->num_printers
)
1213 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1216 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1218 cupsdCloseClient(con
);
1225 else if (!WebInterface
)
1228 * Web interface is disabled. Show an appropriate message...
1231 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1233 cupsdCloseClient(con
);
1240 if ((!strncmp(con
->uri
, "/admin", 6) &&
1241 strncmp(con
->uri
, "/admin/conf/", 12) &&
1242 strncmp(con
->uri
, "/admin/log/", 11)) ||
1243 !strncmp(con
->uri
, "/printers", 9) ||
1244 !strncmp(con
->uri
, "/classes", 8) ||
1245 !strncmp(con
->uri
, "/help", 5) ||
1246 !strncmp(con
->uri
, "/jobs", 5))
1249 * Send CGI output...
1252 if (!strncmp(con
->uri
, "/admin", 6))
1254 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1257 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1259 else if (!strncmp(con
->uri
, "/printers", 9))
1261 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1264 if (con
->uri
[9] && con
->uri
[10])
1265 cupsdSetString(&con
->options
, con
->uri
+ 9);
1267 cupsdSetString(&con
->options
, NULL
);
1269 else if (!strncmp(con
->uri
, "/classes", 8))
1271 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1274 if (con
->uri
[8] && con
->uri
[9])
1275 cupsdSetString(&con
->options
, con
->uri
+ 8);
1277 cupsdSetString(&con
->options
, NULL
);
1279 else if (!strncmp(con
->uri
, "/jobs", 5))
1281 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1284 if (con
->uri
[5] && con
->uri
[6])
1285 cupsdSetString(&con
->options
, con
->uri
+ 5);
1287 cupsdSetString(&con
->options
, NULL
);
1291 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1294 if (con
->uri
[5] && con
->uri
[6])
1295 cupsdSetString(&con
->options
, con
->uri
+ 5);
1297 cupsdSetString(&con
->options
, NULL
);
1300 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1302 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1304 cupsdCloseClient(con
);
1309 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1311 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1312 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1314 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1315 (strchr(con
->uri
+ 12, '/') ||
1316 strlen(con
->uri
) == 12)) ||
1317 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1318 (strchr(con
->uri
+ 11, '/') ||
1319 strlen(con
->uri
) == 11)))
1322 * GET can only be done to configuration files directly under
1326 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1327 "Request for subdirectory \"%s\"!", con
->uri
);
1329 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1331 cupsdCloseClient(con
);
1343 if ((filename
= get_file(con
, &filestats
, buf
,
1344 sizeof(buf
))) == NULL
)
1346 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1348 cupsdCloseClient(con
);
1355 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1357 if (is_cgi(con
, filename
, &filestats
, type
))
1360 * Note: con->command and con->options were set by
1364 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1366 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1368 cupsdCloseClient(con
);
1373 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1375 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1376 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1380 if (!check_if_modified(con
, &filestats
))
1382 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1384 cupsdCloseClient(con
);
1391 strlcpy(line
, "text/plain", sizeof(line
));
1393 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1395 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1397 cupsdCloseClient(con
);
1404 case HTTP_STATE_POST_RECV
:
1406 * See if the POST request includes a Content-Length field, and if
1407 * so check the length against any limits that are set...
1410 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1411 MaxRequestSize
> 0 &&
1412 httpGetLength2(con
->http
) > MaxRequestSize
)
1415 * Request too large...
1418 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1420 cupsdCloseClient(con
);
1426 else if (httpGetLength2(con
->http
) < 0)
1429 * Negative content lengths are invalid!
1432 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1434 cupsdCloseClient(con
);
1442 * See what kind of POST request this is; for IPP requests the
1443 * content-type field will be "application/ipp"...
1446 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1448 con
->request
= ippNew();
1449 else if (!WebInterface
)
1452 * Web interface is disabled. Show an appropriate message...
1455 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1457 cupsdCloseClient(con
);
1463 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1464 strncmp(con
->uri
, "/admin/conf/", 12) &&
1465 strncmp(con
->uri
, "/admin/log/", 11)) ||
1466 !strncmp(con
->uri
, "/printers", 9) ||
1467 !strncmp(con
->uri
, "/classes", 8) ||
1468 !strncmp(con
->uri
, "/help", 5) ||
1469 !strncmp(con
->uri
, "/jobs", 5))
1475 if (!strncmp(con
->uri
, "/admin", 6))
1477 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1480 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1482 else if (!strncmp(con
->uri
, "/printers", 9))
1484 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1487 if (con
->uri
[9] && con
->uri
[10])
1488 cupsdSetString(&con
->options
, con
->uri
+ 9);
1490 cupsdSetString(&con
->options
, NULL
);
1492 else if (!strncmp(con
->uri
, "/classes", 8))
1494 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1497 if (con
->uri
[8] && con
->uri
[9])
1498 cupsdSetString(&con
->options
, con
->uri
+ 8);
1500 cupsdSetString(&con
->options
, NULL
);
1502 else if (!strncmp(con
->uri
, "/jobs", 5))
1504 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1507 if (con
->uri
[5] && con
->uri
[6])
1508 cupsdSetString(&con
->options
, con
->uri
+ 5);
1510 cupsdSetString(&con
->options
, NULL
);
1514 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1517 if (con
->uri
[5] && con
->uri
[6])
1518 cupsdSetString(&con
->options
, con
->uri
+ 5);
1520 cupsdSetString(&con
->options
, NULL
);
1523 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1524 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1532 if ((filename
= get_file(con
, &filestats
, buf
,
1533 sizeof(buf
))) == NULL
)
1535 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1537 cupsdCloseClient(con
);
1544 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1546 if (!is_cgi(con
, filename
, &filestats
, type
))
1549 * Only POST to CGI's...
1552 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1554 cupsdCloseClient(con
);
1561 case HTTP_STATE_PUT_RECV
:
1563 * Validate the resource name...
1566 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1569 * PUT can only be done to the cupsd.conf file...
1572 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1573 "Disallowed PUT request for \"%s\".", con
->uri
);
1575 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1577 cupsdCloseClient(con
);
1585 * See if the PUT request includes a Content-Length field, and if
1586 * so check the length against any limits that are set...
1589 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1590 MaxRequestSize
> 0 &&
1591 httpGetLength2(con
->http
) > MaxRequestSize
)
1594 * Request too large...
1597 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1599 cupsdCloseClient(con
);
1605 else if (httpGetLength2(con
->http
) < 0)
1608 * Negative content lengths are invalid!
1611 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1613 cupsdCloseClient(con
);
1621 * Open a temporary file to hold the request...
1624 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1626 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1630 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1631 "Unable to create request file \"%s\": %s",
1632 con
->filename
, strerror(errno
));
1634 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1636 cupsdCloseClient(con
);
1641 fchmod(con
->file
, 0640);
1642 fchown(con
->file
, RunUser
, Group
);
1643 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1646 case HTTP_STATE_DELETE
:
1647 case HTTP_STATE_TRACE
:
1648 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1649 cupsdCloseClient(con
);
1652 case HTTP_STATE_HEAD
:
1653 if (!strncmp(con
->uri
, "/printers/", 10) &&
1654 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1657 * Send PPD file - get the real printer name since printer
1658 * names are not case sensitive but filenames can be...
1661 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1663 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1664 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1667 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1669 cupsdCloseClient(con
);
1676 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1677 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1680 * Send PNG file - get the real printer name since printer
1681 * names are not case sensitive but filenames can be...
1684 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1686 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1687 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1690 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1692 cupsdCloseClient(con
);
1699 else if (!WebInterface
)
1701 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1703 cupsdCloseClient(con
);
1707 if (httpPrintf(con
->http
, "\r\n") < 0)
1709 cupsdCloseClient(con
);
1713 if (cupsdFlushHeader(con
) < 0)
1715 cupsdCloseClient(con
);
1719 // con->http->state = HTTP_STATE_WAITING;
1720 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1725 if ((!strncmp(con
->uri
, "/admin", 6) &&
1726 strncmp(con
->uri
, "/admin/conf/", 12) &&
1727 strncmp(con
->uri
, "/admin/log/", 11)) ||
1728 !strncmp(con
->uri
, "/printers", 9) ||
1729 !strncmp(con
->uri
, "/classes", 8) ||
1730 !strncmp(con
->uri
, "/help", 5) ||
1731 !strncmp(con
->uri
, "/jobs", 5))
1737 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1739 cupsdCloseClient(con
);
1743 if (httpPrintf(con
->http
, "\r\n") < 0)
1745 cupsdCloseClient(con
);
1749 if (cupsdFlushHeader(con
) < 0)
1751 cupsdCloseClient(con
);
1755 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1757 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1758 (strchr(con
->uri
+ 12, '/') ||
1759 strlen(con
->uri
) == 12)) ||
1760 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1761 (strchr(con
->uri
+ 11, '/') ||
1762 strlen(con
->uri
) == 11)))
1765 * HEAD can only be done to configuration files under
1769 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1770 "Request for subdirectory \"%s\".", con
->uri
);
1772 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1774 cupsdCloseClient(con
);
1780 else if ((filename
= get_file(con
, &filestats
, buf
,
1781 sizeof(buf
))) == NULL
)
1783 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1786 cupsdCloseClient(con
);
1790 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1792 else if (!check_if_modified(con
, &filestats
))
1794 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1796 cupsdCloseClient(con
);
1800 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1808 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1810 strlcpy(line
, "text/plain", sizeof(line
));
1812 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1814 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1816 cupsdCloseClient(con
);
1820 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
1821 httpGetDateString(filestats
.st_mtime
)) < 0)
1823 cupsdCloseClient(con
);
1827 if (httpPrintf(con
->http
, "Content-Length: %lu\r\n",
1828 (unsigned long)filestats
.st_size
) < 0)
1830 cupsdCloseClient(con
);
1834 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1837 if (httpPrintf(con
->http
, "\r\n") < 0)
1839 cupsdCloseClient(con
);
1843 if (cupsdFlushHeader(con
) < 0)
1845 cupsdCloseClient(con
);
1849 // con->http->state = HTTP_STATE_WAITING;
1850 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1855 break; /* Anti-compiler-warning-code */
1861 * Handle any incoming data...
1864 switch (httpGetState(con
->http
))
1866 case HTTP_STATE_PUT_RECV
:
1869 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1871 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1872 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1873 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1874 httpError(con
->http
), strerror(httpError(con
->http
)));
1876 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1877 "HTTP_STATE_PUT_RECV Closing on EOF.");
1879 cupsdCloseClient(con
);
1884 con
->bytes
+= bytes
;
1886 if (write(con
->file
, line
, bytes
) < bytes
)
1888 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1889 "Unable to write %d bytes to \"%s\": %s", bytes
,
1890 con
->filename
, strerror(errno
));
1894 unlink(con
->filename
);
1895 cupsdClearString(&con
->filename
);
1897 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1899 cupsdCloseClient(con
);
1905 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1907 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1910 * End of file, see how big it is...
1913 fstat(con
->file
, &filestats
);
1918 if (filestats
.st_size
> MaxRequestSize
&&
1922 * Request is too big; remove it and send an error...
1925 unlink(con
->filename
);
1926 cupsdClearString(&con
->filename
);
1928 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1930 cupsdCloseClient(con
);
1936 * Install the configuration file...
1939 status
= install_cupsd_conf(con
);
1942 * Return the status to the client...
1945 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1947 cupsdCloseClient(con
);
1953 case HTTP_STATE_POST_RECV
:
1956 if (con
->request
&& con
->file
< 0)
1959 * Grab any request data from the connection...
1962 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1964 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1965 cupsLastErrorString());
1967 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1968 cupsdCloseClient(con
);
1971 else if (ipp_state
!= IPP_STATE_DATA
)
1973 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1975 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1976 cupsdCloseClient(con
);
1980 if (httpGetReady(con
->http
))
1986 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1987 con
->request
->request
.op
.version
[0],
1988 con
->request
->request
.op
.version
[1],
1989 ippOpString(con
->request
->request
.op
.operation_id
),
1990 con
->request
->request
.op
.request_id
);
1991 con
->bytes
+= ippLength(con
->request
);
1995 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1998 * Create a file as needed for the request data...
2001 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2003 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2007 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2008 "Unable to create request file \"%s\": %s",
2009 con
->filename
, strerror(errno
));
2011 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2013 cupsdCloseClient(con
);
2018 fchmod(con
->file
, 0640);
2019 fchown(con
->file
, RunUser
, Group
);
2020 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2023 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2025 if (!httpWait(con
->http
, 0))
2027 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
2029 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
2030 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2031 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
2032 httpError(con
->http
), strerror(httpError(con
->http
)));
2034 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2035 "HTTP_STATE_POST_SEND Closing on EOF.");
2037 cupsdCloseClient(con
);
2042 con
->bytes
+= bytes
;
2044 if (write(con
->file
, line
, bytes
) < bytes
)
2046 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2047 "Unable to write %d bytes to \"%s\": %s",
2048 bytes
, con
->filename
, strerror(errno
));
2052 unlink(con
->filename
);
2053 cupsdClearString(&con
->filename
);
2055 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
2058 cupsdCloseClient(con
);
2063 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
2065 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2067 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2068 "Closing on unexpected state %s.",
2069 httpStateString(httpGetState(con
->http
)));
2070 cupsdCloseClient(con
);
2075 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
2077 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2081 fstat(con
->file
, &filestats
);
2086 if (filestats
.st_size
> MaxRequestSize
&&
2090 * Request is too big; remove it and send an error...
2093 unlink(con
->filename
);
2094 cupsdClearString(&con
->filename
);
2099 * Delete any IPP request data...
2102 ippDelete(con
->request
);
2103 con
->request
= NULL
;
2106 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2108 cupsdCloseClient(con
);
2112 else if (filestats
.st_size
== 0)
2115 * Don't allow empty file...
2118 unlink(con
->filename
);
2119 cupsdClearString(&con
->filename
);
2124 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2126 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2128 cupsdCloseClient(con
);
2133 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2139 cupsdProcessIPPRequest(con
);
2143 unlink(con
->filename
);
2144 cupsdClearString(&con
->filename
);
2153 break; /* Anti-compiler-warning-code */
2156 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2158 if (!httpGetKeepAlive(con
->http
))
2160 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2161 "Closing because Keep-Alive is disabled.");
2162 cupsdCloseClient(con
);
2166 cupsArrayRemove(ActiveClients
, con
);
2167 cupsdSetBusyState();
2174 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2177 int /* O - 1 on success, 0 on failure */
2179 cupsd_client_t
*con
, /* I - Client connection */
2180 char *command
, /* I - Command to run */
2181 char *options
, /* I - Command-line options */
2182 int root
) /* I - Run as root? */
2184 int fd
; /* Standard input file descriptor */
2189 fd
= open(con
->filename
, O_RDONLY
);
2193 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2194 "Unable to open \"%s\" for reading: %s",
2195 con
->filename
? con
->filename
: "/dev/null",
2200 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2205 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2210 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2211 command
, con
->pipe_pid
, con
->file
);
2213 if (con
->pipe_pid
== 0)
2216 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2218 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2220 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2222 con
->sent_header
= 0;
2223 con
->file_ready
= 0;
2224 con
->got_fields
= 0;
2225 con
->header_used
= 0;
2232 * 'cupsdSendError()' - Send an error message via HTTP.
2235 int /* O - 1 if successful, 0 otherwise */
2236 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2237 http_status_t code
, /* I - Error code */
2238 int auth_type
)/* I - Authentication type */
2240 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2245 * Force client to upgrade for authentication if that is how the
2246 * server is configured...
2249 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2250 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2251 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2252 !httpIsEncrypted(con
->http
))
2254 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2256 #endif /* HAVE_SSL */
2259 * Put the request in the access_log file...
2262 cupsdLogRequest(con
, code
);
2265 * To work around bugs in some proxies, don't use Keep-Alive for some
2268 * Kerberos authentication doesn't work without Keep-Alive, so
2269 * never disable it in that case.
2272 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2273 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2276 * Send an error message back to the client. If the error code is a
2277 * 400 or 500 series, make sure the message contains some text, too!
2280 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2284 if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2285 if (httpPrintf(con
->http
, "Connection: Upgrade\r\n") < 0)
2288 if (httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2290 #endif /* HAVE_SSL */
2292 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2293 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2295 if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2299 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2302 * Send a human-readable error message.
2305 char message
[4096], /* Message for user */
2306 urltext
[1024], /* URL redirection text */
2307 redirect
[1024]; /* Redirection link */
2308 const char *text
; /* Status-specific text */
2313 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2314 text
= _cupsLangString(con
->language
,
2315 _("Enter your username and password or the "
2316 "root username and password to access this "
2317 "page. If you are using Kerberos authentication, "
2318 "make sure you have a valid Kerberos ticket."));
2319 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2323 snprintf(urltext
, sizeof(urltext
),
2324 _cupsLangString(con
->language
,
2325 _("You must access this page using the URL "
2326 "<A HREF=\"https://%s:%d%s\">"
2327 "https://%s:%d%s</A>.")),
2328 con
->servername
, con
->serverport
, con
->uri
,
2329 con
->servername
, con
->serverport
, con
->uri
);
2331 snprintf(redirect
, sizeof(redirect
),
2332 "<META HTTP-EQUIV=\"Refresh\" "
2333 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2334 con
->servername
, con
->serverport
, con
->uri
);
2336 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2337 text
= _cupsLangString(con
->language
,
2338 _("The web interface is currently disabled. Run "
2339 "\"cupsctl WebInterface=yes\" to enable it."));
2343 snprintf(message
, sizeof(message
),
2344 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2345 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2348 "\t<META HTTP-EQUIV=\"Content-Type\" "
2349 "CONTENT=\"text/html; charset=utf-8\">\n"
2350 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2351 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2352 "HREF=\"/cups.css\">\n"
2360 _httpStatus(con
->language
, code
), redirect
,
2361 _httpStatus(con
->language
, code
), text
);
2363 if (httpPrintf(con
->http
, "Content-Type: text/html; charset=utf-8\r\n") < 0)
2365 if (httpPrintf(con
->http
, "Content-Length: %d\r\n",
2366 (int)strlen(message
)) < 0)
2368 if (httpPrintf(con
->http
, "\r\n") < 0)
2370 if (httpPrintf(con
->http
, "%s", message
) < 0)
2373 else if (httpPrintf(con
->http
, "\r\n") < 0)
2376 if (cupsdFlushHeader(con
) < 0)
2379 // con->http->state = HTTP_STATE_WAITING;
2381 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2388 * 'cupsdSendHeader()' - Send an HTTP request.
2391 int /* O - 1 on success, 0 on failure */
2393 cupsd_client_t
*con
, /* I - Client to send to */
2394 http_status_t code
, /* I - HTTP status code */
2395 char *type
, /* I - MIME type of document */
2396 int auth_type
) /* I - Type of authentication */
2398 char auth_str
[1024]; /* Authorization string */
2402 * Send the HTTP status header...
2405 if (code
== HTTP_STATUS_CONTINUE
)
2408 * 100-continue doesn't send any headers...
2411 return (httpPrintf(con
->http
, "HTTP/%d.%d 100 Continue\r\n\r\n",
2412 httpGetVersion(con
->http
) / 100,
2413 httpGetVersion(con
->http
) % 100) > 0);
2415 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2418 * Treat our special "web interface is disabled" status as "200 OK" for web
2422 code
= HTTP_STATUS_OK
;
2425 httpFlushWrite(con
->http
);
2427 // con->http->data_encoding = HTTP_ENCODING_FIELDS;
2429 if (httpPrintf(con
->http
, "HTTP/%d.%d %d %s\r\n", httpGetVersion(con
->http
) / 100,
2430 httpGetVersion(con
->http
) % 100, code
, httpStatus(code
)) < 0)
2432 if (httpPrintf(con
->http
, "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2435 if (httpPrintf(con
->http
, "Server: %s\r\n", ServerHeader
) < 0)
2437 if (httpGetKeepAlive(con
->http
) && httpGetVersion(con
->http
) >= HTTP_VERSION_1_0
)
2439 if (httpPrintf(con
->http
, "Connection: Keep-Alive\r\n") < 0)
2441 if (httpPrintf(con
->http
, "Keep-Alive: timeout=%d\r\n",
2442 KeepAliveTimeout
) < 0)
2445 else if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2448 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2449 if (httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2452 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2454 if (auth_type
== CUPSD_AUTH_NONE
)
2456 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2457 auth_type
= cupsdDefaultAuthType();
2459 auth_type
= con
->best
->type
;
2464 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2465 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2466 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2467 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2468 httpGetHostname(con
->http
, NULL
, 0));
2470 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2473 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2474 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2476 # endif /* AF_LOCAL */
2477 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2479 #endif /* HAVE_GSSAPI */
2481 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2482 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2485 * Add a "trc" (try root certification) parameter for local non-Kerberos
2486 * requests when the request requires system group membership - then the
2487 * client knows the root certificate can/should be used.
2489 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2490 * parameter as needed...
2493 char *name
, /* Current user name */
2494 *auth_key
; /* Auth key buffer */
2495 size_t auth_size
; /* Size of remaining buffer */
2497 auth_key
= auth_str
+ strlen(auth_str
);
2498 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2500 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2502 name
= (char *)cupsArrayNext(con
->best
->names
))
2504 #ifdef HAVE_AUTHORIZATION_H
2505 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2507 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2508 /* end parenthesis is stripped in conf.c */
2512 #endif /* HAVE_AUTHORIZATION_H */
2513 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2515 #ifdef HAVE_AUTHORIZATION_H
2516 if (SystemGroupAuthKey
)
2517 snprintf(auth_key
, auth_size
,
2519 SystemGroupAuthKey
);
2522 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2523 #endif /* HAVE_AUTHORIZATION_H */
2531 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2533 if (httpPrintf(con
->http
, "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2538 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2540 if (httpPrintf(con
->http
, "Content-Language: %s\r\n",
2541 con
->language
->language
) < 0)
2547 if (!strcmp(type
, "text/html"))
2549 if (httpPrintf(con
->http
,
2550 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2553 else if (httpPrintf(con
->http
, "Content-Type: %s\r\n", type
) < 0)
2562 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2566 cupsdUpdateCGI(void)
2568 char *ptr
, /* Pointer to end of line in buffer */
2569 message
[1024]; /* Pointer to message text */
2570 int loglevel
; /* Log level for message */
2573 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2574 message
, sizeof(message
))) != NULL
)
2576 if (loglevel
== CUPSD_LOG_INFO
)
2577 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2579 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2583 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2586 * Fatal error on pipe - should never happen!
2589 cupsdLogMessage(CUPSD_LOG_CRIT
,
2590 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2597 * 'cupsdWriteClient()' - Write data to a client as needed.
2601 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2603 int bytes
, /* Number of bytes written */
2604 field_col
; /* Current column */
2605 char *bufptr
, /* Pointer into buffer */
2606 *bufend
; /* Pointer to end of buffer */
2607 ipp_state_t ipp_state
; /* IPP state value */
2610 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2611 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2616 "data_encoding=HTTP_ENCODING_%s, "
2617 "data_remaining=" CUPS_LLFMT
", "
2621 httpError(con
->http
), (int)httpGetReady(con
->http
),
2622 httpStateString(httpGetState(con
->http
)),
2623 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2624 CUPS_LLCAST
httpGetLength2(con
->http
),
2626 con
->response
? ipp_states
[con
->response
->state
] : "",
2627 con
->pipe_pid
, con
->file
);
2629 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2630 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2633 * If we get called in the wrong state, then something went wrong with the
2634 * connection and we need to shut it down...
2637 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP state %s.",
2638 httpStateString(httpGetState(con
->http
)));
2639 cupsdCloseClient(con
);
2646 * Make sure we select on the CGI output...
2649 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2651 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2653 if (!con
->file_ready
)
2656 * Try again later when there is CGI output available...
2659 cupsdRemoveSelect(httpGetFd(con
->http
));
2663 con
->file_ready
= 0;
2666 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2668 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2673 * Write a single attribute or the IPP message header...
2676 ipp_state
= ippWrite(con
->http
, con
->response
);
2679 * If the write buffer has been flushed, stop buffering up attributes...
2682 if (httpGetPending(con
->http
) <= wused
)
2685 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2687 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2688 "Writing IPP response, ipp_state=%s, old "
2689 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2690 ippStateString(ipp_state
),
2691 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2693 if (httpGetPending(con
->http
) > 0)
2694 httpFlushWrite(con
->http
);
2696 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2697 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2699 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2700 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2701 (int)bytes
, httpGetState(con
->http
),
2702 CUPS_LLCAST
httpGetLength2(con
->http
));
2704 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2705 sizeof(con
->header
) - con
->header_used
)) > 0)
2707 con
->header_used
+= bytes
;
2709 if (con
->pipe_pid
&& !con
->got_fields
)
2712 * Inspect the data for Content-Type and other fields.
2715 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2717 !con
->got_fields
&& bufptr
< bufend
;
2720 if (*bufptr
== '\n')
2723 * Send line to client...
2726 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2730 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2732 if (!con
->sent_header
)
2735 * Handle redirection and CGI status codes...
2738 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2740 if (!cupsdSendHeader(con
, HTTP_STATUS_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2742 cupsdCloseClient(con
);
2746 con
->sent_header
= 2;
2748 if (httpPrintf(con
->http
, "Content-Length: 0\r\n") < 0)
2751 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2753 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2755 con
->sent_header
= 2;
2759 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
2761 cupsdCloseClient(con
);
2765 con
->sent_header
= 1;
2767 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
2769 if (httpPrintf(con
->http
, "Transfer-Encoding: chunked\r\n") < 0)
2775 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2776 httpPrintf(con
->http
, "%s\r\n", con
->header
);
2782 con
->header_used
-= bufptr
- con
->header
;
2784 if (con
->header_used
> 0)
2785 memmove(con
->header
, bufptr
, con
->header_used
);
2787 bufptr
= con
->header
- 1;
2790 * See if the line was empty...
2795 con
->got_fields
= 1;
2797 if (cupsdFlushHeader(con
) < 0)
2799 cupsdCloseClient(con
);
2803 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
2804 httpSetLength(con
->http
, 0);
2805 // con->http->data_encoding = HTTP_ENCODING_CHUNKED;
2810 else if (*bufptr
!= '\r')
2814 if (!con
->got_fields
)
2816 // con->http->activity = time(NULL);
2821 if (con
->header_used
> 0)
2823 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2825 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2826 httpError(con
->http
), strerror(httpError(con
->http
)));
2827 cupsdCloseClient(con
);
2831 if (httpIsChunked(con
->http
))
2832 httpFlushWrite(con
->http
);
2834 con
->bytes
+= con
->header_used
;
2836 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2839 bytes
= con
->header_used
;
2841 con
->header_used
= 0;
2846 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2847 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2849 if (!con
->sent_header
&& con
->pipe_pid
)
2850 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2853 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2855 httpFlushWrite(con
->http
);
2857 if (httpIsChunked(con
->http
) && con
->sent_header
== 1)
2859 if (httpWrite2(con
->http
, "", 0) < 0)
2861 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2862 httpError(con
->http
), strerror(httpError(con
->http
)));
2863 cupsdCloseClient(con
);
2869 // con->http->state = HTTP_STATE_WAITING;
2871 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2873 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2877 cupsdRemoveSelect(con
->file
);
2880 cupsdEndProcess(con
->pipe_pid
, 0);
2889 unlink(con
->filename
);
2890 cupsdClearString(&con
->filename
);
2895 ippDelete(con
->request
);
2896 con
->request
= NULL
;
2901 ippDelete(con
->response
);
2902 con
->response
= NULL
;
2905 cupsdClearString(&con
->command
);
2906 cupsdClearString(&con
->options
);
2907 cupsdClearString(&con
->query_string
);
2909 if (!httpGetKeepAlive(con
->http
))
2911 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2912 "Closing because Keep-Alive is disabled.");
2913 cupsdCloseClient(con
);
2918 cupsArrayRemove(ActiveClients
, con
);
2919 cupsdSetBusyState();
2923 // con->http->activity = time(NULL);
2928 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2931 static int /* O - 1 if modified since */
2933 cupsd_client_t
*con
, /* I - Client connection */
2934 struct stat
*filestats
) /* I - File information */
2936 const char *ptr
; /* Pointer into field */
2937 time_t date
; /* Time/date value */
2938 off_t size
; /* Size/length value */
2943 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2948 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2949 "check_if_modified "
2950 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2951 filestats
, CUPS_LLCAST filestats
->st_size
,
2952 (int)filestats
->st_mtime
, ptr
);
2954 while (*ptr
!= '\0')
2956 while (isspace(*ptr
) || *ptr
== ';')
2959 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2962 size
= strtoll(ptr
, NULL
, 10);
2964 while (isdigit(*ptr
))
2967 else if (isalpha(*ptr
))
2969 date
= httpGetDateTime(ptr
);
2970 while (*ptr
!= '\0' && *ptr
!= ';')
2977 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2978 (date
< filestats
->st_mtime
&& date
!= 0) ||
2979 (size
== 0 && date
== 0));
2984 * 'compare_clients()' - Compare two client connections.
2987 static int /* O - Result of comparison */
2988 compare_clients(cupsd_client_t
*a
, /* I - First client */
2989 cupsd_client_t
*b
, /* I - Second client */
2990 void *data
) /* I - User data (not used) */
3004 * 'get_file()' - Get a filename and state info.
3007 static char * /* O - Real filename */
3008 get_file(cupsd_client_t
*con
, /* I - Client connection */
3009 struct stat
*filestats
, /* O - File information */
3010 char *filename
, /* IO - Filename buffer */
3011 int len
) /* I - Buffer length */
3013 int status
; /* Status of filesystem calls */
3014 char *ptr
; /* Pointer info filename */
3015 int plen
; /* Remaining length after pointer */
3016 char language
[7]; /* Language subdirectory, if any */
3020 * Figure out the real filename...
3025 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3026 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3027 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3029 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3030 if (access(filename
, F_OK
) < 0)
3031 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3033 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3034 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3035 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3036 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3037 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3039 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3040 strlcpy(filename
, AccessLog
, len
);
3041 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3042 strlcpy(filename
, ErrorLog
, len
);
3043 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3044 strlcpy(filename
, PageLog
, len
);
3048 else if (con
->language
)
3050 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3051 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3054 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3056 if ((ptr
= strchr(filename
, '?')) != NULL
)
3060 * Grab the status for this language; if there isn't a language-specific file
3061 * then fallback to the default one...
3064 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3065 strncmp(con
->uri
, "/icons/", 7) &&
3066 strncmp(con
->uri
, "/ppd/", 5) &&
3067 strncmp(con
->uri
, "/rss/", 5) &&
3068 strncmp(con
->uri
, "/admin/conf/", 12) &&
3069 strncmp(con
->uri
, "/admin/log/", 11))
3072 * Drop the country code...
3076 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3078 if ((ptr
= strchr(filename
, '?')) != NULL
)
3081 if ((status
= stat(filename
, filestats
)) != 0)
3084 * Drop the language prefix and try the root directory...
3088 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3090 if ((ptr
= strchr(filename
, '?')) != NULL
)
3093 status
= stat(filename
, filestats
);
3098 * If we're found a directory, get the index.html file instead...
3101 if (!status
&& S_ISDIR(filestats
->st_mode
))
3104 * Make sure the URI ends with a slash...
3107 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3108 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3111 * Find the directory index file, trying every language...
3116 if (status
&& language
[0])
3119 * Try a different language subset...
3123 language
[0] = '\0'; /* Strip country code */
3125 language
[0] = '\0'; /* Strip language */
3129 * Look for the index file...
3132 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3134 if ((ptr
= strchr(filename
, '?')) != NULL
)
3137 ptr
= filename
+ strlen(filename
);
3138 plen
= len
- (ptr
- filename
);
3140 strlcpy(ptr
, "index.html", plen
);
3141 status
= stat(filename
, filestats
);
3146 strlcpy(ptr
, "index.class", plen
);
3147 status
= stat(filename
, filestats
);
3149 #endif /* HAVE_JAVA */
3154 strlcpy(ptr
, "index.pl", plen
);
3155 status
= stat(filename
, filestats
);
3157 #endif /* HAVE_PERL */
3162 strlcpy(ptr
, "index.php", plen
);
3163 status
= stat(filename
, filestats
);
3165 #endif /* HAVE_PHP */
3170 strlcpy(ptr
, "index.pyc", plen
);
3171 status
= stat(filename
, filestats
);
3176 strlcpy(ptr
, "index.py", plen
);
3177 status
= stat(filename
, filestats
);
3179 #endif /* HAVE_PYTHON */
3182 while (status
&& language
[0]);
3185 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3186 "get_file filestats=%p, filename=%p, len=%d, "
3187 "returning \"%s\".", filestats
, filename
, len
,
3188 status
? "(null)" : filename
);
3198 * 'install_cupsd_conf()' - Install a configuration file.
3201 static http_status_t
/* O - Status */
3202 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3204 char filename
[1024]; /* Configuration filename */
3205 cups_file_t
*in
, /* Input file */
3206 *out
; /* Output file */
3207 char buffer
[16384]; /* Copy buffer */
3208 ssize_t bytes
; /* Number of bytes */
3212 * Open the request file...
3215 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3217 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3218 con
->filename
, strerror(errno
));
3219 return (HTTP_STATUS_SERVER_ERROR
);
3223 * Open the new config file...
3226 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3229 return (HTTP_STATUS_SERVER_ERROR
);
3232 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3236 * Copy from the request to the new config file...
3239 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3240 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3242 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3243 "Unable to copy to config file \"%s\": %s",
3244 ConfigurationFile
, strerror(errno
));
3249 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3250 cupsdUnlinkOrRemoveFile(filename
);
3252 return (HTTP_STATUS_SERVER_ERROR
);
3256 * Close the files...
3261 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3262 return (HTTP_STATUS_SERVER_ERROR
);
3265 * Remove the request file...
3268 cupsdUnlinkOrRemoveFile(con
->filename
);
3269 cupsdClearString(&con
->filename
);
3272 * Set the NeedReload flag...
3275 NeedReload
= RELOAD_CUPSD
;
3276 ReloadTime
= time(NULL
);
3279 * Return that the file was created successfully...
3282 return (HTTP_STATUS_CREATED
);
3287 * 'is_cgi()' - Is the resource a CGI script/program?
3290 static int /* O - 1 = CGI, 0 = file */
3291 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3292 const char *filename
, /* I - Real filename */
3293 struct stat
*filestats
, /* I - File information */
3294 mime_type_t
*type
) /* I - MIME type */
3296 const char *options
; /* Options on URL */
3300 * Get the options, if any...
3303 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3306 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3310 * Check for known types...
3313 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3315 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3316 "is_cgi filename=\"%s\", filestats=%p, "
3317 "type=%s/%s, returning 0", filename
,
3318 filestats
, type
? type
->super
: "unknown",
3319 type
? type
->type
: "unknown");
3323 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3324 (filestats
->st_mode
& 0111))
3327 * "application/x-httpd-cgi" is a CGI script.
3330 cupsdSetString(&con
->command
, filename
);
3333 cupsdSetStringf(&con
->options
, " %s", options
);
3335 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3336 "is_cgi filename=\"%s\", filestats=%p, "
3337 "type=%s/%s, returning 1", filename
,
3338 filestats
, type
->super
, type
->type
);
3342 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3345 * "application/x-httpd-java" is a Java servlet.
3348 cupsdSetString(&con
->command
, CUPS_JAVA
);
3351 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3353 cupsdSetStringf(&con
->options
, " %s", filename
);
3355 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3356 "is_cgi filename=\"%s\", filestats=%p, "
3357 "type=%s/%s, returning 1", filename
,
3358 filestats
, type
->super
, type
->type
);
3361 #endif /* HAVE_JAVA */
3363 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3366 * "application/x-httpd-perl" is a Perl page.
3369 cupsdSetString(&con
->command
, CUPS_PERL
);
3372 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3374 cupsdSetStringf(&con
->options
, " %s", filename
);
3376 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3377 "is_cgi filename=\"%s\", filestats=%p, "
3378 "type=%s/%s, returning 1", filename
,
3379 filestats
, type
->super
, type
->type
);
3382 #endif /* HAVE_PERL */
3384 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3387 * "application/x-httpd-php" is a PHP page.
3390 cupsdSetString(&con
->command
, CUPS_PHP
);
3393 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3395 cupsdSetStringf(&con
->options
, " %s", filename
);
3397 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3398 "is_cgi filename=\"%s\", filestats=%p, "
3399 "type=%s/%s, returning 1", filename
,
3400 filestats
, type
->super
, type
->type
);
3403 #endif /* HAVE_PHP */
3405 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3408 * "application/x-httpd-python" is a Python page.
3411 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3414 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3416 cupsdSetStringf(&con
->options
, " %s", filename
);
3418 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3419 "is_cgi filename=\"%s\", filestats=%p, "
3420 "type=%s/%s, returning 1", filename
,
3421 filestats
, type
->super
, type
->type
);
3424 #endif /* HAVE_PYTHON */
3426 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3427 "is_cgi filename=\"%s\", filestats=%p, "
3428 "type=%s/%s, returning 0", filename
,
3429 filestats
, type
->super
, type
->type
);
3435 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3438 static int /* O - 0 if relative, 1 if absolute */
3439 is_path_absolute(const char *path
) /* I - Input path */
3442 * Check for a leading slash...
3449 * Check for "/.." in the path...
3452 while ((path
= strstr(path
, "/..")) != NULL
)
3454 if (!path
[3] || path
[3] == '/')
3461 * If we haven't found any relative paths, return 1 indicating an
3470 * 'pipe_command()' - Pipe the output of a command to the remote client.
3473 static int /* O - Process ID */
3474 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3475 int infile
, /* I - Standard input for command */
3476 int *outfile
, /* O - Standard output for command */
3477 char *command
, /* I - Command to run */
3478 char *options
, /* I - Options for command */
3479 int root
) /* I - Run as root? */
3481 int i
; /* Looping var */
3482 int pid
; /* Process ID */
3483 char *commptr
, /* Command string pointer */
3484 commch
; /* Command string character */
3485 char *uriptr
; /* URI string pointer */
3486 int fds
[2]; /* Pipe FDs */
3487 int argc
; /* Number of arguments */
3488 int envc
; /* Number of environment variables */
3489 char argbuf
[10240], /* Argument buffer */
3490 *argv
[100], /* Argument strings */
3491 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3492 char auth_type
[256], /* AUTH_TYPE environment variable */
3493 content_length
[1024], /* CONTENT_LENGTH environment variable */
3494 content_type
[1024], /* CONTENT_TYPE environment variable */
3495 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3496 http_referer
[1024], /* HTTP_REFERER environment variable */
3497 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3498 lang
[1024], /* LANG environment variable */
3499 path_info
[1024], /* PATH_INFO environment variable */
3500 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3501 remote_host
[1024], /* REMOTE_HOST environment variable */
3502 remote_user
[1024], /* REMOTE_USER environment variable */
3503 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3504 script_name
[1024], /* SCRIPT_NAME environment variable */
3505 server_name
[1024], /* SERVER_NAME environment variable */
3506 server_port
[1024]; /* SERVER_PORT environment variable */
3507 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3511 * Parse a copy of the options string, which is of the form:
3513 * argument+argument+argument
3514 * ?argument+argument+argument
3515 * param=value¶m=value
3516 * ?param=value¶m=value
3517 * /name?argument+argument+argument
3518 * /name?param=value¶m=value
3520 * If the string contains an "=" character after the initial name,
3521 * then we treat it as a HTTP GET form request and make a copy of
3522 * the remaining string for the environment variable.
3524 * The string is always parsed out as command-line arguments, to
3525 * be consistent with Apache...
3528 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3529 "pipe_command infile=%d, outfile=%p, "
3530 "command=\"%s\", options=\"%s\", root=%d",
3531 infile
, outfile
, command
,
3532 options
? options
: "(null)", root
);
3539 if (*commptr
== ' ')
3541 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3546 if (argbuf
[0] == '/')
3549 * Found some trailing path information, set PATH_INFO...
3552 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3553 commptr
= argbuf
+ strlen(argbuf
);
3557 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3563 path_info
[0] = '\0';
3565 if (*commptr
== ' ')
3569 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3572 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3579 argv
[argc
++] = commptr
;
3581 for (; *commptr
&& argc
< 99; commptr
++)
3584 * Break arguments whenever we see a + or space...
3587 if (*commptr
== ' ' || *commptr
== '+')
3589 while (*commptr
== ' ' || *commptr
== '+')
3593 * If we don't have a blank string, save it as another argument...
3598 argv
[argc
] = commptr
;
3604 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3605 isxdigit(commptr
[2] & 255))
3608 * Convert the %xx notation to the individual character.
3611 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3612 *commptr
= (commptr
[1] - '0') << 4;
3614 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3616 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3617 *commptr
|= commptr
[2] - '0';
3619 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3621 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3624 * Check for a %00 and break if that is the case...
3636 * Setup the environment variables as needed...
3639 if (con
->username
[0])
3641 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3642 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3644 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3648 auth_type
[0] = '\0';
3651 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3652 IPP_TAG_LANGUAGE
)) != NULL
)
3654 switch (strlen(attr
->values
[0].string
.text
))
3658 * This is an unknown or badly formatted language code; use
3659 * the POSIX locale...
3662 strlcpy(lang
, "LANG=C", sizeof(lang
));
3667 * Just the language code (ll)...
3670 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3671 attr
->values
[0].string
.text
);
3676 * Language and country code (ll-cc)...
3679 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3680 attr
->values
[0].string
.text
[0],
3681 attr
->values
[0].string
.text
[1],
3682 toupper(attr
->values
[0].string
.text
[3] & 255),
3683 toupper(attr
->values
[0].string
.text
[4] & 255));
3687 else if (con
->language
)
3688 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3690 strlcpy(lang
, "LANG=C", sizeof(lang
));
3692 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3693 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3694 sizeof(remote_addr
) - 12);
3696 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3697 httpGetHostname(con
->http
, NULL
, 0));
3699 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3700 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3703 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3704 DocumentRoot
, script_name
+ 12);
3706 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3708 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3710 char *nameptr
; /* Pointer to ":port" */
3712 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3713 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3714 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3715 *nameptr
= '\0'; /* Strip trailing ":port" */
3718 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3721 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3724 envp
[envc
++] = auth_type
;
3726 envp
[envc
++] = lang
;
3727 envp
[envc
++] = "REDIRECT_STATUS=1";
3728 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3729 envp
[envc
++] = server_name
;
3730 envp
[envc
++] = server_port
;
3731 envp
[envc
++] = remote_addr
;
3732 envp
[envc
++] = remote_host
;
3733 envp
[envc
++] = script_name
;
3734 envp
[envc
++] = script_filename
;
3737 envp
[envc
++] = path_info
;
3739 if (con
->username
[0])
3741 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3743 envp
[envc
++] = remote_user
;
3746 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3747 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3748 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3749 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3751 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3753 if (httpGetCookie(con
->http
))
3755 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3756 httpGetCookie(con
->http
));
3757 envp
[envc
++] = http_cookie
;
3760 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3762 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3763 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3764 envp
[envc
++] = http_user_agent
;
3767 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3769 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3770 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3771 envp
[envc
++] = http_referer
;
3774 if (con
->operation
== HTTP_STATE_GET
)
3776 envp
[envc
++] = "REQUEST_METHOD=GET";
3778 if (con
->query_string
)
3781 * Add GET form variables after ?...
3784 envp
[envc
++] = con
->query_string
;
3787 envp
[envc
++] = "QUERY_STRING=";
3791 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3792 CUPS_LLCAST con
->bytes
);
3793 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3794 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3796 envp
[envc
++] = "REQUEST_METHOD=POST";
3797 envp
[envc
++] = content_length
;
3798 envp
[envc
++] = content_type
;
3802 * Tell the CGI if we are using encryption...
3805 if (httpIsEncrypted(con
->http
))
3806 envp
[envc
++] = "HTTPS=ON";
3809 * Terminate the environment array...
3814 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3816 for (i
= 0; i
< argc
; i
++)
3817 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3818 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3819 for (i
= 0; i
< envc
; i
++)
3820 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3821 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3825 * Create a pipe for the output...
3828 if (cupsdOpenPipe(fds
))
3830 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3831 argv
[0], strerror(errno
));
3836 * Then execute the command...
3839 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3840 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3843 * Error - can't fork!
3846 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3849 cupsdClosePipe(fds
);
3855 * Fork successful - return the PID...
3858 if (con
->username
[0])
3859 cupsdAddCert(pid
, con
->username
, con
->type
);
3861 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3872 * 'valid_host()' - Is the Host: field valid?
3875 static int /* O - 1 if valid, 0 if not */
3876 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3878 cupsd_alias_t
*a
; /* Current alias */
3879 cupsd_netif_t
*netif
; /* Current network interface */
3880 const char *end
; /* End character */
3881 char *ptr
; /* Pointer into host value */
3885 * Copy the Host: header for later use...
3888 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3889 sizeof(con
->clientname
));
3890 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3893 con
->clientport
= atoi(ptr
);
3896 con
->clientport
= con
->serverport
;
3902 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3905 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3906 * addresses when accessing CUPS via the loopback interface...
3909 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3910 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3912 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3913 #endif /* __linux */
3914 !strcmp(con
->clientname
, "127.0.0.1") ||
3915 !strcmp(con
->clientname
, "[::1]"));
3918 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3920 * Check if the hostname is something.local (Bonjour); if so, allow it.
3923 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3927 * "." on end, work back to second-to-last "."...
3930 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3933 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3934 !_cups_strcasecmp(end
, ".local.")))
3936 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3939 * Check if the hostname is an IP address...
3942 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3945 * Possible IPv4/IPv6 address...
3948 http_addrlist_t
*addrlist
; /* List of addresses */
3951 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3954 * Good IPv4/IPv6 address...
3957 httpAddrFreeList(addrlist
);
3963 * Check for (alias) name matches...
3966 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3968 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3971 * "ServerAlias *" allows all host values through...
3974 if (!strcmp(a
->name
, "*"))
3977 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3980 * Prefix matches; check the character at the end - it must be "." or nul.
3983 end
= con
->clientname
+ a
->namelen
;
3985 if (!*end
|| (*end
== '.' && !end
[1]))
3990 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3991 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3993 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3996 * "ServerAlias *" allows all host values through...
3999 if (!strcmp(a
->name
, "*"))
4002 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4005 * Prefix matches; check the character at the end - it must be "." or nul.
4008 end
= con
->clientname
+ a
->namelen
;
4010 if (!*end
|| (*end
== '.' && !end
[1]))
4014 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4017 * Check for interface hostname matches...
4020 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4022 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4024 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4027 * Prefix matches; check the character at the end - it must be "." or nul.
4030 end
= con
->clientname
+ netif
->hostlen
;
4032 if (!*end
|| (*end
== '.' && !end
[1]))
4042 * 'write_file()' - Send a file via HTTP.
4045 static int /* O - 0 on failure, 1 on success */
4046 write_file(cupsd_client_t
*con
, /* I - Client connection */
4047 http_status_t code
, /* I - HTTP status */
4048 char *filename
, /* I - Filename */
4049 char *type
, /* I - File type */
4050 struct stat
*filestats
) /* O - File information */
4052 con
->file
= open(filename
, O_RDONLY
);
4054 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
4055 "write_file code=%d, filename=\"%s\" (%d), "
4056 "type=\"%s\", filestats=%p",
4057 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4062 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4066 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4069 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
4070 httpGetDateString(filestats
->st_mtime
)) < 0)
4072 if (httpPrintf(con
->http
, "Content-Length: " CUPS_LLFMT
"\r\n",
4073 CUPS_LLCAST filestats
->st_size
) < 0)
4075 if (httpPrintf(con
->http
, "\r\n") < 0)
4078 if (cupsdFlushHeader(con
) < 0)
4081 httpSetLength(con
->http
, filestats
->st_size
);
4083 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
4084 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4086 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4093 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4097 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4099 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4102 con
->file_ready
= 1;
4104 cupsdRemoveSelect(con
->file
);
4105 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4107 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");