2 * Client routines for the CUPS scheduler.
4 * Copyright © 2020-2025 by OpenPrinting.
5 * Copyright © 2007-2021 by Apple Inc.
6 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
8 * This file contains Kerberos support code, copyright 2006 by
11 * Licensed under Apache License v2.0. See the file "LICENSE" for more
15 #define _CUPS_NO_DEPRECATED
16 #define _HTTP_NO_PRIVATE
21 #endif /* __APPLE__ */
24 #endif /* HAVE_TCPD_H */
31 static int check_if_modified(cupsd_client_t
*con
,
32 struct stat
*filestats
);
33 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
, void *data
);
34 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
35 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
, char *filename
, size_t len
);
36 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
37 static int is_cgi(cupsd_client_t
*con
, const char *filename
, struct stat
*filestats
, mime_type_t
*type
);
38 static int is_path_absolute(const char *path
);
39 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
, char *command
, char *options
, int root
);
40 static int valid_host(cupsd_client_t
*con
);
41 static int write_file(cupsd_client_t
*con
, http_status_t code
, char *filename
, char *type
, struct stat
*filestats
);
42 static void write_pipe(cupsd_client_t
*con
);
46 * 'cupsdAcceptClient()' - Accept a new client.
50 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
52 const char *hostname
; /* Hostname of client */
53 char name
[256]; /* Hostname of client */
54 int count
; /* Count of connections on a host */
55 cupsd_client_t
*con
, /* New client pointer */
56 *tempcon
; /* Temporary client pointer */
57 socklen_t addrlen
; /* Length of address */
58 http_addr_t temp
; /* Temporary address variable */
59 static time_t last_dos
= 0; /* Time of last DoS attack */
61 struct request_info wrap_req
; /* TCP wrappers request information */
62 #endif /* HAVE_TCPD_H */
65 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", (void *)lis
, lis
->fd
, cupsArrayGetCount(Clients
));
68 * Make sure we don't have a full set of clients already...
71 if (MaxClients
&& cupsArrayGetCount(Clients
) >= MaxClients
)
77 * Get a pointer to the next available client...
81 Clients
= cupsArrayNew3(NULL
, NULL
, NULL
, 0, NULL
, NULL
);
85 cupsdLogMessage(CUPSD_LOG_ERROR
,
86 "Unable to allocate memory for clients array!");
87 cupsdPauseListening();
92 ActiveClients
= cupsArrayNew3((cups_array_func_t
)compare_clients
, NULL
, NULL
, 0, NULL
, NULL
);
96 cupsdLogMessage(CUPSD_LOG_ERROR
,
97 "Unable to allocate memory for active clients array!");
98 cupsdPauseListening();
102 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
104 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
105 cupsdPauseListening();
110 * Accept the client and get the remote address...
113 con
->number
= ++ LastClientNumber
;
116 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
118 if (errno
== ENFILE
|| errno
== EMFILE
)
119 cupsdPauseListening();
121 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
129 * Save the connected address and port number...
132 addrlen
= sizeof(con
->clientaddr
);
134 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&con
->clientaddr
, &addrlen
) || addrlen
== 0)
135 con
->clientaddr
= lis
->address
;
137 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Server address is \"%s\".", httpAddrGetString(&con
->clientaddr
, name
, sizeof(name
)));
140 * Check the number of clients on the same address...
143 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayGetFirst(Clients
);
145 tempcon
= (cupsd_client_t
*)cupsArrayGetNext(Clients
))
146 if (httpAddrIsEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
149 if (count
>= MaxClientsPerHost
)
153 if (count
>= MaxClientsPerHost
)
155 if ((time(NULL
) - last_dos
) >= 60)
157 last_dos
= time(NULL
);
158 cupsdLogMessage(CUPSD_LOG_WARN
,
159 "Possible DoS attack - more than %d clients connecting "
162 httpGetHostname(con
->http
, name
, sizeof(name
)));
165 httpClose(con
->http
);
171 * Get the hostname or format the IP address as needed...
175 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
177 hostname
= httpGetHostname(con
->http
, NULL
, 0);
179 if (hostname
== NULL
&& HostNameLookups
== 2)
182 * Can't have an unresolved IP address with double-lookups enabled...
184 cupsdLogClient(con
, CUPSD_LOG_WARN
,
185 "Name lookup failed - closing connection from %s!",
186 httpGetHostname(con
->http
, NULL
, 0));
188 httpClose(con
->http
);
193 if (HostNameLookups
== 2)
196 * Do double lookups as needed...
199 http_addrlist_t
*addrlist
, /* List of addresses */
200 *addr
; /* Current address */
202 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
205 * See if the hostname maps to the same IP address...
208 for (addr
= addrlist
; addr
; addr
= addr
->next
)
209 if (httpAddrIsEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
215 httpAddrFreeList(addrlist
);
220 * Can't have a hostname that doesn't resolve to the same IP address
221 * with double-lookups enabled...
224 cupsdLogClient(con
, CUPSD_LOG_WARN
,
225 "IP lookup failed - closing connection from %s!",
226 httpGetHostname(con
->http
, NULL
, 0));
228 httpClose(con
->http
);
236 * See if the connection is denied by TCP wrappers...
239 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
243 if (!hosts_access(&wrap_req
))
245 cupsdLogClient(con
, CUPSD_LOG_WARN
,
246 "Connection from %s refused by /etc/hosts.allow and "
247 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
249 httpClose(con
->http
);
253 #endif /* HAVE_TCPD_H */
256 if (httpAddrGetFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
259 socklen_t peersize
; /* Size of peer credentials */
260 pid_t peerpid
; /* Peer process ID */
261 char peername
[256]; /* Name of process */
263 peersize
= sizeof(peerpid
);
264 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
267 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
268 cupsdLogClient(con
, CUPSD_LOG_INFO
,
269 "Accepted from %s (Domain ???[%d])",
270 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
272 cupsdLogClient(con
, CUPSD_LOG_INFO
,
273 "Accepted from %s (Domain %s[%d])",
274 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
277 # endif /* __APPLE__ */
279 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Accepted from %s (Domain)",
280 httpGetHostname(con
->http
, NULL
, 0));
283 #endif /* AF_LOCAL */
284 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Accepted from %s:%d (IPv%d)",
285 httpGetHostname(con
->http
, NULL
, 0),
286 httpAddrGetPort(httpGetAddress(con
->http
)),
287 httpAddrGetFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
290 * Get the local address the client connected to...
293 addrlen
= sizeof(temp
);
294 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
296 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
299 cupsCopyString(con
->servername
, "localhost", sizeof(con
->servername
));
300 con
->serverport
= LocalPort
;
303 else if (httpAddrGetFamily(&temp
) == AF_LOCAL
)
305 cupsCopyString(con
->servername
, "localhost", sizeof(con
->servername
));
306 con
->serverport
= LocalPort
;
308 #endif /* AF_LOCAL */
311 if (httpAddrIsLocalhost(&temp
))
312 cupsCopyString(con
->servername
, "localhost", sizeof(con
->servername
));
313 else if (HostNameLookups
)
314 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
316 httpAddrGetString(&temp
, con
->servername
, sizeof(con
->servername
));
318 con
->serverport
= httpAddrGetPort(&(lis
->address
));
322 * Apply ServerHeader if any...
326 httpSetDefaultField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
329 * Add the connection to the array of active clients...
332 cupsArrayAdd(Clients
, con
);
335 * Add the socket to the server select.
338 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
341 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
344 * Temporarily suspend accept()'s until we lose a client...
347 if (cupsArrayGetCount(Clients
) == MaxClients
)
348 cupsdPauseListening();
351 * See if we are connecting on a secure port...
354 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
357 * https connection; go secure...
360 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
361 cupsdCloseClient(con
);
369 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
373 cupsdCloseAllClients(void)
375 cupsd_client_t
*con
; /* Current client */
378 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d", cupsArrayGetCount(Clients
));
380 for (con
= (cupsd_client_t
*)cupsArrayGetFirst(Clients
);
382 con
= (cupsd_client_t
*)cupsArrayGetNext(Clients
))
383 if (cupsdCloseClient(con
))
384 cupsdCloseClient(con
);
389 * 'cupsdCloseClient()' - Close a remote client.
392 int /* O - 1 if partial close, 0 if fully closed */
393 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
395 int partial
; /* Do partial close for SSL? */
398 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Closing connection.");
401 * Flush pending writes before closing...
404 httpFlushWrite(con
->http
);
408 if (con
->pipe_pid
!= 0)
411 * Stop any CGI process...
414 cupsdEndProcess(con
->pipe_pid
, 1);
420 cupsdRemoveSelect(con
->file
);
429 * Don't close connection when there is a background thread pending
436 * Close the socket and clear the file from the input set for select()...
439 if (httpGetFd(con
->http
) >= 0)
441 cupsArrayRemove(ActiveClients
, con
);
442 cupsdSetBusyState(0);
445 * Shutdown encryption as needed...
448 if (httpIsEncrypted(con
->http
))
451 if (partial
&& !httpGetError(con
->http
))
454 * Only do a partial close so that the encrypted client gets everything.
457 httpShutdown(con
->http
);
458 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
461 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
466 * Shut the socket down fully...
469 cupsdRemoveSelect(httpGetFd(con
->http
));
470 httpClose(con
->http
);
481 cupsdRemoveSelect(httpGetFd(con
->http
));
483 httpClose(con
->http
);
487 unlink(con
->filename
);
488 cupsdClearString(&con
->filename
);
491 cupsdClearString(&con
->command
);
492 cupsdClearString(&con
->options
);
493 cupsdClearString(&con
->query_string
);
497 ippDelete(con
->request
);
503 ippDelete(con
->response
);
504 con
->response
= NULL
;
509 cupsLangFree(con
->language
);
510 con
->language
= NULL
;
513 #ifdef HAVE_AUTHORIZATION_H
516 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
519 #endif /* HAVE_AUTHORIZATION_H */
522 * Re-enable new client connections if we are going back under the
526 if (cupsArrayGetCount(Clients
) == MaxClients
)
527 cupsdResumeListening();
530 * Compact the list of clients as necessary...
533 cupsArrayRemove(Clients
, con
);
543 * 'cupsdReadClient()' - Read data from a client.
547 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
549 char line
[32768], /* Line from client... */
550 locale
[64], /* Locale */
551 name
[128], /* Class/Printer name */
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", httpGetError(con
->http
), (int)httpGetReady(con
->http
), httpStateString(httpGetState(con
->http
)), httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH", CUPS_LLCAST
httpGetRemaining(con
->http
), (void *)con
->request
, con
->request
? ippStateString(ippGetState(con
->request
)) : "", con
->file
);
567 if (httpGetError(con
->http
) == EPIPE
&& !httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
570 * Connection closed...
573 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
574 cupsdCloseClient(con
);
578 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
579 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
580 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
583 * If we get called in the wrong state, then something went wrong with the
584 * connection and we need to shut it down...
587 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con
->http
)));
588 cupsdCloseClient(con
);
595 * Automatically check for a SSL/TLS handshake...
600 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
601 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
604 * Encrypt this connection...
607 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf
[0] & 255);
609 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
610 cupsdCloseClient(con
);
616 switch (httpGetState(con
->http
))
618 case HTTP_STATE_WAITING
:
620 * See if we've received a request line...
623 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
624 if (con
->operation
== HTTP_STATE_ERROR
||
625 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
626 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
628 if (httpGetError(con
->http
))
630 if (httpGetError(con
->http
) != EPIPE
)
631 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "HTTP_STATE_WAITING Closing for error %d (%s)", httpGetError(con
->http
), strerror(httpGetError(con
->http
)));
633 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "HTTP_STATE_WAITING Closing on EOF.");
637 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "HTTP_STATE_WAITING Closing on error: %s", cupsGetErrorString());
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';
660 con
->realname
[0] = '\0';
661 con
->email
[0] = '\0';
662 con
->autherror
[0] = '\0';
664 cupsdClearString(&con
->command
);
665 cupsdClearString(&con
->options
);
666 cupsdClearString(&con
->query_string
);
670 ippDelete(con
->request
);
676 ippDelete(con
->response
);
677 con
->response
= NULL
;
682 cupsLangFree(con
->language
);
683 con
->language
= NULL
;
689 #endif /* HAVE_GSSAPI */
692 * Handle full URLs in the request line...
695 if (strcmp(con
->uri
, "*"))
697 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
698 userpass
[HTTP_MAX_URI
], /* Username:password */
699 hostname
[HTTP_MAX_URI
], /* Hostname */
700 resource
[HTTP_MAX_URI
]; /* Resource path */
701 int port
; /* Port number */
704 * Separate the URI into its components...
707 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
708 scheme
, sizeof(scheme
),
709 userpass
, sizeof(userpass
),
710 hostname
, sizeof(hostname
), &port
,
711 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
713 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
715 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
716 cupsdCloseClient(con
);
721 * Only allow URIs with the servername, localhost, or an IP
725 if (strcmp(scheme
, "file") &&
726 _cups_strcasecmp(hostname
, ServerName
) &&
727 _cups_strcasecmp(hostname
, "localhost") &&
728 !cupsArrayFind(ServerAlias
, hostname
) &&
729 !isdigit(hostname
[0]) && hostname
[0] != '[')
732 * Nope, we don't do proxies...
735 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
737 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
738 cupsdCloseClient(con
);
743 * Copy the resource portion back into the URI; both resource and
744 * con->uri are HTTP_MAX_URI bytes in size...
747 cupsCopyString(con
->uri
, resource
, sizeof(con
->uri
));
751 * Process the request...
754 gettimeofday(&(con
->start
), NULL
);
756 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
757 httpStateString(con
->operation
), con
->uri
,
758 httpGetVersion(con
->http
) / 100,
759 httpGetVersion(con
->http
) % 100);
761 if (!cupsArrayFind(ActiveClients
, con
))
763 cupsArrayAdd(ActiveClients
, con
);
764 cupsdSetBusyState(0);
767 case HTTP_STATE_OPTIONS
:
768 case HTTP_STATE_DELETE
:
769 case HTTP_STATE_GET
:
770 case HTTP_STATE_HEAD
:
771 case HTTP_STATE_POST
:
772 case HTTP_STATE_PUT
:
773 case HTTP_STATE_TRACE
:
775 * Parse incoming parameters until the status changes...
778 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
779 if (!httpGetReady(con
->http
))
782 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
784 if (httpGetError(con
->http
) && httpGetError(con
->http
) != EPIPE
)
785 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
786 "Closing for error %d (%s) while reading headers.",
787 httpGetError(con
->http
), strerror(httpGetError(con
->http
)));
789 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
790 "Closing on EOF while reading headers.");
792 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
793 cupsdCloseClient(con
);
799 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
802 * Connection closed...
805 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
806 cupsdCloseClient(con
);
809 break; /* Anti-compiler-warning-code */
813 * Handle new transfers...
816 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Read: status=%d, state=%d", status
, httpGetState(con
->http
));
818 if (status
== HTTP_STATUS_OK
)
821 * Record whether the client is a web browser. "Mozilla" was the original
822 * and it seems that every web browser in existence now uses that as the
823 * prefix with additional information identifying *which* browser.
825 * Chrome (at least) has problems with multiple WWW-Authenticate values in
826 * a single header, so we only report Basic or Negotiate to web browsers and
827 * leave the multiple choices to the native CUPS client...
830 con
->is_browser
= !strncmp(httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
), "Mozilla/", 8);
832 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
835 * Figure out the locale from the Accept-Language and Content-Type
839 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
843 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
847 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
848 "charset=")) != NULL
)
851 * Combine language and charset, and trim any extra params in the
855 snprintf(locale
, sizeof(locale
), "%s.%s",
856 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
858 if ((ptr
= strchr(locale
, ',')) != NULL
)
862 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
863 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
865 con
->language
= cupsLangGet(locale
);
868 con
->language
= cupsLangGet(DefaultLocale
);
872 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
873 "Keep-Alive", 10) && KeepAlive
)
874 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
875 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
877 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
879 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
880 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
883 * HTTP/1.1 and higher require the "Host:" field...
886 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
888 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
889 cupsdCloseClient(con
);
893 else if (!valid_host(con
))
896 * Access to localhost must use "localhost" or the corresponding IPv4
897 * or IPv6 values in the Host: field.
900 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
901 "Request from \"%s\" using invalid Host: field \"%s\".",
902 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
904 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
906 cupsdCloseClient(con
);
910 else if (con
->operation
== HTTP_STATE_OPTIONS
)
913 * Do OPTIONS command...
916 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
918 httpClearFields(con
->http
);
919 httpClearCookie(con
->http
);
921 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
923 cupsdCloseClient(con
);
928 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
931 * Do encryption stuff...
934 httpClearFields(con
->http
);
935 httpClearCookie(con
->http
);
937 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
939 cupsdCloseClient(con
);
943 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
945 cupsdCloseClient(con
);
950 httpClearFields(con
->http
);
951 httpClearCookie(con
->http
);
952 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
954 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
956 cupsdCloseClient(con
);
960 else if (!is_path_absolute(con
->uri
))
963 * Protect against malicious users!
966 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
967 "Request for non-absolute resource \"%s\".", con
->uri
);
969 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
971 cupsdCloseClient(con
);
977 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
978 "Upgrade") && !httpIsEncrypted(con
->http
))
981 * Do encryption stuff...
984 httpClearFields(con
->http
);
985 httpClearCookie(con
->http
);
987 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
990 cupsdCloseClient(con
);
994 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
996 cupsdCloseClient(con
);
1001 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1003 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1004 cupsdCloseClient(con
);
1008 if (httpGetExpect(con
->http
) &&
1009 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1011 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1014 * Send 100-continue header...
1017 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1019 cupsdCloseClient(con
);
1026 * Send 417-expectation-failed header...
1029 httpClearFields(con
->http
);
1030 httpClearCookie(con
->http
);
1031 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1033 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1034 cupsdCloseClient(con
);
1039 switch (httpGetState(con
->http
))
1041 case HTTP_STATE_GET_SEND
:
1042 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1044 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1046 cupsRWLockRead(&MimeDatabase
->lock
);
1048 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1050 cupsRWUnlock(&MimeDatabase
->lock
);
1052 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1054 if (is_cgi(con
, filename
, &filestats
, type
))
1057 * Note: con->command and con->options were set by is_cgi()...
1060 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1062 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1064 cupsdCloseClient(con
);
1069 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1071 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1072 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1076 if (!check_if_modified(con
, &filestats
))
1078 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1080 cupsdCloseClient(con
);
1087 cupsCopyString(line
, "text/plain", sizeof(line
));
1089 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1091 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1093 cupsdCloseClient(con
);
1098 else if (!buf
[0] && (!strcmp(con
->uri
, "/") || !strncmp(con
->uri
, "/?", 2) || !strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/help", 5) || !strncmp(con
->uri
, "/jobs", 5) || !strncmp(con
->uri
, "/printers", 9)))
1103 * Web interface is disabled. Show an appropriate message...
1106 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1108 cupsdCloseClient(con
);
1116 * Send CGI output...
1119 if (!strcmp(con
->uri
, "/") || !strncmp(con
->uri
, "/?", 2))
1121 cupsdSetStringf(&con
->command
, "%s/cgi-bin/home.cgi", ServerBin
);
1122 cupsdSetString(&con
->options
, strchr(con
->uri
+ 1, '?'));
1124 else if (!strncmp(con
->uri
, "/admin", 6))
1126 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1127 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1129 else if (!strncmp(con
->uri
, "/classes", 8))
1131 if (strlen(con
->uri
) > 9)
1133 if (con
->uri
[9] != '?')
1135 unsigned int i
= 0; // Array index
1137 for (ptr
= con
->uri
+ 9; *ptr
&& *ptr
!= '?' && i
< sizeof(name
);)
1142 if (!cupsdFindClass(name
))
1144 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1146 cupsdCloseClient(con
);
1155 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1156 if (con
->uri
[8] && con
->uri
[9])
1157 cupsdSetString(&con
->options
, con
->uri
+ 8);
1159 cupsdSetString(&con
->options
, NULL
);
1161 else if (!strncmp(con
->uri
, "/jobs", 5))
1163 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1164 if (con
->uri
[5] && con
->uri
[6])
1165 cupsdSetString(&con
->options
, con
->uri
+ 5);
1167 cupsdSetString(&con
->options
, NULL
);
1169 else if (!strncmp(con
->uri
, "/printers", 9))
1171 if (strlen(con
->uri
) > 10)
1173 if (con
->uri
[10] != '?')
1175 unsigned int i
= 0; // Array index
1177 for (ptr
= con
->uri
+ 10; *ptr
&& *ptr
!= '?' && i
< sizeof(name
);)
1182 if (!cupsdFindPrinter(name
))
1184 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1186 cupsdCloseClient(con
);
1195 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1196 if (con
->uri
[9] && con
->uri
[10])
1197 cupsdSetString(&con
->options
, con
->uri
+ 9);
1199 cupsdSetString(&con
->options
, NULL
);
1203 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1204 if (con
->uri
[5] && con
->uri
[6])
1205 cupsdSetString(&con
->options
, con
->uri
+ 5);
1207 cupsdSetString(&con
->options
, NULL
);
1210 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1212 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1214 cupsdCloseClient(con
);
1219 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1221 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1222 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1226 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1228 cupsdCloseClient(con
);
1234 case HTTP_STATE_POST_RECV
:
1236 * See if the POST request includes a Content-Length field, and if
1237 * so check the length against any limits that are set...
1240 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] && MaxRequestSize
> 0 && httpGetLength2(con
->http
) > MaxRequestSize
)
1243 * Request too large...
1246 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1248 cupsdCloseClient(con
);
1254 else if (httpGetLength2(con
->http
) < 0)
1257 * Negative content lengths are invalid!
1260 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1262 cupsdCloseClient(con
);
1270 * See what kind of POST request this is; for IPP requests the
1271 * content-type field will be "application/ipp"...
1274 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
), "application/ipp"))
1276 con
->request
= ippNew();
1279 else if (!WebInterface
)
1282 * Web interface is disabled. Show an appropriate message...
1285 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1287 cupsdCloseClient(con
);
1294 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1300 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1302 if (!is_cgi(con
, filename
, &filestats
, type
))
1305 * Only POST to CGI's...
1308 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1310 cupsdCloseClient(con
);
1315 else if (!strcmp(con
->uri
, "/") || !strncmp(con
->uri
, "/?", 2) || !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))
1321 if (!strcmp(con
->uri
, "/") || !strncmp(con
->uri
, "/?", 2))
1323 cupsdSetStringf(&con
->command
, "%s/cgi-bin/home.cgi", ServerBin
);
1324 cupsdSetString(&con
->options
, strchr(con
->uri
+ 1, '?'));
1326 else if (!strncmp(con
->uri
, "/admin", 6))
1328 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1329 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1331 else if (!strncmp(con
->uri
, "/printers", 9))
1333 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1334 if (con
->uri
[9] && con
->uri
[10])
1335 cupsdSetString(&con
->options
, con
->uri
+ 9);
1337 cupsdSetString(&con
->options
, NULL
);
1339 else if (!strncmp(con
->uri
, "/classes", 8))
1341 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1342 if (con
->uri
[8] && con
->uri
[9])
1343 cupsdSetString(&con
->options
, con
->uri
+ 8);
1345 cupsdSetString(&con
->options
, NULL
);
1347 else if (!strncmp(con
->uri
, "/jobs", 5))
1349 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1350 if (con
->uri
[5] && con
->uri
[6])
1351 cupsdSetString(&con
->options
, con
->uri
+ 5);
1353 cupsdSetString(&con
->options
, NULL
);
1357 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1358 if (con
->uri
[5] && con
->uri
[6])
1359 cupsdSetString(&con
->options
, con
->uri
+ 5);
1361 cupsdSetString(&con
->options
, NULL
);
1364 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1365 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1369 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1371 cupsdCloseClient(con
);
1377 case HTTP_STATE_PUT_RECV
:
1379 * Validate the resource name...
1382 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1385 * PUT can only be done to the cupsd.conf file...
1388 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Disallowed PUT request for \"%s\".", con
->uri
);
1390 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1392 cupsdCloseClient(con
);
1400 * See if the PUT request includes a Content-Length field, and if
1401 * so check the length against any limits that are set...
1404 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] && MaxRequestSize
> 0 && httpGetLength2(con
->http
) > MaxRequestSize
)
1407 * Request too large...
1410 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1412 cupsdCloseClient(con
);
1418 else if (httpGetLength2(con
->http
) < 0)
1421 * Negative content lengths are invalid!
1424 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1426 cupsdCloseClient(con
);
1434 * Open a temporary file to hold the request...
1437 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1438 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1442 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to create request file \"%s\": %s", con
->filename
, strerror(errno
));
1444 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1446 cupsdCloseClient(con
);
1451 fchmod(con
->file
, 0640);
1452 fchown(con
->file
, RunUser
, Group
);
1453 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1456 case HTTP_STATE_DELETE
:
1457 case HTTP_STATE_TRACE
:
1458 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1459 cupsdCloseClient(con
);
1462 case HTTP_STATE_HEAD
:
1463 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1465 if (!check_if_modified(con
, &filestats
))
1467 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1469 cupsdCloseClient(con
);
1473 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1481 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1483 cupsCopyString(line
, "text/plain", sizeof(line
));
1485 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1487 httpClearFields(con
->http
);
1488 httpClearCookie(con
->http
);
1490 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
, httpGetDateString(filestats
.st_mtime
));
1491 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1493 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1495 cupsdCloseClient(con
);
1499 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1502 else if (!WebInterface
)
1504 httpClearFields(con
->http
);
1505 httpClearCookie(con
->http
);
1507 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1509 cupsdCloseClient(con
);
1513 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1517 if (!buf
[0] && (!strcmp(con
->uri
, "/") || !strncmp(con
->uri
, "/?", 2) || !strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/help", 5) || !strncmp(con
->uri
, "/jobs", 5) || !strncmp(con
->uri
, "/printers", 9)))
1523 httpClearFields(con
->http
);
1524 httpClearCookie(con
->http
);
1526 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1528 cupsdCloseClient(con
);
1532 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1536 httpClearFields(con
->http
);
1537 httpClearCookie(con
->http
);
1539 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1541 cupsdCloseClient(con
);
1545 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1550 break; /* Anti-compiler-warning-code */
1556 * Handle any incoming data...
1559 switch (httpGetState(con
->http
))
1561 case HTTP_STATE_PUT_RECV
:
1564 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1566 if (httpGetError(con
->http
) && httpGetError(con
->http
) != EPIPE
)
1567 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1568 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1569 httpGetError(con
->http
), strerror(httpGetError(con
->http
)));
1571 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1572 "HTTP_STATE_PUT_RECV Closing on EOF.");
1574 cupsdCloseClient(con
);
1579 con
->bytes
+= bytes
;
1581 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1585 unlink(con
->filename
);
1586 cupsdClearString(&con
->filename
);
1588 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1590 cupsdCloseClient(con
);
1595 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1597 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1598 "Unable to write %d bytes to \"%s\": %s", bytes
,
1599 con
->filename
, strerror(errno
));
1603 unlink(con
->filename
);
1604 cupsdClearString(&con
->filename
);
1606 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1608 cupsdCloseClient(con
);
1613 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1615 cupsdCloseClient(con
);
1619 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1621 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1624 * End of file, see how big it is...
1627 fstat(con
->file
, &filestats
);
1632 if (filestats
.st_size
> MaxRequestSize
&&
1636 * Request is too big; remove it and send an error...
1639 unlink(con
->filename
);
1640 cupsdClearString(&con
->filename
);
1642 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1644 cupsdCloseClient(con
);
1650 * Install the configuration file...
1653 status
= install_cupsd_conf(con
);
1656 * Return the status to the client...
1659 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1667 case HTTP_STATE_POST_RECV
:
1670 if (con
->request
&& con
->file
< 0)
1673 * Grab any request data from the connection...
1676 if (!httpWait(con
->http
, 0))
1679 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1681 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1682 cupsGetErrorString());
1684 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1685 cupsdCloseClient(con
);
1688 else if (ipp_state
!= IPP_STATE_DATA
)
1690 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1692 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1693 cupsdCloseClient(con
);
1697 if (httpGetReady(con
->http
))
1703 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1704 con
->request
->request
.op
.version
[0],
1705 con
->request
->request
.op
.version
[1],
1706 ippOpString(con
->request
->request
.op
.operation_id
),
1707 con
->request
->request
.op
.request_id
);
1708 con
->bytes
+= (off_t
)ippGetLength(con
->request
);
1712 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1715 * Create a file as needed for the request data...
1718 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1720 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1724 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1725 "Unable to create request file \"%s\": %s",
1726 con
->filename
, strerror(errno
));
1728 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1730 cupsdCloseClient(con
);
1735 fchmod(con
->file
, 0640);
1736 fchown(con
->file
, RunUser
, Group
);
1737 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1740 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1742 if (!httpWait(con
->http
, 0))
1744 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1746 if (httpGetError(con
->http
) && httpGetError(con
->http
) != EPIPE
)
1747 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1748 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1749 httpGetError(con
->http
), strerror(httpGetError(con
->http
)));
1751 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1752 "HTTP_STATE_POST_SEND Closing on EOF.");
1754 cupsdCloseClient(con
);
1759 con
->bytes
+= bytes
;
1761 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1765 unlink(con
->filename
);
1766 cupsdClearString(&con
->filename
);
1768 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1770 cupsdCloseClient(con
);
1775 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1777 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1778 "Unable to write %d bytes to \"%s\": %s",
1779 bytes
, con
->filename
, strerror(errno
));
1783 unlink(con
->filename
);
1784 cupsdClearString(&con
->filename
);
1786 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1789 cupsdCloseClient(con
);
1794 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1796 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1798 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1799 "Closing on unexpected state %s.",
1800 httpStateString(httpGetState(con
->http
)));
1801 cupsdCloseClient(con
);
1806 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1808 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1812 if (fstat(con
->file
, &filestats
))
1813 filestats
.st_size
= 0;
1818 if (filestats
.st_size
> MaxRequestSize
&&
1822 * Request is too big; remove it and send an error...
1825 unlink(con
->filename
);
1826 cupsdClearString(&con
->filename
);
1831 * Delete any IPP request data...
1834 ippDelete(con
->request
);
1835 con
->request
= NULL
;
1838 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1840 cupsdCloseClient(con
);
1844 else if (filestats
.st_size
== 0)
1847 * Don't allow empty file...
1850 unlink(con
->filename
);
1851 cupsdClearString(&con
->filename
);
1856 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1858 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1860 cupsdCloseClient(con
);
1865 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1871 cupsdProcessIPPRequest(con
);
1875 unlink(con
->filename
);
1876 cupsdClearString(&con
->filename
);
1885 break; /* Anti-compiler-warning-code */
1888 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
1890 if (!httpGetKeepAlive(con
->http
))
1892 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1893 "Closing because Keep-Alive is disabled.");
1894 cupsdCloseClient(con
);
1898 cupsArrayRemove(ActiveClients
, con
);
1899 cupsdSetBusyState(0);
1906 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1909 int /* O - 1 on success, 0 on failure */
1911 cupsd_client_t
*con
, /* I - Client connection */
1912 char *command
, /* I - Command to run */
1913 char *options
, /* I - Command-line options */
1914 int root
) /* I - Run as root? */
1916 int fd
; /* Standard input file descriptor */
1921 fd
= open(con
->filename
, O_RDONLY
);
1925 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1926 "Unable to open \"%s\" for reading: %s",
1927 con
->filename
? con
->filename
: "/dev/null",
1932 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1937 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1938 con
->pipe_status
= HTTP_STATUS_OK
;
1940 httpClearFields(con
->http
);
1941 httpClearCookie(con
->http
);
1946 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
1947 command
, con
->pipe_pid
, con
->file
);
1949 if (con
->pipe_pid
== 0)
1952 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1954 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
1956 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
1958 con
->sent_header
= 0;
1959 con
->file_ready
= 0;
1960 con
->got_fields
= 0;
1961 con
->header_used
= 0;
1968 * 'cupsdSendError()' - Send an error message via HTTP.
1971 int /* O - 1 if successful, 0 otherwise */
1972 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1973 http_status_t code
, /* I - Error code */
1974 int auth_type
)/* I - Authentication type */
1976 char location
[2048]; /* Location field */
1979 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
1982 * Force client to upgrade for authentication if that is how the
1983 * server is configured...
1986 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
1987 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
1988 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
1989 !httpIsEncrypted(con
->http
))
1991 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
1995 * Put the request in the access_log file...
1998 cupsdLogRequest(con
, code
);
2001 * To work around bugs in some proxies, don't use Keep-Alive for some
2004 * Kerberos authentication doesn't work without Keep-Alive, so
2005 * never disable it in that case.
2008 cupsCopyString(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
2010 httpClearFields(con
->http
);
2012 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
2014 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2015 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2017 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2018 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2019 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2021 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2024 * Send a human-readable error message.
2027 char message
[4096], /* Message for user */
2028 urltext
[1024], /* URL redirection text */
2029 redirect
[1024]; /* Redirection link */
2030 const char *text
; /* Status-specific text */
2035 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2037 text
= _cupsLangString(con
->language
,
2038 _("Enter your username and password or the "
2039 "root username and password to access this "
2040 "page. If you are using Kerberos authentication, "
2041 "make sure you have a valid Kerberos ticket."));
2043 else if (code
== HTTP_STATUS_FORBIDDEN
)
2045 if (con
->username
[0])
2046 text
= _cupsLangString(con
->language
, _("Your account does not have the necessary privileges."));
2048 text
= _cupsLangString(con
->language
, _("You cannot access this page."));
2050 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2054 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
);
2056 snprintf(redirect
, sizeof(redirect
), "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;URL=https://%s:%d%s\">\n", con
->servername
, con
->serverport
, con
->uri
);
2058 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2059 text
= _cupsLangString(con
->language
,
2060 _("The web interface is currently disabled. Run "
2061 "\"cupsctl WebInterface=yes\" to enable it."));
2065 snprintf(message
, sizeof(message
),
2066 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2067 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2070 "\t<META HTTP-EQUIV=\"Content-Type\" "
2071 "CONTENT=\"text/html; charset=utf-8\">\n"
2072 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2073 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2074 "HREF=\"/cups.css\">\n"
2082 _httpStatusString(con
->language
, code
), redirect
,
2083 _httpStatusString(con
->language
, code
), text
);
2086 * Send an error message back to the client. If the error code is a
2087 * 400 or 500 series, make sure the message contains some text, too!
2090 size_t length
= strlen(message
); /* Length of message */
2092 httpSetLength(con
->http
, length
);
2094 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2097 if (httpWrite2(con
->http
, message
, length
) < 0)
2100 if (httpFlushWrite(con
->http
) < 0)
2105 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2107 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2116 * 'cupsdSendHeader()' - Send an HTTP request.
2119 int /* O - 1 on success, 0 on failure */
2121 cupsd_client_t
*con
, /* I - Client to send to */
2122 http_status_t code
, /* I - HTTP status code */
2123 char *type
, /* I - MIME type of document */
2124 int auth_type
) /* I - Type of authentication */
2126 char auth_str
[2048]; /* Authorization string */
2129 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2132 * Send the HTTP status header...
2135 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2138 * Treat our special "web interface is disabled" status as "200 OK" for web
2142 code
= HTTP_STATUS_OK
;
2145 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2146 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2148 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2150 if (auth_type
== CUPSD_AUTH_NONE
)
2152 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2153 auth_type
= cupsdDefaultAuthType();
2155 auth_type
= con
->best
->type
;
2160 if (auth_type
== CUPSD_AUTH_BASIC
)
2162 cupsCopyString(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2164 else if (auth_type
== CUPSD_AUTH_BEARER
)
2169 * Bearer realm="OAUTH-URI" [scope="SCOPES"] [error="invalid_token" error_description="ERROR"]
2172 char *auth_ptr
; /* Pointer into auth string */
2174 snprintf(auth_str
, sizeof(auth_str
), "Bearer realm=\"%s\"", OAuthServer
);
2175 auth_ptr
= auth_str
+ strlen(auth_str
);
2178 snprintf(auth_ptr
, sizeof(auth_str
) - (size_t)(auth_ptr
- auth_str
), " scope=\"%s\"", OAuthScopes
);
2179 auth_ptr
+= strlen(auth_ptr
);
2181 if (con
->autherror
[0])
2182 snprintf(auth_ptr
, sizeof(auth_str
) - (size_t)(auth_ptr
- auth_str
), " error=\"invalid_token\" error_description=\"%s\"", con
->autherror
);
2184 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2186 cupsCopyString(auth_str
, "Negotiate", sizeof(auth_str
));
2189 if (con
->best
&& !con
->is_browser
&& !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2192 * Add a "trc" (try root certification) parameter for local
2193 * requests when the request requires system group membership - then the
2194 * client knows the root certificate can/should be used.
2196 * Also, for macOS we also look for @AUTHKEY and add an "AuthRef key=foo"
2197 * method as needed...
2200 char *name
, /* Current user name */
2201 *auth_key
; /* Auth key buffer */
2202 size_t auth_size
; /* Size of remaining buffer */
2203 int need_local
= 1; /* Do we need to list "Local" method? */
2205 auth_key
= auth_str
+ strlen(auth_str
);
2206 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2208 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
2209 if (httpAddrGetFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2211 cupsCopyString(auth_key
, ", PeerCred", auth_size
);
2215 #endif /* SO_PEERCRED && AF_LOCAL */
2217 for (name
= (char *)cupsArrayGetFirst(con
->best
->names
);
2219 name
= (char *)cupsArrayGetNext(con
->best
->names
))
2221 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendHeader: require \"%s\"", name
);
2223 #ifdef HAVE_AUTHORIZATION_H
2224 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2226 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\", Local trc=\"y\"", name
+ 9);
2228 /* end parenthesis is stripped in conf.c */
2232 #endif /* HAVE_AUTHORIZATION_H */
2233 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2235 #ifdef HAVE_AUTHORIZATION_H
2236 if (SystemGroupAuthKey
)
2237 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\", Local trc=\"y\"", SystemGroupAuthKey
);
2239 #endif /* HAVE_AUTHORIZATION_H */
2240 cupsCopyString(auth_key
, ", Local trc=\"y\"", auth_size
);
2247 cupsConcatString(auth_key
, ", Local", auth_size
);
2252 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2254 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2258 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2259 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2263 if (!strcmp(type
, "text/html"))
2264 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2266 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2269 return (!httpWriteResponse(con
->http
, code
));
2274 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2278 cupsdUpdateCGI(void)
2280 char *ptr
, /* Pointer to end of line in buffer */
2281 message
[1024]; /* Pointer to message text */
2282 int loglevel
; /* Log level for message */
2285 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2286 message
, sizeof(message
))) != NULL
)
2288 if (loglevel
== CUPSD_LOG_INFO
)
2289 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2291 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2295 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2298 * Fatal error on pipe - should never happen!
2301 cupsdLogMessage(CUPSD_LOG_CRIT
,
2302 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2309 * 'cupsdWriteClient()' - Write data to a client as needed.
2313 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2315 int bytes
, /* Number of bytes written */
2316 field_col
; /* Current column */
2317 char *bufptr
, /* Pointer into buffer */
2318 *bufend
; /* Pointer to end of buffer */
2319 ipp_state_t ipp_state
; /* IPP state value */
2322 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "con->http=%p", (void *)con
->http
);
2323 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2328 "data_encoding=HTTP_ENCODING_%s, "
2329 "data_remaining=" CUPS_LLFMT
", "
2333 httpGetError(con
->http
), (int)httpGetReady(con
->http
),
2334 httpStateString(httpGetState(con
->http
)),
2335 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2336 CUPS_LLCAST
httpGetLength2(con
->http
),
2337 (void *)con
->response
,
2338 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2339 con
->pipe_pid
, con
->file
);
2341 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2342 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2345 * If we get called in the wrong state, then something went wrong with the
2346 * connection and we need to shut it down...
2349 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2350 httpStateString(httpGetState(con
->http
)));
2351 cupsdCloseClient(con
);
2358 * Make sure we select on the CGI output...
2361 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2363 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2365 if (!con
->file_ready
)
2368 * Try again later when there is CGI output available...
2371 cupsdRemoveSelect(httpGetFd(con
->http
));
2375 con
->file_ready
= 0;
2378 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2380 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2383 * Limit GET bytes to original size of file (STR #3265)...
2386 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2389 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2391 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2396 * Write a single attribute or the IPP message header...
2399 ipp_state
= ippWrite(con
->http
, con
->response
);
2402 * If the write buffer has been flushed, stop buffering up attributes...
2405 if (httpGetPending(con
->http
) <= wused
)
2408 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2410 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2411 "Writing IPP response, ipp_state=%s, old "
2412 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2413 ippStateString(ipp_state
),
2414 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2416 if (httpGetPending(con
->http
) > 0)
2417 httpFlushWrite(con
->http
);
2419 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2420 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2422 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2423 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2424 (int)bytes
, httpGetState(con
->http
),
2425 CUPS_LLCAST
httpGetLength2(con
->http
));
2427 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2429 con
->header_used
+= bytes
;
2430 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Script header: BEFORE header_used=%lu", (unsigned long)con
->header_used
);
2432 if (con
->pipe_pid
&& !con
->got_fields
)
2435 * Inspect the data for Content-Type and other fields.
2438 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2440 !con
->got_fields
&& bufptr
< bufend
;
2443 if (*bufptr
== '\n')
2446 * Send line to client...
2449 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2453 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2455 if (!con
->sent_header
)
2458 * Handle redirection and CGI status codes...
2461 http_field_t field
; /* HTTP field */
2462 char *value
= strchr(con
->header
, ':');
2463 /* Value of field */
2468 while (isspace(*value
& 255))
2472 field
= httpFieldValue(con
->header
);
2473 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Script header: field=%d, value=\"%s\"", field
, value
);
2475 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2477 httpSetField(con
->http
, field
, value
);
2479 if (field
== HTTP_FIELD_LOCATION
)
2480 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2482 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2483 con
->pipe_status
= (http_status_t
)atoi(value
);
2484 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2485 httpSetCookie(con
->http
, value
);
2492 con
->header_used
-= bufptr
- con
->header
;
2493 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Script header: AFTER header_used=%lu", (unsigned long)con
->header_used
);
2495 if (con
->header_used
> 0)
2496 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2498 bufptr
= con
->header
- 1;
2499 bufend
= con
->header
+ con
->header_used
;
2502 * See if the line was empty...
2507 con
->got_fields
= 1;
2509 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2510 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2511 httpSetLength(con
->http
, 0);
2513 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2515 if (con
->pipe_status
== HTTP_STATUS_OK
)
2517 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2519 cupsdCloseClient(con
);
2523 con
->sent_header
= 1;
2527 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2529 cupsdCloseClient(con
);
2533 con
->sent_header
= 1;
2539 else if (*bufptr
!= '\r')
2543 if (!con
->got_fields
)
2547 if (con
->header_used
> 0)
2549 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2551 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2552 httpGetError(con
->http
), strerror(httpGetError(con
->http
)));
2553 cupsdCloseClient(con
);
2557 if (httpIsChunked(con
->http
))
2558 httpFlushWrite(con
->http
);
2560 con
->bytes
+= con
->header_used
;
2562 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2565 bytes
= con
->header_used
;
2567 con
->header_used
= 0;
2572 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2573 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2575 if (!con
->sent_header
&& con
->pipe_pid
)
2576 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2579 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2581 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2583 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2585 if (httpWrite2(con
->http
, "", 0) < 0)
2587 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2588 httpGetError(con
->http
), strerror(httpGetError(con
->http
)));
2589 cupsdCloseClient(con
);
2594 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Flushing write buffer.");
2595 httpFlushWrite(con
->http
);
2596 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2599 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2601 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2605 cupsdRemoveSelect(con
->file
);
2608 cupsdEndProcess(con
->pipe_pid
, 0);
2617 unlink(con
->filename
);
2618 cupsdClearString(&con
->filename
);
2623 ippDelete(con
->request
);
2624 con
->request
= NULL
;
2629 ippDelete(con
->response
);
2630 con
->response
= NULL
;
2633 cupsdClearString(&con
->command
);
2634 cupsdClearString(&con
->options
);
2635 cupsdClearString(&con
->query_string
);
2637 if (!httpGetKeepAlive(con
->http
))
2639 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2640 "Closing because Keep-Alive is disabled.");
2641 cupsdCloseClient(con
);
2646 cupsArrayRemove(ActiveClients
, con
);
2647 cupsdSetBusyState(0);
2654 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2657 static int /* O - 1 if modified since */
2659 cupsd_client_t
*con
, /* I - Client connection */
2660 struct stat
*filestats
) /* I - File information */
2662 const char *ptr
; /* Pointer into field */
2663 time_t date
; /* Time/date value */
2664 off_t size
; /* Size/length value */
2669 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2674 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "check_if_modified: filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"", (void *)filestats
, CUPS_LLCAST filestats
->st_size
, (int)filestats
->st_mtime
, ptr
);
2676 while (*ptr
!= '\0')
2678 while (isspace(*ptr
) || *ptr
== ';')
2681 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2684 size
= strtoll(ptr
, NULL
, 10);
2686 while (isdigit(*ptr
))
2689 else if (isalpha(*ptr
))
2691 date
= httpGetDateTime(ptr
);
2692 while (*ptr
!= '\0' && *ptr
!= ';')
2699 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2700 (date
< filestats
->st_mtime
&& date
!= 0) ||
2701 (size
== 0 && date
== 0));
2706 * 'compare_clients()' - Compare two client connections.
2709 static int /* O - Result of comparison */
2710 compare_clients(cupsd_client_t
*a
, /* I - First client */
2711 cupsd_client_t
*b
, /* I - Second client */
2712 void *data
) /* I - User data (not used) */
2726 * 'cupsd_start_tls()' - Start encryption on a connection.
2729 static int /* O - 0 on success, -1 on error */
2730 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2731 http_encryption_t e
) /* I - Encryption mode */
2733 if (!httpSetEncryption(con
->http
, e
))
2735 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2736 cupsGetErrorString());
2740 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Connection now encrypted.");
2746 * 'get_file()' - Get a filename and state info.
2749 static char * /* O - Real filename */
2750 get_file(cupsd_client_t
*con
, /* I - Client connection */
2751 struct stat
*filestats
, /* O - File information */
2752 char *filename
, /* IO - Filename buffer */
2753 size_t len
) /* I - Buffer length */
2755 int status
; /* Status of filesystem calls */
2756 char *ptr
; /* Pointer info filename */
2757 size_t plen
; /* Remaining length after pointer */
2758 char language
[7], /* Language subdirectory, if any */
2759 dest
[1024]; /* Destination name */
2760 int perm_check
= 1; /* Do permissions check? */
2761 cupsd_printer_t
*p
; /* Printer */
2765 * Figure out the real filename...
2771 if (!strcmp(con
->uri
, "/") || !strncmp(con
->uri
, "/?", 2))
2774 * The homepage/dashboard is served by the home.cgi program...
2779 else if (!strncmp(con
->uri
, "/help", 5) && (con
->uri
[5] == '/' || !con
->uri
[5]))
2782 * All help files are served by the help.cgi program...
2787 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"))
2789 cupsCopyString(dest
, strchr(con
->uri
+ 1, '/') + 1, sizeof(dest
));
2790 dest
[strlen(dest
) - 4] = '\0'; /* Strip .ppd */
2792 if ((p
= cupsdFindDest(dest
)) == NULL
)
2794 cupsCopyString(filename
, "/", len
);
2795 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2799 if (p
->type
& CUPS_PTYPE_CLASS
)
2801 int i
; /* Looping var */
2803 for (i
= 0; i
< p
->num_printers
; i
++)
2805 if (!(p
->printers
[i
]->type
& CUPS_PTYPE_CLASS
))
2807 snprintf(filename
, len
, "%s/ppd/%s.ppd", ServerRoot
, p
->printers
[i
]->name
);
2808 if (!access(filename
, 0))
2816 if (i
>= p
->num_printers
)
2820 snprintf(filename
, len
, "%s/ppd/%s.ppd", ServerRoot
, p
->name
);
2824 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"))
2826 cupsCopyString(dest
, strchr(con
->uri
+ 1, '/') + 1, sizeof(dest
));
2827 dest
[strlen(dest
) - 4] = '\0'; /* Strip .png */
2829 if ((p
= cupsdFindDest(dest
)) == NULL
)
2831 cupsCopyString(filename
, "/", len
);
2832 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2836 if (p
->type
& CUPS_PTYPE_CLASS
)
2838 int i
; /* Looping var */
2840 for (i
= 0; i
< p
->num_printers
; i
++)
2842 if (!(p
->printers
[i
]->type
& CUPS_PTYPE_CLASS
))
2844 snprintf(filename
, len
, "%s/images/%s.png", CacheDir
, p
->printers
[i
]->name
);
2845 if (!access(filename
, 0))
2853 if (i
>= p
->num_printers
)
2857 snprintf(filename
, len
, "%s/images/%s.png", CacheDir
, p
->name
);
2859 if (access(filename
, F_OK
) < 0)
2860 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2864 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2866 cupsCopyString(filename
, ConfigurationFile
, len
);
2870 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2872 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2873 cupsCopyString(filename
, AccessLog
, len
);
2874 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2875 cupsCopyString(filename
, ErrorLog
, len
);
2876 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2877 cupsCopyString(filename
, PageLog
, len
);
2883 else if (!strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/jobs", 5) || !strncmp(con
->uri
, "/printers", 9))
2886 * Admin/class/job/printer pages are served by CGI...
2891 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2893 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2895 else if (!strncmp(con
->uri
, "/strings/", 9) && !strcmp(con
->uri
+ strlen(con
->uri
) - 8, ".strings"))
2897 snprintf(filename
, len
, "%s/strings/%s", ServerRoot
, con
->uri
+ 9);
2900 else if (con
->language
)
2902 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2903 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2906 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2908 if ((ptr
= strchr(filename
, '?')) != NULL
)
2912 * Grab the status for this language; if there isn't a language-specific file
2913 * then fallback to the default one...
2916 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
2917 strncmp(con
->uri
, "/icons/", 7) &&
2918 strncmp(con
->uri
, "/ppd/", 5) &&
2919 strncmp(con
->uri
, "/rss/", 5) &&
2920 strncmp(con
->uri
, "/strings/", 9) &&
2921 strncmp(con
->uri
, "/admin/conf/", 12) &&
2922 strncmp(con
->uri
, "/admin/log/", 11))
2925 * Drop the country code...
2929 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2931 if ((ptr
= strchr(filename
, '?')) != NULL
)
2934 if ((status
= lstat(filename
, filestats
)) != 0)
2937 * Drop the language prefix and try the root directory...
2941 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2943 if ((ptr
= strchr(filename
, '?')) != NULL
)
2946 status
= lstat(filename
, filestats
);
2951 * If we've found a symlink, 404 the sucker to avoid disclosing information.
2954 if (!status
&& S_ISLNK(filestats
->st_mode
))
2956 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
2961 * Similarly, if the file/directory does not have world read permissions, do
2962 * not allow access...
2965 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
2967 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
2972 * If we've found a directory, get the index.html file instead...
2975 if (!status
&& S_ISDIR(filestats
->st_mode
))
2978 * Make sure the URI ends with a slash...
2981 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
2982 cupsConcatString(con
->uri
, "/", sizeof(con
->uri
));
2985 * Find the directory index file, trying every language...
2990 if (status
&& language
[0])
2993 * Try a different language subset...
2997 language
[3] = '\0'; /* Strip country code */
2999 language
[0] = '\0'; /* Strip language */
3003 * Look for the index file...
3006 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3008 if ((ptr
= strchr(filename
, '?')) != NULL
)
3011 ptr
= filename
+ strlen(filename
);
3012 plen
= len
- (size_t)(ptr
- filename
);
3014 cupsCopyString(ptr
, "index.html", plen
);
3015 status
= lstat(filename
, filestats
);
3017 while (status
&& language
[0]);
3020 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3023 if (!status
&& S_ISLNK(filestats
->st_mode
))
3025 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3030 * Similarly, if the file/directory does not have world read permissions, do
3031 * not allow access...
3034 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3036 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3041 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", (void *)filestats
, (void *)filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3051 * 'install_cupsd_conf()' - Install a configuration file.
3054 static http_status_t
/* O - Status */
3055 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3057 char filename
[1024]; /* Configuration filename */
3058 cups_file_t
*in
, /* Input file */
3059 *out
; /* Output file */
3060 char buffer
[16384]; /* Copy buffer */
3061 ssize_t bytes
; /* Number of bytes */
3065 * Open the request file...
3068 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3070 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3071 con
->filename
, strerror(errno
));
3076 * Open the new config file...
3079 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3085 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3089 * Copy from the request to the new config file...
3092 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3093 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3095 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3096 "Unable to copy to config file \"%s\": %s",
3097 ConfigurationFile
, strerror(errno
));
3102 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3103 cupsdUnlinkOrRemoveFile(filename
);
3109 * Close the files...
3114 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3118 * Remove the request file...
3121 cupsdUnlinkOrRemoveFile(con
->filename
);
3122 cupsdClearString(&con
->filename
);
3125 * Set the NeedReload flag...
3128 NeedReload
= RELOAD_CUPSD
;
3129 ReloadTime
= time(NULL
);
3132 * Return that the file was created successfully...
3135 return (HTTP_STATUS_CREATED
);
3138 * Common exit for errors...
3143 cupsdUnlinkOrRemoveFile(con
->filename
);
3144 cupsdClearString(&con
->filename
);
3146 return (HTTP_STATUS_SERVER_ERROR
);
3151 * 'is_cgi()' - Is the resource a CGI script/program?
3154 static int /* O - 1 = CGI, 0 = file */
3155 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3156 const char *filename
, /* I - Real filename */
3157 struct stat
*filestats
, /* I - File information */
3158 mime_type_t
*type
) /* I - MIME type */
3160 const char *options
; /* Options on URL */
3164 * Get the options, if any...
3167 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3170 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3174 * Check for known types...
3177 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3179 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, (void *)filestats
, type
? type
->super
: "unknown", type
? type
->type
: "unknown");
3183 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") && (filestats
->st_mode
& 0111) && (getuid() || !(filestats
->st_mode
& 022)))
3186 * "application/x-httpd-cgi" is a CGI script.
3189 cupsdSetString(&con
->command
, filename
);
3192 cupsdSetStringf(&con
->options
, " %s", options
);
3194 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, (void *)filestats
, type
->super
, type
->type
);
3198 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, (void *)filestats
, type
->super
, type
->type
);
3204 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3207 static int /* O - 0 if relative, 1 if absolute */
3208 is_path_absolute(const char *path
) /* I - Input path */
3211 * Check for a leading slash...
3218 * Check for "<" or quotes in the path and reject since this is probably
3219 * someone trying to inject HTML...
3222 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3226 * Check for "/.." in the path...
3229 while ((path
= strstr(path
, "/..")) != NULL
)
3231 if (!path
[3] || path
[3] == '/')
3238 * If we haven't found any relative paths, return 1 indicating an
3247 * 'pipe_command()' - Pipe the output of a command to the remote client.
3250 static int /* O - Process ID */
3251 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3252 int infile
, /* I - Standard input for command */
3253 int *outfile
, /* O - Standard output for command */
3254 char *command
, /* I - Command to run */
3255 char *options
, /* I - Options for command */
3256 int root
) /* I - Run as root? */
3258 int i
; /* Looping var */
3259 int pid
; /* Process ID */
3260 char *commptr
, /* Command string pointer */
3261 commch
; /* Command string character */
3262 char *uriptr
; /* URI string pointer */
3263 int fds
[2]; /* Pipe FDs */
3264 int argc
; /* Number of arguments */
3265 int envc
; /* Number of environment variables */
3266 char argbuf
[10240], /* Argument buffer */
3267 *argv
[100], /* Argument strings */
3268 *envp
[MAX_ENV
+ 30]; /* Environment variables */
3269 char auth_type
[256], /* AUTH_TYPE environment variable */
3270 content_length
[1024], /* CONTENT_LENGTH environment variable */
3271 content_type
[1024], /* CONTENT_TYPE environment variable */
3272 cups_oauth_scopes
[1024],/* CUPS_OAUTH_SCOPES environment variable */
3273 cups_oauth_server
[1024],/* CUPS_OAUTH_SERVER environment variable */
3274 http_authorization
[16384],
3275 /* HTTP_AUTHORIZATION environemnt variable */
3276 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3277 http_referer
[1024], /* HTTP_REFERER environment variable */
3278 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3279 lang
[1024], /* LANG environment variable */
3280 path_info
[1024], /* PATH_INFO environment variable */
3281 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3282 remote_email
[1024], /* REMOTE_EMAIL environment variable */
3283 remote_host
[1024], /* REMOTE_HOST environment variable */
3284 remote_name
[1024], /* REMOTE_NAME ("real name") environment variable */
3285 remote_user
[1024], /* REMOTE_USER environment variable */
3286 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3287 script_name
[1024], /* SCRIPT_NAME environment variable */
3288 server_name
[1024], /* SERVER_NAME environment variable */
3289 server_port
[1024]; /* SERVER_PORT environment variable */
3290 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3294 * Parse a copy of the options string, which is of the form:
3296 * argument+argument+argument
3297 * ?argument+argument+argument
3298 * param=value¶m=value
3299 * ?param=value¶m=value
3300 * /name?argument+argument+argument
3301 * /name?param=value¶m=value
3303 * If the string contains an "=" character after the initial name,
3304 * then we treat it as a HTTP GET form request and make a copy of
3305 * the remaining string for the environment variable.
3307 * The string is always parsed out as command-line arguments, to
3308 * be consistent with Apache...
3311 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, (void *)outfile
, command
, options
? options
: "(null)", root
);
3316 cupsCopyString(argbuf
, options
, sizeof(argbuf
));
3320 if (argbuf
[0] == '/')
3323 * Found some trailing path information, set PATH_INFO...
3326 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3327 commptr
= argbuf
+ strlen(argbuf
);
3331 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3337 path_info
[0] = '\0';
3339 if (*commptr
== ' ')
3343 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3346 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3353 argv
[argc
++] = commptr
;
3355 for (; *commptr
&& argc
< 99; commptr
++)
3358 * Break arguments whenever we see a + or space...
3361 if (*commptr
== ' ' || *commptr
== '+')
3363 while (*commptr
== ' ' || *commptr
== '+')
3367 * If we don't have a blank string, save it as another argument...
3372 argv
[argc
] = commptr
;
3378 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3379 isxdigit(commptr
[2] & 255))
3382 * Convert the %xx notation to the individual character.
3385 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3386 *commptr
= (char)((commptr
[1] - '0') << 4);
3388 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3390 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3391 *commptr
|= commptr
[2] - '0';
3393 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3395 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3398 * Check for a %00 and break if that is the case...
3410 * Setup the environment variables as needed...
3413 if (con
->username
[0])
3415 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3416 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3418 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3422 auth_type
[0] = '\0';
3424 if (con
->request
&& (attr
= ippFindAttribute(con
->request
, "attributes-natural-language", IPP_TAG_LANGUAGE
)) != NULL
)
3426 cups_lang_t
*language
= cupsLangGet(ippGetString(attr
, 0, NULL
));
3428 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", language
->language
);
3429 cupsLangFree(language
);
3431 else if (con
->language
)
3432 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3434 cupsCopyString(lang
, "LANG=C", sizeof(lang
));
3436 cupsCopyString(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3437 httpAddrGetString(httpGetAddress(con
->http
), remote_addr
+ 12,
3438 sizeof(remote_addr
) - 12);
3440 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3441 httpGetHostname(con
->http
, NULL
, 0));
3443 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3444 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3447 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3448 DocumentRoot
, script_name
+ 12);
3450 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3452 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3454 char *nameptr
; /* Pointer to ":port" */
3456 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3457 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3458 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3459 *nameptr
= '\0'; /* Strip trailing ":port" */
3462 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3465 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3468 envp
[envc
++] = auth_type
;
3470 envp
[envc
++] = lang
;
3471 envp
[envc
++] = "CUPS_VERSION=" CUPS_SVERSION
;
3472 envp
[envc
++] = "REDIRECT_STATUS=1";
3473 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3474 envp
[envc
++] = server_name
;
3475 envp
[envc
++] = server_port
;
3476 envp
[envc
++] = remote_addr
;
3477 envp
[envc
++] = remote_host
;
3478 envp
[envc
++] = script_name
;
3479 envp
[envc
++] = script_filename
;
3483 snprintf(cups_oauth_scopes
, sizeof(cups_oauth_scopes
), "CUPS_OAUTH_SCOPES=%s", OAuthScopes
);
3484 envp
[envc
++] = cups_oauth_scopes
;
3489 snprintf(cups_oauth_server
, sizeof(cups_oauth_server
), "CUPS_OAUTH_SERVER=%s", OAuthServer
);
3490 envp
[envc
++] = cups_oauth_server
;
3494 envp
[envc
++] = path_info
;
3498 snprintf(remote_email
, sizeof(remote_email
), "REMOTE_EMAIL=%s", con
->email
);
3499 envp
[envc
++] = remote_email
;
3502 if (con
->realname
[0])
3504 snprintf(remote_name
, sizeof(remote_name
), "REMOTE_NAME=%s", con
->realname
);
3505 envp
[envc
++] = remote_name
;
3508 if (con
->username
[0])
3510 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3511 envp
[envc
++] = remote_user
;
3514 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3515 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3516 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3517 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3519 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3521 if (httpGetAuthString(con
->http
))
3523 snprintf(http_authorization
, sizeof(http_authorization
), "HTTP_AUTHORIZATION=%s", httpGetAuthString(con
->http
));
3524 envp
[envc
++] = http_authorization
;
3527 if (httpGetCookie(con
->http
))
3529 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3530 httpGetCookie(con
->http
));
3531 envp
[envc
++] = http_cookie
;
3534 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3536 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3537 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3538 envp
[envc
++] = http_user_agent
;
3541 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3543 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3544 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3545 envp
[envc
++] = http_referer
;
3548 if (con
->operation
== HTTP_STATE_GET
)
3550 envp
[envc
++] = "REQUEST_METHOD=GET";
3552 if (con
->query_string
)
3555 * Add GET form variables after ?...
3558 envp
[envc
++] = con
->query_string
;
3561 envp
[envc
++] = "QUERY_STRING=";
3565 snprintf(content_length
, sizeof(content_length
), "CONTENT_LENGTH=" CUPS_LLFMT
, CUPS_LLCAST con
->bytes
);
3566 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3567 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3569 envp
[envc
++] = "REQUEST_METHOD=POST";
3570 envp
[envc
++] = content_length
;
3571 envp
[envc
++] = content_type
;
3575 * Tell the CGI if we are using encryption...
3578 if (httpIsEncrypted(con
->http
))
3579 envp
[envc
++] = "HTTPS=ON";
3582 * Terminate the environment array...
3587 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3589 for (i
= 0; i
< argc
; i
++)
3590 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3591 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3592 for (i
= 0; i
< envc
; i
++)
3593 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3594 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3598 * Create a pipe for the output...
3601 if (cupsdOpenPipe(fds
))
3603 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3604 argv
[0], strerror(errno
));
3609 * Then execute the command...
3612 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3613 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3616 * Error - can't fork!
3619 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3622 cupsdClosePipe(fds
);
3628 * Fork successful - return the PID...
3631 if (con
->username
[0])
3632 cupsdAddCert(pid
, con
->username
, con
->type
);
3634 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3645 * 'valid_host()' - Is the Host: field valid?
3648 static int /* O - 1 if valid, 0 if not */
3649 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3651 cupsd_alias_t
*a
; /* Current alias */
3652 cupsd_netif_t
*netif
; /* Current network interface */
3653 const char *end
; /* End character */
3654 char *ptr
; /* Pointer into host value */
3658 * Copy the Host: header for later use...
3661 cupsCopyString(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3662 sizeof(con
->clientname
));
3663 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3666 con
->clientport
= atoi(ptr
);
3669 con
->clientport
= con
->serverport
;
3675 if (httpAddrIsLocalhost(httpGetAddress(con
->http
)))
3678 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3679 * addresses when accessing CUPS via the loopback interface...
3682 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3683 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3684 !strcmp(con
->clientname
, "127.0.0.1") ||
3685 !strcmp(con
->clientname
, "[::1]"));
3689 * Check if the hostname is something.local (Bonjour); if so, allow it.
3692 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3696 * "." on end, work back to second-to-last "."...
3699 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3702 if (end
&& (!_cups_strcasecmp(end
, ".local") || !_cups_strcasecmp(end
, ".local.")))
3706 * Check if the hostname is an IP address...
3709 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3712 * Possible IPv4/IPv6 address...
3715 http_addrlist_t
*addrlist
; /* List of addresses */
3718 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3721 * Good IPv4/IPv6 address...
3724 httpAddrFreeList(addrlist
);
3730 * Check for (alias) name matches...
3733 for (a
= (cupsd_alias_t
*)cupsArrayGetFirst(ServerAlias
);
3735 a
= (cupsd_alias_t
*)cupsArrayGetNext(ServerAlias
))
3738 * "ServerAlias *" allows all host values through...
3741 if (!strcmp(a
->name
, "*"))
3744 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3747 * Prefix matches; check the character at the end - it must be "." or nul.
3750 end
= con
->clientname
+ a
->namelen
;
3752 if (!*end
|| (*end
== '.' && !end
[1]))
3757 for (a
= (cupsd_alias_t
*)cupsArrayGetFirst(DNSSDAlias
); a
; a
= (cupsd_alias_t
*)cupsArrayGetNext(DNSSDAlias
))
3760 * "ServerAlias *" allows all host values through...
3763 if (!strcmp(a
->name
, "*"))
3766 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3769 * Prefix matches; check the character at the end - it must be "." or nul.
3772 end
= con
->clientname
+ a
->namelen
;
3774 if (!*end
|| (*end
== '.' && !end
[1]))
3780 * Check for interface hostname matches...
3783 for (netif
= (cupsd_netif_t
*)cupsArrayGetFirst(NetIFList
);
3785 netif
= (cupsd_netif_t
*)cupsArrayGetNext(NetIFList
))
3787 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3790 * Prefix matches; check the character at the end - it must be "." or nul.
3793 end
= con
->clientname
+ netif
->hostlen
;
3795 if (!*end
|| (*end
== '.' && !end
[1]))
3805 * 'write_file()' - Send a file via HTTP.
3808 static int /* O - 0 on failure, 1 on success */
3809 write_file(cupsd_client_t
*con
, /* I - Client connection */
3810 http_status_t code
, /* I - HTTP status */
3811 char *filename
, /* I - Filename */
3812 char *type
, /* I - File type */
3813 struct stat
*filestats
) /* O - File information */
3815 con
->file
= open(filename
, O_RDONLY
);
3817 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", (void *)filestats
);
3822 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3825 con
->sent_header
= 1;
3827 httpClearFields(con
->http
);
3828 httpClearCookie(con
->http
);
3830 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
3832 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3833 httpGetDateString(filestats
->st_mtime
));
3835 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3838 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3840 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3847 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3851 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3853 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
3855 con
->file_ready
= 1;
3857 cupsdRemoveSelect(con
->file
);
3858 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3860 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");