2 * Client routines for the CUPS scheduler.
4 * Copyright © 2007-2018 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
7 * This file contains Kerberos support code, copyright 2006 by
10 * Licensed under Apache License v2.0. See the file "LICENSE" for more
15 * Include necessary headers...
18 #define _CUPS_NO_DEPRECATED
19 #define _HTTP_NO_PRIVATE
24 #endif /* __APPLE__ */
27 #endif /* HAVE_TCPD_H */
34 static int check_if_modified(cupsd_client_t
*con
,
35 struct stat
*filestats
);
36 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
39 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
41 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
42 char *filename
, size_t len
);
43 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
44 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
45 struct stat
*filestats
, mime_type_t
*type
);
46 static int is_path_absolute(const char *path
);
47 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
48 char *command
, char *options
, int root
);
49 static int valid_host(cupsd_client_t
*con
);
50 static int write_file(cupsd_client_t
*con
, http_status_t code
,
51 char *filename
, char *type
,
52 struct stat
*filestats
);
53 static void write_pipe(cupsd_client_t
*con
);
57 * 'cupsdAcceptClient()' - Accept a new client.
61 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
63 const char *hostname
; /* Hostname of client */
64 char name
[256]; /* Hostname of client */
65 int count
; /* Count of connections on a host */
66 cupsd_client_t
*con
, /* New client pointer */
67 *tempcon
; /* Temporary client pointer */
68 socklen_t addrlen
; /* Length of address */
69 http_addr_t temp
; /* Temporary address variable */
70 static time_t last_dos
= 0; /* Time of last DoS attack */
72 struct request_info wrap_req
; /* TCP wrappers request information */
73 #endif /* HAVE_TCPD_H */
76 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis
, lis
->fd
, cupsArrayCount(Clients
));
79 * Make sure we don't have a full set of clients already...
82 if (cupsArrayCount(Clients
) == MaxClients
)
88 * Get a pointer to the next available client...
92 Clients
= cupsArrayNew(NULL
, NULL
);
96 cupsdLogMessage(CUPSD_LOG_ERROR
,
97 "Unable to allocate memory for clients array!");
98 cupsdPauseListening();
103 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
107 cupsdLogMessage(CUPSD_LOG_ERROR
,
108 "Unable to allocate memory for active clients array!");
109 cupsdPauseListening();
113 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
115 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
116 cupsdPauseListening();
121 * Accept the client and get the remote address...
124 con
->number
= ++ LastClientNumber
;
127 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
129 if (errno
== ENFILE
|| errno
== EMFILE
)
130 cupsdPauseListening();
132 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
140 * Save the connected address and port number...
143 addrlen
= sizeof(con
->clientaddr
);
145 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&con
->clientaddr
, &addrlen
) || addrlen
== 0)
146 con
->clientaddr
= lis
->address
;
148 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Server address is \"%s\".", httpAddrString(&con
->clientaddr
, name
, sizeof(name
)));
151 * Check the number of clients on the same address...
154 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
156 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
157 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
160 if (count
>= MaxClientsPerHost
)
164 if (count
>= MaxClientsPerHost
)
166 if ((time(NULL
) - last_dos
) >= 60)
168 last_dos
= time(NULL
);
169 cupsdLogMessage(CUPSD_LOG_WARN
,
170 "Possible DoS attack - more than %d clients connecting "
173 httpGetHostname(con
->http
, name
, sizeof(name
)));
176 httpClose(con
->http
);
182 * Get the hostname or format the IP address as needed...
186 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
188 hostname
= httpGetHostname(con
->http
, NULL
, 0);
190 if (hostname
== NULL
&& HostNameLookups
== 2)
193 * Can't have an unresolved IP address with double-lookups enabled...
196 httpClose(con
->http
);
198 cupsdLogClient(con
, CUPSD_LOG_WARN
,
199 "Name lookup failed - connection from %s closed!",
200 httpGetHostname(con
->http
, NULL
, 0));
206 if (HostNameLookups
== 2)
209 * Do double lookups as needed...
212 http_addrlist_t
*addrlist
, /* List of addresses */
213 *addr
; /* Current address */
215 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
218 * See if the hostname maps to the same IP address...
221 for (addr
= addrlist
; addr
; addr
= addr
->next
)
222 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
228 httpAddrFreeList(addrlist
);
233 * Can't have a hostname that doesn't resolve to the same IP address
234 * with double-lookups enabled...
237 httpClose(con
->http
);
239 cupsdLogClient(con
, CUPSD_LOG_WARN
,
240 "IP lookup failed - connection from %s closed!",
241 httpGetHostname(con
->http
, NULL
, 0));
249 * See if the connection is denied by TCP wrappers...
252 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
256 if (!hosts_access(&wrap_req
))
258 httpClose(con
->http
);
260 cupsdLogClient(con
, CUPSD_LOG_WARN
,
261 "Connection from %s refused by /etc/hosts.allow and "
262 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
266 #endif /* HAVE_TCPD_H */
269 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
272 socklen_t peersize
; /* Size of peer credentials */
273 pid_t peerpid
; /* Peer process ID */
274 char peername
[256]; /* Name of process */
276 peersize
= sizeof(peerpid
);
277 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
280 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
281 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
282 "Accepted from %s (Domain ???[%d])",
283 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
285 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
286 "Accepted from %s (Domain %s[%d])",
287 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
290 # endif /* __APPLE__ */
292 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
293 httpGetHostname(con
->http
, NULL
, 0));
296 #endif /* AF_LOCAL */
297 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
298 httpGetHostname(con
->http
, NULL
, 0),
299 httpAddrPort(httpGetAddress(con
->http
)),
300 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
303 * Get the local address the client connected to...
306 addrlen
= sizeof(temp
);
307 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
309 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
312 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
313 con
->serverport
= LocalPort
;
316 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
318 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
319 con
->serverport
= LocalPort
;
321 #endif /* AF_LOCAL */
324 if (httpAddrLocalhost(&temp
))
325 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
326 else if (HostNameLookups
)
327 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
329 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
331 con
->serverport
= httpAddrPort(&(lis
->address
));
335 * Add the connection to the array of active clients...
338 cupsArrayAdd(Clients
, con
);
341 * Add the socket to the server select.
344 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
347 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
350 * Temporarily suspend accept()'s until we lose a client...
353 if (cupsArrayCount(Clients
) == MaxClients
)
354 cupsdPauseListening();
358 * See if we are connecting on a secure port...
361 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
364 * https connection; go secure...
367 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
368 cupsdCloseClient(con
);
372 #endif /* HAVE_SSL */
377 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
381 cupsdCloseAllClients(void)
383 cupsd_client_t
*con
; /* Current client */
386 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients
));
388 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
390 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
391 if (cupsdCloseClient(con
))
392 cupsdCloseClient(con
);
397 * 'cupsdCloseClient()' - Close a remote client.
400 int /* O - 1 if partial close, 0 if fully closed */
401 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
403 int partial
; /* Do partial close for SSL? */
406 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
409 * Flush pending writes before closing...
412 httpFlushWrite(con
->http
);
416 if (con
->pipe_pid
!= 0)
419 * Stop any CGI process...
422 cupsdEndProcess(con
->pipe_pid
, 1);
428 cupsdRemoveSelect(con
->file
);
435 * Close the socket and clear the file from the input set for select()...
438 if (httpGetFd(con
->http
) >= 0)
440 cupsArrayRemove(ActiveClients
, con
);
441 cupsdSetBusyState(0);
445 * Shutdown encryption as needed...
448 if (httpIsEncrypted(con
->http
))
450 #endif /* HAVE_SSL */
455 * Only do a partial close so that the encrypted client gets everything.
458 httpShutdown(con
->http
);
459 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
462 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
467 * Shut the socket down fully...
470 cupsdRemoveSelect(httpGetFd(con
->http
));
471 httpClose(con
->http
);
482 cupsdRemoveSelect(httpGetFd(con
->http
));
484 httpClose(con
->http
);
488 unlink(con
->filename
);
489 cupsdClearString(&con
->filename
);
492 cupsdClearString(&con
->command
);
493 cupsdClearString(&con
->options
);
494 cupsdClearString(&con
->query_string
);
498 ippDelete(con
->request
);
504 ippDelete(con
->response
);
505 con
->response
= NULL
;
510 cupsLangFree(con
->language
);
511 con
->language
= NULL
;
514 #ifdef HAVE_AUTHORIZATION_H
517 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
520 #endif /* HAVE_AUTHORIZATION_H */
523 * Re-enable new client connections if we are going back under the
527 if (cupsArrayCount(Clients
) == MaxClients
)
528 cupsdResumeListening();
531 * Compact the list of clients as necessary...
534 cupsArrayRemove(Clients
, con
);
544 * 'cupsdReadClient()' - Read data from a client.
548 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
550 char line
[32768], /* Line from client... */
551 locale
[64], /* Locale */
552 *ptr
; /* Pointer into strings */
553 http_status_t status
; /* Transfer status */
554 ipp_state_t ipp_state
; /* State of IPP transfer */
555 int bytes
; /* Number of bytes to POST */
556 char *filename
; /* Name of file for GET/HEAD */
557 char buf
[1024]; /* Buffer for real filename */
558 struct stat filestats
; /* File information */
559 mime_type_t
*type
; /* MIME type of file */
560 static unsigned request_id
= 0; /* Request ID for temp files */
563 status
= HTTP_STATUS_CONTINUE
;
565 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=" CUPS_LLFMT
", request=%p(%s), file=%d", httpError(con
->http
), (int)httpGetReady(con
->http
), httpStateString(httpGetState(con
->http
)), httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH", CUPS_LLCAST
httpGetRemaining(con
->http
), con
->request
, con
->request
? ippStateString(ippGetState(con
->request
)) : "", con
->file
);
567 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
568 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
569 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
572 * If we get called in the wrong state, then something went wrong with the
573 * connection and we need to shut it down...
576 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
579 * Connection closed...
582 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
583 cupsdCloseClient(con
);
587 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con
->http
)));
588 cupsdCloseClient(con
);
596 * Automatically check for a SSL/TLS handshake...
601 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
602 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
605 * Encrypt this connection...
608 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf
[0] & 255);
610 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
611 cupsdCloseClient(con
);
616 #endif /* HAVE_SSL */
618 switch (httpGetState(con
->http
))
620 case HTTP_STATE_WAITING
:
622 * See if we've received a request line...
625 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
626 if (con
->operation
== HTTP_STATE_ERROR
||
627 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
628 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
630 if (httpError(con
->http
))
631 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
632 "HTTP_STATE_WAITING Closing for error %d (%s)",
633 httpError(con
->http
), strerror(httpError(con
->http
)));
635 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
636 "HTTP_STATE_WAITING Closing on error: %s",
637 cupsLastErrorString());
639 cupsdCloseClient(con
);
644 * Ignore blank request lines...
647 if (con
->operation
== HTTP_STATE_WAITING
)
651 * Clear other state variables...
658 con
->username
[0] = '\0';
659 con
->password
[0] = '\0';
661 cupsdClearString(&con
->command
);
662 cupsdClearString(&con
->options
);
663 cupsdClearString(&con
->query_string
);
667 ippDelete(con
->request
);
673 ippDelete(con
->response
);
674 con
->response
= NULL
;
679 cupsLangFree(con
->language
);
680 con
->language
= NULL
;
686 #endif /* HAVE_GSSAPI */
689 * Handle full URLs in the request line...
692 if (strcmp(con
->uri
, "*"))
694 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
695 userpass
[HTTP_MAX_URI
], /* Username:password */
696 hostname
[HTTP_MAX_URI
], /* Hostname */
697 resource
[HTTP_MAX_URI
]; /* Resource path */
698 int port
; /* Port number */
701 * Separate the URI into its components...
704 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
705 scheme
, sizeof(scheme
),
706 userpass
, sizeof(userpass
),
707 hostname
, sizeof(hostname
), &port
,
708 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
710 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
712 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
713 cupsdCloseClient(con
);
718 * Only allow URIs with the servername, localhost, or an IP
722 if (strcmp(scheme
, "file") &&
723 _cups_strcasecmp(hostname
, ServerName
) &&
724 _cups_strcasecmp(hostname
, "localhost") &&
725 !cupsArrayFind(ServerAlias
, hostname
) &&
726 !isdigit(hostname
[0]) && hostname
[0] != '[')
729 * Nope, we don't do proxies...
732 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
734 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
735 cupsdCloseClient(con
);
740 * Copy the resource portion back into the URI; both resource and
741 * con->uri are HTTP_MAX_URI bytes in size...
744 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
748 * Process the request...
751 gettimeofday(&(con
->start
), NULL
);
753 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
754 httpStateString(con
->operation
) + 11, con
->uri
,
755 httpGetVersion(con
->http
) / 100,
756 httpGetVersion(con
->http
) % 100);
758 if (!cupsArrayFind(ActiveClients
, con
))
760 cupsArrayAdd(ActiveClients
, con
);
761 cupsdSetBusyState(0);
764 case HTTP_STATE_OPTIONS
:
765 case HTTP_STATE_DELETE
:
766 case HTTP_STATE_GET
:
767 case HTTP_STATE_HEAD
:
768 case HTTP_STATE_POST
:
769 case HTTP_STATE_PUT
:
770 case HTTP_STATE_TRACE
:
772 * Parse incoming parameters until the status changes...
775 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
776 if (!httpGetReady(con
->http
))
779 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
781 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
782 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
783 "Closing for error %d (%s) while reading headers.",
784 httpError(con
->http
), strerror(httpError(con
->http
)));
786 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
787 "Closing on EOF while reading headers.");
789 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
790 cupsdCloseClient(con
);
796 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
799 * Connection closed...
802 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
803 cupsdCloseClient(con
);
806 break; /* Anti-compiler-warning-code */
810 * Handle new transfers...
813 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d, state=%d", status
, httpGetState(con
->http
));
815 if (status
== HTTP_STATUS_OK
)
818 * Record whether the client is a web browser. "Mozilla" was the original
819 * and it seems that every web browser in existence now uses that as the
820 * prefix with additional information identifying *which* browser.
822 * Chrome (at least) has problems with multiple WWW-Authenticate values in
823 * a single header, so we only report Basic or Negotiate to web browsers and
824 * leave the multiple choices to the native CUPS client...
827 con
->is_browser
= !strncmp(httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
), "Mozilla/", 8);
829 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
832 * Figure out the locale from the Accept-Language and Content-Type
836 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
840 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
844 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
845 "charset=")) != NULL
)
848 * Combine language and charset, and trim any extra params in the
852 snprintf(locale
, sizeof(locale
), "%s.%s",
853 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
855 if ((ptr
= strchr(locale
, ',')) != NULL
)
859 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
860 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
862 con
->language
= cupsLangGet(locale
);
865 con
->language
= cupsLangGet(DefaultLocale
);
869 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
870 "Keep-Alive", 10) && KeepAlive
)
871 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
872 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
874 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
876 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
877 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
880 * HTTP/1.1 and higher require the "Host:" field...
883 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
885 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
886 cupsdCloseClient(con
);
890 else if (!valid_host(con
))
893 * Access to localhost must use "localhost" or the corresponding IPv4
894 * or IPv6 values in the Host: field.
897 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
898 "Request from \"%s\" using invalid Host: field \"%s\".",
899 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
901 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
903 cupsdCloseClient(con
);
907 else if (con
->operation
== HTTP_STATE_OPTIONS
)
910 * Do OPTIONS command...
913 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
915 httpClearFields(con
->http
);
917 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
919 cupsdCloseClient(con
);
924 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
928 * Do encryption stuff...
931 httpClearFields(con
->http
);
933 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
935 cupsdCloseClient(con
);
939 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
941 cupsdCloseClient(con
);
945 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
947 cupsdCloseClient(con
);
950 #endif /* HAVE_SSL */
953 httpClearFields(con
->http
);
954 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
956 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
958 cupsdCloseClient(con
);
962 else if (!is_path_absolute(con
->uri
))
965 * Protect against malicious users!
968 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
969 "Request for non-absolute resource \"%s\".", con
->uri
);
971 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
973 cupsdCloseClient(con
);
979 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
980 "Upgrade") && !httpIsEncrypted(con
->http
))
984 * Do encryption stuff...
987 httpClearFields(con
->http
);
989 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
992 cupsdCloseClient(con
);
996 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
998 cupsdCloseClient(con
);
1002 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1004 cupsdCloseClient(con
);
1007 #endif /* HAVE_SSL */
1010 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1012 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1013 cupsdCloseClient(con
);
1017 if (httpGetExpect(con
->http
) &&
1018 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1020 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1023 * Send 100-continue header...
1026 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1028 cupsdCloseClient(con
);
1035 * Send 417-expectation-failed header...
1038 httpClearFields(con
->http
);
1039 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1041 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1042 cupsdCloseClient(con
);
1047 switch (httpGetState(con
->http
))
1049 case HTTP_STATE_GET_SEND
:
1050 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1052 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1054 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1056 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1058 if (is_cgi(con
, filename
, &filestats
, type
))
1061 * Note: con->command and con->options were set by is_cgi()...
1064 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1066 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1068 cupsdCloseClient(con
);
1073 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1075 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1076 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1080 if (!check_if_modified(con
, &filestats
))
1082 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1084 cupsdCloseClient(con
);
1091 strlcpy(line
, "text/plain", sizeof(line
));
1093 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1095 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1097 cupsdCloseClient(con
);
1102 else if (!strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/printers", 9) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/help", 5) || !strncmp(con
->uri
, "/jobs", 5))
1107 * Web interface is disabled. Show an appropriate message...
1110 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1112 cupsdCloseClient(con
);
1120 * Send CGI output...
1123 if (!strncmp(con
->uri
, "/admin", 6))
1125 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1126 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1128 else if (!strncmp(con
->uri
, "/printers", 9))
1130 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1131 if (con
->uri
[9] && con
->uri
[10])
1132 cupsdSetString(&con
->options
, con
->uri
+ 9);
1134 cupsdSetString(&con
->options
, NULL
);
1136 else if (!strncmp(con
->uri
, "/classes", 8))
1138 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1139 if (con
->uri
[8] && con
->uri
[9])
1140 cupsdSetString(&con
->options
, con
->uri
+ 8);
1142 cupsdSetString(&con
->options
, NULL
);
1144 else if (!strncmp(con
->uri
, "/jobs", 5))
1146 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1147 if (con
->uri
[5] && con
->uri
[6])
1148 cupsdSetString(&con
->options
, con
->uri
+ 5);
1150 cupsdSetString(&con
->options
, NULL
);
1154 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1155 if (con
->uri
[5] && con
->uri
[6])
1156 cupsdSetString(&con
->options
, con
->uri
+ 5);
1158 cupsdSetString(&con
->options
, NULL
);
1161 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1163 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1165 cupsdCloseClient(con
);
1170 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1172 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1173 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1177 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1179 cupsdCloseClient(con
);
1185 case HTTP_STATE_POST_RECV
:
1187 * See if the POST request includes a Content-Length field, and if
1188 * so check the length against any limits that are set...
1191 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] && MaxRequestSize
> 0 && httpGetLength2(con
->http
) > MaxRequestSize
)
1194 * Request too large...
1197 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1199 cupsdCloseClient(con
);
1205 else if (httpGetLength2(con
->http
) < 0)
1208 * Negative content lengths are invalid!
1211 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1213 cupsdCloseClient(con
);
1221 * See what kind of POST request this is; for IPP requests the
1222 * content-type field will be "application/ipp"...
1225 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
), "application/ipp"))
1227 con
->request
= ippNew();
1230 else if (!WebInterface
)
1233 * Web interface is disabled. Show an appropriate message...
1236 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1238 cupsdCloseClient(con
);
1245 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1251 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1253 if (!is_cgi(con
, filename
, &filestats
, type
))
1256 * Only POST to CGI's...
1259 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1261 cupsdCloseClient(con
);
1266 else if (!strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/printers", 9) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/help", 5) || !strncmp(con
->uri
, "/jobs", 5))
1272 if (!strncmp(con
->uri
, "/admin", 6))
1274 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1275 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1277 else if (!strncmp(con
->uri
, "/printers", 9))
1279 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1280 if (con
->uri
[9] && con
->uri
[10])
1281 cupsdSetString(&con
->options
, con
->uri
+ 9);
1283 cupsdSetString(&con
->options
, NULL
);
1285 else if (!strncmp(con
->uri
, "/classes", 8))
1287 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1288 if (con
->uri
[8] && con
->uri
[9])
1289 cupsdSetString(&con
->options
, con
->uri
+ 8);
1291 cupsdSetString(&con
->options
, NULL
);
1293 else if (!strncmp(con
->uri
, "/jobs", 5))
1295 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1296 if (con
->uri
[5] && con
->uri
[6])
1297 cupsdSetString(&con
->options
, con
->uri
+ 5);
1299 cupsdSetString(&con
->options
, NULL
);
1303 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1304 if (con
->uri
[5] && con
->uri
[6])
1305 cupsdSetString(&con
->options
, con
->uri
+ 5);
1307 cupsdSetString(&con
->options
, NULL
);
1310 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1311 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1315 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1317 cupsdCloseClient(con
);
1323 case HTTP_STATE_PUT_RECV
:
1325 * Validate the resource name...
1328 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1331 * PUT can only be done to the cupsd.conf file...
1334 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Disallowed PUT request for \"%s\".", con
->uri
);
1336 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1338 cupsdCloseClient(con
);
1346 * See if the PUT request includes a Content-Length field, and if
1347 * so check the length against any limits that are set...
1350 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] && MaxRequestSize
> 0 && httpGetLength2(con
->http
) > MaxRequestSize
)
1353 * Request too large...
1356 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1358 cupsdCloseClient(con
);
1364 else if (httpGetLength2(con
->http
) < 0)
1367 * Negative content lengths are invalid!
1370 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1372 cupsdCloseClient(con
);
1380 * Open a temporary file to hold the request...
1383 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1384 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1388 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to create request file \"%s\": %s", con
->filename
, strerror(errno
));
1390 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1392 cupsdCloseClient(con
);
1397 fchmod(con
->file
, 0640);
1398 fchown(con
->file
, RunUser
, Group
);
1399 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1402 case HTTP_STATE_DELETE
:
1403 case HTTP_STATE_TRACE
:
1404 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1405 cupsdCloseClient(con
);
1408 case HTTP_STATE_HEAD
:
1409 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1411 if (!check_if_modified(con
, &filestats
))
1413 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1415 cupsdCloseClient(con
);
1419 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1427 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1429 strlcpy(line
, "text/plain", sizeof(line
));
1431 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1433 httpClearFields(con
->http
);
1435 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
, httpGetDateString(filestats
.st_mtime
));
1436 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1438 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1440 cupsdCloseClient(con
);
1444 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1447 else if (!WebInterface
)
1449 httpClearFields(con
->http
);
1451 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1453 cupsdCloseClient(con
);
1457 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1461 if (!strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/printers", 9) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/help", 5) || !strncmp(con
->uri
, "/jobs", 5))
1467 httpClearFields(con
->http
);
1469 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1471 cupsdCloseClient(con
);
1475 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1479 httpClearFields(con
->http
);
1481 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1483 cupsdCloseClient(con
);
1487 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1492 break; /* Anti-compiler-warning-code */
1498 * Handle any incoming data...
1501 switch (httpGetState(con
->http
))
1503 case HTTP_STATE_PUT_RECV
:
1506 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1508 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1509 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1510 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1511 httpError(con
->http
), strerror(httpError(con
->http
)));
1513 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1514 "HTTP_STATE_PUT_RECV Closing on EOF.");
1516 cupsdCloseClient(con
);
1521 con
->bytes
+= bytes
;
1523 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1527 unlink(con
->filename
);
1528 cupsdClearString(&con
->filename
);
1530 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1532 cupsdCloseClient(con
);
1537 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1539 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1540 "Unable to write %d bytes to \"%s\": %s", bytes
,
1541 con
->filename
, strerror(errno
));
1545 unlink(con
->filename
);
1546 cupsdClearString(&con
->filename
);
1548 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1550 cupsdCloseClient(con
);
1555 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1557 cupsdCloseClient(con
);
1561 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1563 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1566 * End of file, see how big it is...
1569 fstat(con
->file
, &filestats
);
1574 if (filestats
.st_size
> MaxRequestSize
&&
1578 * Request is too big; remove it and send an error...
1581 unlink(con
->filename
);
1582 cupsdClearString(&con
->filename
);
1584 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1586 cupsdCloseClient(con
);
1592 * Install the configuration file...
1595 status
= install_cupsd_conf(con
);
1598 * Return the status to the client...
1601 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1603 cupsdCloseClient(con
);
1609 case HTTP_STATE_POST_RECV
:
1612 if (con
->request
&& con
->file
< 0)
1615 * Grab any request data from the connection...
1618 if (!httpWait(con
->http
, 0))
1621 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1623 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1624 cupsLastErrorString());
1626 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1627 cupsdCloseClient(con
);
1630 else if (ipp_state
!= IPP_STATE_DATA
)
1632 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1634 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1635 cupsdCloseClient(con
);
1639 if (httpGetReady(con
->http
))
1645 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1646 con
->request
->request
.op
.version
[0],
1647 con
->request
->request
.op
.version
[1],
1648 ippOpString(con
->request
->request
.op
.operation_id
),
1649 con
->request
->request
.op
.request_id
);
1650 con
->bytes
+= (off_t
)ippLength(con
->request
);
1654 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1657 * Create a file as needed for the request data...
1660 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1662 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1666 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1667 "Unable to create request file \"%s\": %s",
1668 con
->filename
, strerror(errno
));
1670 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1672 cupsdCloseClient(con
);
1677 fchmod(con
->file
, 0640);
1678 fchown(con
->file
, RunUser
, Group
);
1679 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1682 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1684 if (!httpWait(con
->http
, 0))
1686 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1688 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1689 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1690 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1691 httpError(con
->http
), strerror(httpError(con
->http
)));
1693 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1694 "HTTP_STATE_POST_SEND Closing on EOF.");
1696 cupsdCloseClient(con
);
1701 con
->bytes
+= bytes
;
1703 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1707 unlink(con
->filename
);
1708 cupsdClearString(&con
->filename
);
1710 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1712 cupsdCloseClient(con
);
1717 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1719 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1720 "Unable to write %d bytes to \"%s\": %s",
1721 bytes
, con
->filename
, strerror(errno
));
1725 unlink(con
->filename
);
1726 cupsdClearString(&con
->filename
);
1728 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1731 cupsdCloseClient(con
);
1736 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1738 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1740 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1741 "Closing on unexpected state %s.",
1742 httpStateString(httpGetState(con
->http
)));
1743 cupsdCloseClient(con
);
1748 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1750 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1754 fstat(con
->file
, &filestats
);
1759 if (filestats
.st_size
> MaxRequestSize
&&
1763 * Request is too big; remove it and send an error...
1766 unlink(con
->filename
);
1767 cupsdClearString(&con
->filename
);
1772 * Delete any IPP request data...
1775 ippDelete(con
->request
);
1776 con
->request
= NULL
;
1779 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1781 cupsdCloseClient(con
);
1785 else if (filestats
.st_size
== 0)
1788 * Don't allow empty file...
1791 unlink(con
->filename
);
1792 cupsdClearString(&con
->filename
);
1797 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1799 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1801 cupsdCloseClient(con
);
1806 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1812 cupsdProcessIPPRequest(con
);
1816 unlink(con
->filename
);
1817 cupsdClearString(&con
->filename
);
1826 break; /* Anti-compiler-warning-code */
1829 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
1831 if (!httpGetKeepAlive(con
->http
))
1833 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1834 "Closing because Keep-Alive is disabled.");
1835 cupsdCloseClient(con
);
1839 cupsArrayRemove(ActiveClients
, con
);
1840 cupsdSetBusyState(0);
1847 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1850 int /* O - 1 on success, 0 on failure */
1852 cupsd_client_t
*con
, /* I - Client connection */
1853 char *command
, /* I - Command to run */
1854 char *options
, /* I - Command-line options */
1855 int root
) /* I - Run as root? */
1857 int fd
; /* Standard input file descriptor */
1862 fd
= open(con
->filename
, O_RDONLY
);
1866 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1867 "Unable to open \"%s\" for reading: %s",
1868 con
->filename
? con
->filename
: "/dev/null",
1873 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1878 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1879 con
->pipe_status
= HTTP_STATUS_OK
;
1881 httpClearFields(con
->http
);
1886 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
1887 command
, con
->pipe_pid
, con
->file
);
1889 if (con
->pipe_pid
== 0)
1892 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1894 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
1896 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
1898 con
->sent_header
= 0;
1899 con
->file_ready
= 0;
1900 con
->got_fields
= 0;
1901 con
->header_used
= 0;
1908 * 'cupsdSendError()' - Send an error message via HTTP.
1911 int /* O - 1 if successful, 0 otherwise */
1912 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1913 http_status_t code
, /* I - Error code */
1914 int auth_type
)/* I - Authentication type */
1916 char location
[HTTP_MAX_VALUE
]; /* Location field */
1919 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
1923 * Force client to upgrade for authentication if that is how the
1924 * server is configured...
1927 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
1928 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
1929 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
1930 !httpIsEncrypted(con
->http
))
1932 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
1934 #endif /* HAVE_SSL */
1937 * Put the request in the access_log file...
1940 cupsdLogRequest(con
, code
);
1943 * To work around bugs in some proxies, don't use Keep-Alive for some
1946 * Kerberos authentication doesn't work without Keep-Alive, so
1947 * never disable it in that case.
1950 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
1952 httpClearFields(con
->http
);
1954 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
1956 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
1957 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1959 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
1960 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
1961 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
1963 if (code
>= HTTP_STATUS_BAD_REQUEST
)
1966 * Send a human-readable error message.
1969 char message
[4096], /* Message for user */
1970 urltext
[1024], /* URL redirection text */
1971 redirect
[1024]; /* Redirection link */
1972 const char *text
; /* Status-specific text */
1977 if (code
== HTTP_STATUS_UNAUTHORIZED
)
1978 text
= _cupsLangString(con
->language
,
1979 _("Enter your username and password or the "
1980 "root username and password to access this "
1981 "page. If you are using Kerberos authentication, "
1982 "make sure you have a valid Kerberos ticket."));
1983 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
1987 snprintf(urltext
, sizeof(urltext
), _cupsLangString(con
->language
, _("You must access this page using the URL https://%s:%d%s.")), con
->servername
, con
->serverport
, con
->uri
);
1989 snprintf(redirect
, sizeof(redirect
), "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;URL=https://%s:%d%s\">\n", con
->servername
, con
->serverport
, con
->uri
);
1991 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
1992 text
= _cupsLangString(con
->language
,
1993 _("The web interface is currently disabled. Run "
1994 "\"cupsctl WebInterface=yes\" to enable it."));
1998 snprintf(message
, sizeof(message
),
1999 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2000 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2003 "\t<META HTTP-EQUIV=\"Content-Type\" "
2004 "CONTENT=\"text/html; charset=utf-8\">\n"
2005 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2006 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2007 "HREF=\"/cups.css\">\n"
2015 _httpStatus(con
->language
, code
), redirect
,
2016 _httpStatus(con
->language
, code
), text
);
2019 * Send an error message back to the client. If the error code is a
2020 * 400 or 500 series, make sure the message contains some text, too!
2023 size_t length
= strlen(message
); /* Length of message */
2025 httpSetLength(con
->http
, length
);
2027 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2030 if (httpWrite2(con
->http
, message
, length
) < 0)
2033 if (httpFlushWrite(con
->http
) < 0)
2038 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2040 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2049 * 'cupsdSendHeader()' - Send an HTTP request.
2052 int /* O - 1 on success, 0 on failure */
2054 cupsd_client_t
*con
, /* I - Client to send to */
2055 http_status_t code
, /* I - HTTP status code */
2056 char *type
, /* I - MIME type of document */
2057 int auth_type
) /* I - Type of authentication */
2059 char auth_str
[1024]; /* Authorization string */
2062 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2065 * Send the HTTP status header...
2068 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2071 * Treat our special "web interface is disabled" status as "200 OK" for web
2075 code
= HTTP_STATUS_OK
;
2079 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2081 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2082 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2084 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2086 if (auth_type
== CUPSD_AUTH_NONE
)
2088 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2089 auth_type
= cupsdDefaultAuthType();
2091 auth_type
= con
->best
->type
;
2096 if (auth_type
== CUPSD_AUTH_BASIC
)
2098 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2100 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2102 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
2103 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2104 strlcpy(auth_str
, "PeerCred", sizeof(auth_str
));
2106 #endif /* SO_PEERCRED && AF_LOCAL */
2107 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2110 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&& !con
->is_browser
&& !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2113 * Add a "trc" (try root certification) parameter for local non-Kerberos
2114 * requests when the request requires system group membership - then the
2115 * client knows the root certificate can/should be used.
2117 * Also, for macOS we also look for @AUTHKEY and add an "AuthRef key=foo"
2118 * method as needed...
2121 char *name
, /* Current user name */
2122 *auth_key
; /* Auth key buffer */
2123 size_t auth_size
; /* Size of remaining buffer */
2124 int need_local
= 1; /* Do we need to list "Local" method? */
2126 auth_key
= auth_str
+ strlen(auth_str
);
2127 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2129 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
2130 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2132 strlcpy(auth_key
, ", PeerCred", auth_size
);
2136 #endif /* SO_PEERCRED && AF_LOCAL */
2138 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2140 name
= (char *)cupsArrayNext(con
->best
->names
))
2142 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendHeader: require \"%s\"", name
);
2144 #ifdef HAVE_AUTHORIZATION_H
2145 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2147 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\", Local trc=\"y\"", name
+ 9);
2149 /* end parenthesis is stripped in conf.c */
2153 #endif /* HAVE_AUTHORIZATION_H */
2154 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2156 #ifdef HAVE_AUTHORIZATION_H
2157 if (SystemGroupAuthKey
)
2158 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\", Local trc=\"y\"", SystemGroupAuthKey
);
2160 #endif /* HAVE_AUTHORIZATION_H */
2161 strlcpy(auth_key
, ", Local trc=\"y\"", auth_size
);
2168 strlcat(auth_key
, ", Local", auth_size
);
2173 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2175 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2179 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2180 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2184 if (!strcmp(type
, "text/html"))
2185 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2187 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2190 return (!httpWriteResponse(con
->http
, code
));
2195 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2199 cupsdUpdateCGI(void)
2201 char *ptr
, /* Pointer to end of line in buffer */
2202 message
[1024]; /* Pointer to message text */
2203 int loglevel
; /* Log level for message */
2206 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2207 message
, sizeof(message
))) != NULL
)
2209 if (loglevel
== CUPSD_LOG_INFO
)
2210 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2212 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2216 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2219 * Fatal error on pipe - should never happen!
2222 cupsdLogMessage(CUPSD_LOG_CRIT
,
2223 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2230 * 'cupsdWriteClient()' - Write data to a client as needed.
2234 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2236 int bytes
, /* Number of bytes written */
2237 field_col
; /* Current column */
2238 char *bufptr
, /* Pointer into buffer */
2239 *bufend
; /* Pointer to end of buffer */
2240 ipp_state_t ipp_state
; /* IPP state value */
2243 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2244 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2249 "data_encoding=HTTP_ENCODING_%s, "
2250 "data_remaining=" CUPS_LLFMT
", "
2254 httpError(con
->http
), (int)httpGetReady(con
->http
),
2255 httpStateString(httpGetState(con
->http
)),
2256 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2257 CUPS_LLCAST
httpGetLength2(con
->http
),
2259 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2260 con
->pipe_pid
, con
->file
);
2262 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2263 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2266 * If we get called in the wrong state, then something went wrong with the
2267 * connection and we need to shut it down...
2270 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2271 httpStateString(httpGetState(con
->http
)));
2272 cupsdCloseClient(con
);
2279 * Make sure we select on the CGI output...
2282 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2284 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2286 if (!con
->file_ready
)
2289 * Try again later when there is CGI output available...
2292 cupsdRemoveSelect(httpGetFd(con
->http
));
2296 con
->file_ready
= 0;
2299 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2301 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2304 * Limit GET bytes to original size of file (STR #3265)...
2307 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2310 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2312 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2317 * Write a single attribute or the IPP message header...
2320 ipp_state
= ippWrite(con
->http
, con
->response
);
2323 * If the write buffer has been flushed, stop buffering up attributes...
2326 if (httpGetPending(con
->http
) <= wused
)
2329 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2331 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2332 "Writing IPP response, ipp_state=%s, old "
2333 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2334 ippStateString(ipp_state
),
2335 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2337 if (httpGetPending(con
->http
) > 0)
2338 httpFlushWrite(con
->http
);
2340 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2341 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2343 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2344 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2345 (int)bytes
, httpGetState(con
->http
),
2346 CUPS_LLCAST
httpGetLength2(con
->http
));
2348 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2350 con
->header_used
+= bytes
;
2352 if (con
->pipe_pid
&& !con
->got_fields
)
2355 * Inspect the data for Content-Type and other fields.
2358 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2360 !con
->got_fields
&& bufptr
< bufend
;
2363 if (*bufptr
== '\n')
2366 * Send line to client...
2369 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2373 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2375 if (!con
->sent_header
)
2378 * Handle redirection and CGI status codes...
2381 http_field_t field
; /* HTTP field */
2382 char *value
= strchr(con
->header
, ':');
2383 /* Value of field */
2388 while (isspace(*value
& 255))
2392 field
= httpFieldValue(con
->header
);
2394 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2396 httpSetField(con
->http
, field
, value
);
2398 if (field
== HTTP_FIELD_LOCATION
)
2400 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2401 con
->sent_header
= 2;
2404 con
->sent_header
= 1;
2406 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2408 con
->pipe_status
= (http_status_t
)atoi(value
);
2409 con
->sent_header
= 2;
2411 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2413 httpSetCookie(con
->http
, value
);
2414 con
->sent_header
= 1;
2422 con
->header_used
-= bufptr
- con
->header
;
2424 if (con
->header_used
> 0)
2425 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2427 bufptr
= con
->header
- 1;
2430 * See if the line was empty...
2435 con
->got_fields
= 1;
2437 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2438 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2439 httpSetLength(con
->http
, 0);
2441 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2443 if (con
->pipe_status
== HTTP_STATUS_OK
)
2445 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2447 cupsdCloseClient(con
);
2453 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2455 cupsdCloseClient(con
);
2463 else if (*bufptr
!= '\r')
2467 if (!con
->got_fields
)
2471 if (con
->header_used
> 0)
2473 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2475 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2476 httpError(con
->http
), strerror(httpError(con
->http
)));
2477 cupsdCloseClient(con
);
2481 if (httpIsChunked(con
->http
))
2482 httpFlushWrite(con
->http
);
2484 con
->bytes
+= con
->header_used
;
2486 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2489 bytes
= con
->header_used
;
2491 con
->header_used
= 0;
2496 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2497 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2499 if (!con
->sent_header
&& con
->pipe_pid
)
2500 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2503 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2505 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2507 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2509 if (httpWrite2(con
->http
, "", 0) < 0)
2511 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2512 httpError(con
->http
), strerror(httpError(con
->http
)));
2513 cupsdCloseClient(con
);
2518 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2519 httpFlushWrite(con
->http
);
2520 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2523 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2525 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2529 cupsdRemoveSelect(con
->file
);
2532 cupsdEndProcess(con
->pipe_pid
, 0);
2541 unlink(con
->filename
);
2542 cupsdClearString(&con
->filename
);
2547 ippDelete(con
->request
);
2548 con
->request
= NULL
;
2553 ippDelete(con
->response
);
2554 con
->response
= NULL
;
2557 cupsdClearString(&con
->command
);
2558 cupsdClearString(&con
->options
);
2559 cupsdClearString(&con
->query_string
);
2561 if (!httpGetKeepAlive(con
->http
))
2563 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2564 "Closing because Keep-Alive is disabled.");
2565 cupsdCloseClient(con
);
2570 cupsArrayRemove(ActiveClients
, con
);
2571 cupsdSetBusyState(0);
2578 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2581 static int /* O - 1 if modified since */
2583 cupsd_client_t
*con
, /* I - Client connection */
2584 struct stat
*filestats
) /* I - File information */
2586 const char *ptr
; /* Pointer into field */
2587 time_t date
; /* Time/date value */
2588 off_t size
; /* Size/length value */
2593 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2598 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "check_if_modified: filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"", filestats
, CUPS_LLCAST filestats
->st_size
, (int)filestats
->st_mtime
, ptr
);
2600 while (*ptr
!= '\0')
2602 while (isspace(*ptr
) || *ptr
== ';')
2605 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2608 size
= strtoll(ptr
, NULL
, 10);
2610 while (isdigit(*ptr
))
2613 else if (isalpha(*ptr
))
2615 date
= httpGetDateTime(ptr
);
2616 while (*ptr
!= '\0' && *ptr
!= ';')
2623 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2624 (date
< filestats
->st_mtime
&& date
!= 0) ||
2625 (size
== 0 && date
== 0));
2630 * 'compare_clients()' - Compare two client connections.
2633 static int /* O - Result of comparison */
2634 compare_clients(cupsd_client_t
*a
, /* I - First client */
2635 cupsd_client_t
*b
, /* I - Second client */
2636 void *data
) /* I - User data (not used) */
2651 * 'cupsd_start_tls()' - Start encryption on a connection.
2654 static int /* O - 0 on success, -1 on error */
2655 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2656 http_encryption_t e
) /* I - Encryption mode */
2658 if (httpEncryption(con
->http
, e
))
2660 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2661 cupsLastErrorString());
2665 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Connection now encrypted.");
2668 #endif /* HAVE_SSL */
2672 * 'get_file()' - Get a filename and state info.
2675 static char * /* O - Real filename */
2676 get_file(cupsd_client_t
*con
, /* I - Client connection */
2677 struct stat
*filestats
, /* O - File information */
2678 char *filename
, /* IO - Filename buffer */
2679 size_t len
) /* I - Buffer length */
2681 int status
; /* Status of filesystem calls */
2682 char *ptr
; /* Pointer info filename */
2683 size_t plen
; /* Remaining length after pointer */
2684 char language
[7], /* Language subdirectory, if any */
2685 dest
[1024]; /* Destination name */
2686 int perm_check
= 1; /* Do permissions check? */
2687 cupsd_printer_t
*p
; /* Printer */
2691 * Figure out the real filename...
2696 if (!strncmp(con
->uri
, "/help", 5) && (con
->uri
[5] == '/' || !con
->uri
[5]))
2699 * All help files are served by the help.cgi program...
2704 else if ((!strncmp(con
->uri
, "/ppd/", 5) || !strncmp(con
->uri
, "/printers/", 10) || !strncmp(con
->uri
, "/classes/", 9)) && !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
2706 strlcpy(dest
, strchr(con
->uri
+ 1, '/') + 1, sizeof(dest
));
2707 dest
[strlen(dest
) - 4] = '\0'; /* Strip .ppd */
2709 if ((p
= cupsdFindDest(dest
)) == NULL
)
2711 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2715 if (p
->type
& CUPS_PRINTER_CLASS
)
2717 int i
; /* Looping var */
2719 for (i
= 0; i
< p
->num_printers
; i
++)
2721 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
2723 snprintf(filename
, len
, "%s/ppd/%s.ppd", ServerRoot
, p
->printers
[i
]->name
);
2724 if (!access(filename
, 0))
2732 if (i
>= p
->num_printers
)
2736 snprintf(filename
, len
, "%s/ppd/%s.ppd", ServerRoot
, p
->name
);
2740 else if ((!strncmp(con
->uri
, "/icons/", 7) || !strncmp(con
->uri
, "/printers/", 10) || !strncmp(con
->uri
, "/classes/", 9)) && !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
2742 strlcpy(dest
, strchr(con
->uri
+ 1, '/') + 1, sizeof(dest
));
2743 dest
[strlen(dest
) - 4] = '\0'; /* Strip .png */
2745 if ((p
= cupsdFindDest(dest
)) == NULL
)
2747 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2751 if (p
->type
& CUPS_PRINTER_CLASS
)
2753 int i
; /* Looping var */
2755 for (i
= 0; i
< p
->num_printers
; i
++)
2757 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
2759 snprintf(filename
, len
, "%s/images/%s.png", CacheDir
, p
->printers
[i
]->name
);
2760 if (!access(filename
, 0))
2768 if (i
>= p
->num_printers
)
2772 snprintf(filename
, len
, "%s/images/%s.png", CacheDir
, p
->name
);
2774 if (access(filename
, F_OK
) < 0)
2775 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2779 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2780 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2781 else if (!strncmp(con
->uri
, "/strings/", 9) && !strcmp(con
->uri
+ strlen(con
->uri
) - 8, ".strings"))
2783 strlcpy(dest
, con
->uri
+ 9, sizeof(dest
));
2784 dest
[strlen(dest
) - 8] = '\0';
2786 if ((p
= cupsdFindDest(dest
)) == NULL
)
2788 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2794 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No strings files for \"%s\".", dest
);
2798 strlcpy(filename
, p
->strings
, len
);
2802 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2804 strlcpy(filename
, ConfigurationFile
, len
);
2808 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2810 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2811 strlcpy(filename
, AccessLog
, len
);
2812 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2813 strlcpy(filename
, ErrorLog
, len
);
2814 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2815 strlcpy(filename
, PageLog
, len
);
2821 else if (con
->language
)
2823 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2824 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2827 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2829 if ((ptr
= strchr(filename
, '?')) != NULL
)
2833 * Grab the status for this language; if there isn't a language-specific file
2834 * then fallback to the default one...
2837 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
2838 strncmp(con
->uri
, "/icons/", 7) &&
2839 strncmp(con
->uri
, "/ppd/", 5) &&
2840 strncmp(con
->uri
, "/rss/", 5) &&
2841 strncmp(con
->uri
, "/strings/", 9) &&
2842 strncmp(con
->uri
, "/admin/conf/", 12) &&
2843 strncmp(con
->uri
, "/admin/log/", 11))
2846 * Drop the country code...
2850 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2852 if ((ptr
= strchr(filename
, '?')) != NULL
)
2855 if ((status
= lstat(filename
, filestats
)) != 0)
2858 * Drop the language prefix and try the root directory...
2862 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2864 if ((ptr
= strchr(filename
, '?')) != NULL
)
2867 status
= lstat(filename
, filestats
);
2872 * If we've found a symlink, 404 the sucker to avoid disclosing information.
2875 if (!status
&& S_ISLNK(filestats
->st_mode
))
2877 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
2882 * Similarly, if the file/directory does not have world read permissions, do
2883 * not allow access...
2886 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
2888 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
2893 * If we've found a directory, get the index.html file instead...
2896 if (!status
&& S_ISDIR(filestats
->st_mode
))
2899 * Make sure the URI ends with a slash...
2902 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
2903 strlcat(con
->uri
, "/", sizeof(con
->uri
));
2906 * Find the directory index file, trying every language...
2911 if (status
&& language
[0])
2914 * Try a different language subset...
2918 language
[0] = '\0'; /* Strip country code */
2920 language
[0] = '\0'; /* Strip language */
2924 * Look for the index file...
2927 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2929 if ((ptr
= strchr(filename
, '?')) != NULL
)
2932 ptr
= filename
+ strlen(filename
);
2933 plen
= len
- (size_t)(ptr
- filename
);
2935 strlcpy(ptr
, "index.html", plen
);
2936 status
= lstat(filename
, filestats
);
2938 while (status
&& language
[0]);
2941 * If we've found a symlink, 404 the sucker to avoid disclosing information.
2944 if (!status
&& S_ISLNK(filestats
->st_mode
))
2946 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
2951 * Similarly, if the file/directory does not have world read permissions, do
2952 * not allow access...
2955 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
2957 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
2962 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
2972 * 'install_cupsd_conf()' - Install a configuration file.
2975 static http_status_t
/* O - Status */
2976 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
2978 char filename
[1024]; /* Configuration filename */
2979 cups_file_t
*in
, /* Input file */
2980 *out
; /* Output file */
2981 char buffer
[16384]; /* Copy buffer */
2982 ssize_t bytes
; /* Number of bytes */
2986 * Open the request file...
2989 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2991 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
2992 con
->filename
, strerror(errno
));
2997 * Open the new config file...
3000 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3006 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3010 * Copy from the request to the new config file...
3013 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3014 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3016 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3017 "Unable to copy to config file \"%s\": %s",
3018 ConfigurationFile
, strerror(errno
));
3023 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3024 cupsdUnlinkOrRemoveFile(filename
);
3030 * Close the files...
3035 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3039 * Remove the request file...
3042 cupsdUnlinkOrRemoveFile(con
->filename
);
3043 cupsdClearString(&con
->filename
);
3046 * Set the NeedReload flag...
3049 NeedReload
= RELOAD_CUPSD
;
3050 ReloadTime
= time(NULL
);
3053 * Return that the file was created successfully...
3056 return (HTTP_STATUS_CREATED
);
3059 * Common exit for errors...
3064 cupsdUnlinkOrRemoveFile(con
->filename
);
3065 cupsdClearString(&con
->filename
);
3067 return (HTTP_STATUS_SERVER_ERROR
);
3072 * 'is_cgi()' - Is the resource a CGI script/program?
3075 static int /* O - 1 = CGI, 0 = file */
3076 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3077 const char *filename
, /* I - Real filename */
3078 struct stat
*filestats
, /* I - File information */
3079 mime_type_t
*type
) /* I - MIME type */
3081 const char *options
; /* Options on URL */
3085 * Get the options, if any...
3088 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3091 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3095 * Check for known types...
3098 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3100 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
? type
->super
: "unknown", type
? type
->type
: "unknown");
3104 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3105 (filestats
->st_mode
& 0111))
3108 * "application/x-httpd-cgi" is a CGI script.
3111 cupsdSetString(&con
->command
, filename
);
3114 cupsdSetStringf(&con
->options
, " %s", options
);
3116 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3120 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
->super
, type
->type
);
3126 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3129 static int /* O - 0 if relative, 1 if absolute */
3130 is_path_absolute(const char *path
) /* I - Input path */
3133 * Check for a leading slash...
3140 * Check for "<" or quotes in the path and reject since this is probably
3141 * someone trying to inject HTML...
3144 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3148 * Check for "/.." in the path...
3151 while ((path
= strstr(path
, "/..")) != NULL
)
3153 if (!path
[3] || path
[3] == '/')
3160 * If we haven't found any relative paths, return 1 indicating an
3169 * 'pipe_command()' - Pipe the output of a command to the remote client.
3172 static int /* O - Process ID */
3173 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3174 int infile
, /* I - Standard input for command */
3175 int *outfile
, /* O - Standard output for command */
3176 char *command
, /* I - Command to run */
3177 char *options
, /* I - Options for command */
3178 int root
) /* I - Run as root? */
3180 int i
; /* Looping var */
3181 int pid
; /* Process ID */
3182 char *commptr
, /* Command string pointer */
3183 commch
; /* Command string character */
3184 char *uriptr
; /* URI string pointer */
3185 int fds
[2]; /* Pipe FDs */
3186 int argc
; /* Number of arguments */
3187 int envc
; /* Number of environment variables */
3188 char argbuf
[10240], /* Argument buffer */
3189 *argv
[100], /* Argument strings */
3190 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3191 char auth_type
[256], /* AUTH_TYPE environment variable */
3192 content_length
[1024], /* CONTENT_LENGTH environment variable */
3193 content_type
[1024], /* CONTENT_TYPE environment variable */
3194 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3195 http_referer
[1024], /* HTTP_REFERER environment variable */
3196 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3197 lang
[1024], /* LANG environment variable */
3198 path_info
[1024], /* PATH_INFO environment variable */
3199 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3200 remote_host
[1024], /* REMOTE_HOST environment variable */
3201 remote_user
[1024], /* REMOTE_USER environment variable */
3202 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3203 script_name
[1024], /* SCRIPT_NAME environment variable */
3204 server_name
[1024], /* SERVER_NAME environment variable */
3205 server_port
[1024]; /* SERVER_PORT environment variable */
3206 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3210 * Parse a copy of the options string, which is of the form:
3212 * argument+argument+argument
3213 * ?argument+argument+argument
3214 * param=value¶m=value
3215 * ?param=value¶m=value
3216 * /name?argument+argument+argument
3217 * /name?param=value¶m=value
3219 * If the string contains an "=" character after the initial name,
3220 * then we treat it as a HTTP GET form request and make a copy of
3221 * the remaining string for the environment variable.
3223 * The string is always parsed out as command-line arguments, to
3224 * be consistent with Apache...
3227 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, outfile
, command
, options
? options
: "(null)", root
);
3232 strlcpy(argbuf
, options
, sizeof(argbuf
));
3236 if (argbuf
[0] == '/')
3239 * Found some trailing path information, set PATH_INFO...
3242 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3243 commptr
= argbuf
+ strlen(argbuf
);
3247 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3253 path_info
[0] = '\0';
3255 if (*commptr
== ' ')
3259 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3262 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3269 argv
[argc
++] = commptr
;
3271 for (; *commptr
&& argc
< 99; commptr
++)
3274 * Break arguments whenever we see a + or space...
3277 if (*commptr
== ' ' || *commptr
== '+')
3279 while (*commptr
== ' ' || *commptr
== '+')
3283 * If we don't have a blank string, save it as another argument...
3288 argv
[argc
] = commptr
;
3294 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3295 isxdigit(commptr
[2] & 255))
3298 * Convert the %xx notation to the individual character.
3301 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3302 *commptr
= (char)((commptr
[1] - '0') << 4);
3304 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3306 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3307 *commptr
|= commptr
[2] - '0';
3309 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3311 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3314 * Check for a %00 and break if that is the case...
3326 * Setup the environment variables as needed...
3329 if (con
->username
[0])
3331 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3332 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3334 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3338 auth_type
[0] = '\0';
3340 if (con
->request
&& (attr
= ippFindAttribute(con
->request
, "attributes-natural-language", IPP_TAG_LANGUAGE
)) != NULL
)
3342 cups_lang_t
*language
= cupsLangGet(ippGetString(attr
, 0, NULL
));
3344 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", language
->language
);
3345 cupsLangFree(language
);
3347 else if (con
->language
)
3348 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3350 strlcpy(lang
, "LANG=C", sizeof(lang
));
3352 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3353 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3354 sizeof(remote_addr
) - 12);
3356 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3357 httpGetHostname(con
->http
, NULL
, 0));
3359 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3360 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3363 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3364 DocumentRoot
, script_name
+ 12);
3366 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3368 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3370 char *nameptr
; /* Pointer to ":port" */
3372 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3373 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3374 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3375 *nameptr
= '\0'; /* Strip trailing ":port" */
3378 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3381 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3384 envp
[envc
++] = auth_type
;
3386 envp
[envc
++] = lang
;
3387 envp
[envc
++] = "REDIRECT_STATUS=1";
3388 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3389 envp
[envc
++] = server_name
;
3390 envp
[envc
++] = server_port
;
3391 envp
[envc
++] = remote_addr
;
3392 envp
[envc
++] = remote_host
;
3393 envp
[envc
++] = script_name
;
3394 envp
[envc
++] = script_filename
;
3397 envp
[envc
++] = path_info
;
3399 if (con
->username
[0])
3401 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3403 envp
[envc
++] = remote_user
;
3406 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3407 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3408 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3409 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3411 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3413 if (httpGetCookie(con
->http
))
3415 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3416 httpGetCookie(con
->http
));
3417 envp
[envc
++] = http_cookie
;
3420 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3422 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3423 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3424 envp
[envc
++] = http_user_agent
;
3427 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3429 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3430 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3431 envp
[envc
++] = http_referer
;
3434 if (con
->operation
== HTTP_STATE_GET
)
3436 envp
[envc
++] = "REQUEST_METHOD=GET";
3438 if (con
->query_string
)
3441 * Add GET form variables after ?...
3444 envp
[envc
++] = con
->query_string
;
3447 envp
[envc
++] = "QUERY_STRING=";
3451 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3452 CUPS_LLCAST con
->bytes
);
3453 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3454 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3456 envp
[envc
++] = "REQUEST_METHOD=POST";
3457 envp
[envc
++] = content_length
;
3458 envp
[envc
++] = content_type
;
3462 * Tell the CGI if we are using encryption...
3465 if (httpIsEncrypted(con
->http
))
3466 envp
[envc
++] = "HTTPS=ON";
3469 * Terminate the environment array...
3474 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3476 for (i
= 0; i
< argc
; i
++)
3477 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3478 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3479 for (i
= 0; i
< envc
; i
++)
3480 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3481 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3485 * Create a pipe for the output...
3488 if (cupsdOpenPipe(fds
))
3490 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3491 argv
[0], strerror(errno
));
3496 * Then execute the command...
3499 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3500 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3503 * Error - can't fork!
3506 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3509 cupsdClosePipe(fds
);
3515 * Fork successful - return the PID...
3518 if (con
->username
[0])
3519 cupsdAddCert(pid
, con
->username
, con
->type
);
3521 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3532 * 'valid_host()' - Is the Host: field valid?
3535 static int /* O - 1 if valid, 0 if not */
3536 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3538 cupsd_alias_t
*a
; /* Current alias */
3539 cupsd_netif_t
*netif
; /* Current network interface */
3540 const char *end
; /* End character */
3541 char *ptr
; /* Pointer into host value */
3545 * Copy the Host: header for later use...
3548 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3549 sizeof(con
->clientname
));
3550 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3553 con
->clientport
= atoi(ptr
);
3556 con
->clientport
= con
->serverport
;
3562 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3565 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3566 * addresses when accessing CUPS via the loopback interface...
3569 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3570 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3571 !strcmp(con
->clientname
, "127.0.0.1") ||
3572 !strcmp(con
->clientname
, "[::1]"));
3575 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3577 * Check if the hostname is something.local (Bonjour); if so, allow it.
3580 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3584 * "." on end, work back to second-to-last "."...
3587 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3590 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3591 !_cups_strcasecmp(end
, ".local.")))
3593 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3596 * Check if the hostname is an IP address...
3599 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3602 * Possible IPv4/IPv6 address...
3605 http_addrlist_t
*addrlist
; /* List of addresses */
3608 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3611 * Good IPv4/IPv6 address...
3614 httpAddrFreeList(addrlist
);
3620 * Check for (alias) name matches...
3623 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3625 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3628 * "ServerAlias *" allows all host values through...
3631 if (!strcmp(a
->name
, "*"))
3634 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3637 * Prefix matches; check the character at the end - it must be "." or nul.
3640 end
= con
->clientname
+ a
->namelen
;
3642 if (!*end
|| (*end
== '.' && !end
[1]))
3647 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3648 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3650 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3653 * "ServerAlias *" allows all host values through...
3656 if (!strcmp(a
->name
, "*"))
3659 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3662 * Prefix matches; check the character at the end - it must be "." or nul.
3665 end
= con
->clientname
+ a
->namelen
;
3667 if (!*end
|| (*end
== '.' && !end
[1]))
3671 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3674 * Check for interface hostname matches...
3677 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3679 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3681 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3684 * Prefix matches; check the character at the end - it must be "." or nul.
3687 end
= con
->clientname
+ netif
->hostlen
;
3689 if (!*end
|| (*end
== '.' && !end
[1]))
3699 * 'write_file()' - Send a file via HTTP.
3702 static int /* O - 0 on failure, 1 on success */
3703 write_file(cupsd_client_t
*con
, /* I - Client connection */
3704 http_status_t code
, /* I - HTTP status */
3705 char *filename
, /* I - Filename */
3706 char *type
, /* I - File type */
3707 struct stat
*filestats
) /* O - File information */
3709 con
->file
= open(filename
, O_RDONLY
);
3711 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3716 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3719 con
->sent_header
= 1;
3721 httpClearFields(con
->http
);
3723 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
3725 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3726 httpGetDateString(filestats
->st_mtime
));
3728 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3731 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3733 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3740 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3744 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3746 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
3748 con
->file_ready
= 1;
3750 cupsdRemoveSelect(con
->file
);
3751 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3753 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");