2 * Client routines for the CUPS scheduler.
4 * Copyright © 2021 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
16 * Include necessary headers...
19 #define _CUPS_NO_DEPRECATED
20 #define _HTTP_NO_PRIVATE
25 #endif /* __APPLE__ */
28 #endif /* HAVE_TCPD_H */
35 static int check_if_modified(cupsd_client_t
*con
,
36 struct stat
*filestats
);
37 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
40 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
42 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
43 char *filename
, size_t len
);
44 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
45 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
46 struct stat
*filestats
, mime_type_t
*type
);
47 static int is_path_absolute(const char *path
);
48 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
49 char *command
, char *options
, int root
);
50 static int valid_host(cupsd_client_t
*con
);
51 static int write_file(cupsd_client_t
*con
, http_status_t code
,
52 char *filename
, char *type
,
53 struct stat
*filestats
);
54 static void write_pipe(cupsd_client_t
*con
);
58 * 'cupsdAcceptClient()' - Accept a new client.
62 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
64 const char *hostname
; /* Hostname of client */
65 char name
[256]; /* Hostname of client */
66 int count
; /* Count of connections on a host */
67 cupsd_client_t
*con
, /* New client pointer */
68 *tempcon
; /* Temporary client pointer */
69 socklen_t addrlen
; /* Length of address */
70 http_addr_t temp
; /* Temporary address variable */
71 static time_t last_dos
= 0; /* Time of last DoS attack */
73 struct request_info wrap_req
; /* TCP wrappers request information */
74 #endif /* HAVE_TCPD_H */
77 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis
, lis
->fd
, cupsArrayCount(Clients
));
80 * Make sure we don't have a full set of clients already...
83 if (cupsArrayCount(Clients
) == MaxClients
)
89 * Get a pointer to the next available client...
93 Clients
= cupsArrayNew(NULL
, NULL
);
97 cupsdLogMessage(CUPSD_LOG_ERROR
,
98 "Unable to allocate memory for clients array!");
99 cupsdPauseListening();
104 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
108 cupsdLogMessage(CUPSD_LOG_ERROR
,
109 "Unable to allocate memory for active clients array!");
110 cupsdPauseListening();
114 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
116 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
117 cupsdPauseListening();
122 * Accept the client and get the remote address...
125 con
->number
= ++ LastClientNumber
;
128 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
130 if (errno
== ENFILE
|| errno
== EMFILE
)
131 cupsdPauseListening();
133 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
141 * Save the connected address and port number...
144 addrlen
= sizeof(con
->clientaddr
);
146 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&con
->clientaddr
, &addrlen
) || addrlen
== 0)
147 con
->clientaddr
= lis
->address
;
149 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Server address is \"%s\".", httpAddrString(&con
->clientaddr
, name
, sizeof(name
)));
152 * Check the number of clients on the same address...
155 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
157 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
158 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
161 if (count
>= MaxClientsPerHost
)
165 if (count
>= MaxClientsPerHost
)
167 if ((time(NULL
) - last_dos
) >= 60)
169 last_dos
= time(NULL
);
170 cupsdLogMessage(CUPSD_LOG_WARN
,
171 "Possible DoS attack - more than %d clients connecting "
174 httpGetHostname(con
->http
, name
, sizeof(name
)));
177 httpClose(con
->http
);
183 * Get the hostname or format the IP address as needed...
187 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
189 hostname
= httpGetHostname(con
->http
, NULL
, 0);
191 if (hostname
== NULL
&& HostNameLookups
== 2)
194 * Can't have an unresolved IP address with double-lookups enabled...
197 httpClose(con
->http
);
199 cupsdLogClient(con
, CUPSD_LOG_WARN
,
200 "Name lookup failed - connection from %s closed!",
201 httpGetHostname(con
->http
, NULL
, 0));
207 if (HostNameLookups
== 2)
210 * Do double lookups as needed...
213 http_addrlist_t
*addrlist
, /* List of addresses */
214 *addr
; /* Current address */
216 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
219 * See if the hostname maps to the same IP address...
222 for (addr
= addrlist
; addr
; addr
= addr
->next
)
223 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
229 httpAddrFreeList(addrlist
);
234 * Can't have a hostname that doesn't resolve to the same IP address
235 * with double-lookups enabled...
238 httpClose(con
->http
);
240 cupsdLogClient(con
, CUPSD_LOG_WARN
,
241 "IP lookup failed - connection from %s closed!",
242 httpGetHostname(con
->http
, NULL
, 0));
250 * See if the connection is denied by TCP wrappers...
253 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
257 if (!hosts_access(&wrap_req
))
259 httpClose(con
->http
);
261 cupsdLogClient(con
, CUPSD_LOG_WARN
,
262 "Connection from %s refused by /etc/hosts.allow and "
263 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
267 #endif /* HAVE_TCPD_H */
270 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
273 socklen_t peersize
; /* Size of peer credentials */
274 pid_t peerpid
; /* Peer process ID */
275 char peername
[256]; /* Name of process */
277 peersize
= sizeof(peerpid
);
278 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
281 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
282 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
283 "Accepted from %s (Domain ???[%d])",
284 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
286 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
287 "Accepted from %s (Domain %s[%d])",
288 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
291 # endif /* __APPLE__ */
293 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
294 httpGetHostname(con
->http
, NULL
, 0));
297 #endif /* AF_LOCAL */
298 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
299 httpGetHostname(con
->http
, NULL
, 0),
300 httpAddrPort(httpGetAddress(con
->http
)),
301 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
304 * Get the local address the client connected to...
307 addrlen
= sizeof(temp
);
308 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
310 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
313 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
314 con
->serverport
= LocalPort
;
317 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
319 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
320 con
->serverport
= LocalPort
;
322 #endif /* AF_LOCAL */
325 if (httpAddrLocalhost(&temp
))
326 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
327 else if (HostNameLookups
)
328 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
330 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
332 con
->serverport
= httpAddrPort(&(lis
->address
));
336 * Add the connection to the array of active clients...
339 cupsArrayAdd(Clients
, con
);
342 * Add the socket to the server select.
345 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
348 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
351 * Temporarily suspend accept()'s until we lose a client...
354 if (cupsArrayCount(Clients
) == MaxClients
)
355 cupsdPauseListening();
359 * See if we are connecting on a secure port...
362 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
365 * https connection; go secure...
368 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
369 cupsdCloseClient(con
);
373 #endif /* HAVE_SSL */
378 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
382 cupsdCloseAllClients(void)
384 cupsd_client_t
*con
; /* Current client */
387 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients
));
389 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
391 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
392 if (cupsdCloseClient(con
))
393 cupsdCloseClient(con
);
398 * 'cupsdCloseClient()' - Close a remote client.
401 int /* O - 1 if partial close, 0 if fully closed */
402 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
404 int partial
; /* Do partial close for SSL? */
407 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
410 * Flush pending writes before closing...
413 httpFlushWrite(con
->http
);
417 if (con
->pipe_pid
!= 0)
420 * Stop any CGI process...
423 cupsdEndProcess(con
->pipe_pid
, 1);
429 cupsdRemoveSelect(con
->file
);
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);
446 * Shutdown encryption as needed...
449 if (httpIsEncrypted(con
->http
))
451 #endif /* HAVE_SSL */
456 * Only do a partial close so that the encrypted client gets everything.
459 httpShutdown(con
->http
);
460 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
463 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
468 * Shut the socket down fully...
471 cupsdRemoveSelect(httpGetFd(con
->http
));
472 httpClose(con
->http
);
483 cupsdRemoveSelect(httpGetFd(con
->http
));
485 httpClose(con
->http
);
489 unlink(con
->filename
);
490 cupsdClearString(&con
->filename
);
493 cupsdClearString(&con
->command
);
494 cupsdClearString(&con
->options
);
495 cupsdClearString(&con
->query_string
);
499 ippDelete(con
->request
);
505 ippDelete(con
->response
);
506 con
->response
= NULL
;
511 cupsLangFree(con
->language
);
512 con
->language
= NULL
;
515 #ifdef HAVE_AUTHORIZATION_H
518 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
521 #endif /* HAVE_AUTHORIZATION_H */
524 * Re-enable new client connections if we are going back under the
528 if (cupsArrayCount(Clients
) == MaxClients
)
529 cupsdResumeListening();
532 * Compact the list of clients as necessary...
535 cupsArrayRemove(Clients
, con
);
545 * 'cupsdReadClient()' - Read data from a client.
549 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
551 char line
[32768], /* Line from client... */
552 locale
[64], /* Locale */
553 *ptr
; /* Pointer into strings */
554 http_status_t status
; /* Transfer status */
555 ipp_state_t ipp_state
; /* State of IPP transfer */
556 int bytes
; /* Number of bytes to POST */
557 char *filename
; /* Name of file for GET/HEAD */
558 char buf
[1024]; /* Buffer for real filename */
559 struct stat filestats
; /* File information */
560 mime_type_t
*type
; /* MIME type of file */
561 static unsigned request_id
= 0; /* Request ID for temp files */
564 status
= HTTP_STATUS_CONTINUE
;
566 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
);
568 if (httpError(con
->http
) == EPIPE
&& !httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
571 * Connection closed...
574 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
575 cupsdCloseClient(con
);
579 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
580 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
581 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
584 * If we get called in the wrong state, then something went wrong with the
585 * connection and we need to shut it down...
588 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con
->http
)));
589 cupsdCloseClient(con
);
597 * Automatically check for a SSL/TLS handshake...
602 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
603 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
606 * Encrypt this connection...
609 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf
[0] & 255);
611 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
612 cupsdCloseClient(con
);
617 #endif /* HAVE_SSL */
619 switch (httpGetState(con
->http
))
621 case HTTP_STATE_WAITING
:
623 * See if we've received a request line...
626 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
627 if (con
->operation
== HTTP_STATE_ERROR
||
628 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
629 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
631 if (httpError(con
->http
))
632 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
633 "HTTP_STATE_WAITING Closing for error %d (%s)",
634 httpError(con
->http
), strerror(httpError(con
->http
)));
636 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
637 "HTTP_STATE_WAITING Closing on error: %s",
638 cupsLastErrorString());
640 cupsdCloseClient(con
);
645 * Ignore blank request lines...
648 if (con
->operation
== HTTP_STATE_WAITING
)
652 * Clear other state variables...
659 con
->username
[0] = '\0';
660 con
->password
[0] = '\0';
662 cupsdClearString(&con
->command
);
663 cupsdClearString(&con
->options
);
664 cupsdClearString(&con
->query_string
);
668 ippDelete(con
->request
);
674 ippDelete(con
->response
);
675 con
->response
= NULL
;
680 cupsLangFree(con
->language
);
681 con
->language
= NULL
;
687 #endif /* HAVE_GSSAPI */
690 * Handle full URLs in the request line...
693 if (strcmp(con
->uri
, "*"))
695 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
696 userpass
[HTTP_MAX_URI
], /* Username:password */
697 hostname
[HTTP_MAX_URI
], /* Hostname */
698 resource
[HTTP_MAX_URI
]; /* Resource path */
699 int port
; /* Port number */
702 * Separate the URI into its components...
705 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
706 scheme
, sizeof(scheme
),
707 userpass
, sizeof(userpass
),
708 hostname
, sizeof(hostname
), &port
,
709 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
711 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
713 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
714 cupsdCloseClient(con
);
719 * Only allow URIs with the servername, localhost, or an IP
723 if (strcmp(scheme
, "file") &&
724 _cups_strcasecmp(hostname
, ServerName
) &&
725 _cups_strcasecmp(hostname
, "localhost") &&
726 !cupsArrayFind(ServerAlias
, hostname
) &&
727 !isdigit(hostname
[0]) && hostname
[0] != '[')
730 * Nope, we don't do proxies...
733 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
735 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
736 cupsdCloseClient(con
);
741 * Copy the resource portion back into the URI; both resource and
742 * con->uri are HTTP_MAX_URI bytes in size...
745 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
749 * Process the request...
752 gettimeofday(&(con
->start
), NULL
);
754 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
755 httpStateString(con
->operation
) + 11, con
->uri
,
756 httpGetVersion(con
->http
) / 100,
757 httpGetVersion(con
->http
) % 100);
759 if (!cupsArrayFind(ActiveClients
, con
))
761 cupsArrayAdd(ActiveClients
, con
);
762 cupsdSetBusyState(0);
765 case HTTP_STATE_OPTIONS
:
766 case HTTP_STATE_DELETE
:
767 case HTTP_STATE_GET
:
768 case HTTP_STATE_HEAD
:
769 case HTTP_STATE_POST
:
770 case HTTP_STATE_PUT
:
771 case HTTP_STATE_TRACE
:
773 * Parse incoming parameters until the status changes...
776 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
777 if (!httpGetReady(con
->http
))
780 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
782 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
783 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
784 "Closing for error %d (%s) while reading headers.",
785 httpError(con
->http
), strerror(httpError(con
->http
)));
787 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
788 "Closing on EOF while reading headers.");
790 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
791 cupsdCloseClient(con
);
797 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
800 * Connection closed...
803 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
804 cupsdCloseClient(con
);
807 break; /* Anti-compiler-warning-code */
811 * Handle new transfers...
814 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d, state=%d", status
, httpGetState(con
->http
));
816 if (status
== HTTP_STATUS_OK
)
819 * Record whether the client is a web browser. "Mozilla" was the original
820 * and it seems that every web browser in existence now uses that as the
821 * prefix with additional information identifying *which* browser.
823 * Chrome (at least) has problems with multiple WWW-Authenticate values in
824 * a single header, so we only report Basic or Negotiate to web browsers and
825 * leave the multiple choices to the native CUPS client...
828 con
->is_browser
= !strncmp(httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
), "Mozilla/", 8);
830 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
833 * Figure out the locale from the Accept-Language and Content-Type
837 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
841 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
845 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
846 "charset=")) != NULL
)
849 * Combine language and charset, and trim any extra params in the
853 snprintf(locale
, sizeof(locale
), "%s.%s",
854 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
856 if ((ptr
= strchr(locale
, ',')) != NULL
)
860 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
861 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
863 con
->language
= cupsLangGet(locale
);
866 con
->language
= cupsLangGet(DefaultLocale
);
870 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
871 "Keep-Alive", 10) && KeepAlive
)
872 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
873 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
875 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
877 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
878 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
881 * HTTP/1.1 and higher require the "Host:" field...
884 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
886 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
887 cupsdCloseClient(con
);
891 else if (!valid_host(con
))
894 * Access to localhost must use "localhost" or the corresponding IPv4
895 * or IPv6 values in the Host: field.
898 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
899 "Request from \"%s\" using invalid Host: field \"%s\".",
900 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
902 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
904 cupsdCloseClient(con
);
908 else if (con
->operation
== HTTP_STATE_OPTIONS
)
911 * Do OPTIONS command...
914 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
916 httpClearFields(con
->http
);
918 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
920 cupsdCloseClient(con
);
925 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
929 * Do encryption stuff...
932 httpClearFields(con
->http
);
934 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
936 cupsdCloseClient(con
);
940 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
942 cupsdCloseClient(con
);
946 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
948 cupsdCloseClient(con
);
951 #endif /* HAVE_SSL */
954 httpClearFields(con
->http
);
955 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
957 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
959 cupsdCloseClient(con
);
963 else if (!is_path_absolute(con
->uri
))
966 * Protect against malicious users!
969 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
970 "Request for non-absolute resource \"%s\".", con
->uri
);
972 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
974 cupsdCloseClient(con
);
980 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
981 "Upgrade") && !httpIsEncrypted(con
->http
))
985 * Do encryption stuff...
988 httpClearFields(con
->http
);
990 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
993 cupsdCloseClient(con
);
997 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
999 cupsdCloseClient(con
);
1003 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1005 cupsdCloseClient(con
);
1008 #endif /* HAVE_SSL */
1011 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1013 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1014 cupsdCloseClient(con
);
1018 if (httpGetExpect(con
->http
) &&
1019 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1021 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1024 * Send 100-continue header...
1027 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1029 cupsdCloseClient(con
);
1036 * Send 417-expectation-failed header...
1039 httpClearFields(con
->http
);
1040 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1042 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1043 cupsdCloseClient(con
);
1048 switch (httpGetState(con
->http
))
1050 case HTTP_STATE_GET_SEND
:
1051 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1053 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1055 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1057 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1059 if (is_cgi(con
, filename
, &filestats
, type
))
1062 * Note: con->command and con->options were set by is_cgi()...
1065 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1067 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1069 cupsdCloseClient(con
);
1074 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1076 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1077 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1081 if (!check_if_modified(con
, &filestats
))
1083 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1085 cupsdCloseClient(con
);
1092 strlcpy(line
, "text/plain", sizeof(line
));
1094 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1096 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1098 cupsdCloseClient(con
);
1103 else if (!buf
[0] && (!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)))
1108 * Web interface is disabled. Show an appropriate message...
1111 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1113 cupsdCloseClient(con
);
1121 * Send CGI output...
1124 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 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1132 if (con
->uri
[8] && con
->uri
[9])
1133 cupsdSetString(&con
->options
, con
->uri
+ 8);
1135 cupsdSetString(&con
->options
, NULL
);
1137 else if (!strncmp(con
->uri
, "/jobs", 5))
1139 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1140 if (con
->uri
[5] && con
->uri
[6])
1141 cupsdSetString(&con
->options
, con
->uri
+ 5);
1143 cupsdSetString(&con
->options
, NULL
);
1145 else if (!strncmp(con
->uri
, "/printers", 9))
1147 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1148 if (con
->uri
[9] && con
->uri
[10])
1149 cupsdSetString(&con
->options
, con
->uri
+ 9);
1151 cupsdSetString(&con
->options
, NULL
);
1155 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1156 if (con
->uri
[5] && con
->uri
[6])
1157 cupsdSetString(&con
->options
, con
->uri
+ 5);
1159 cupsdSetString(&con
->options
, NULL
);
1162 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1164 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1166 cupsdCloseClient(con
);
1171 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1173 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1174 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1178 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1180 cupsdCloseClient(con
);
1186 case HTTP_STATE_POST_RECV
:
1188 * See if the POST request includes a Content-Length field, and if
1189 * so check the length against any limits that are set...
1192 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] && MaxRequestSize
> 0 && httpGetLength2(con
->http
) > MaxRequestSize
)
1195 * Request too large...
1198 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1200 cupsdCloseClient(con
);
1206 else if (httpGetLength2(con
->http
) < 0)
1209 * Negative content lengths are invalid!
1212 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1214 cupsdCloseClient(con
);
1222 * See what kind of POST request this is; for IPP requests the
1223 * content-type field will be "application/ipp"...
1226 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
), "application/ipp"))
1228 con
->request
= ippNew();
1231 else if (!WebInterface
)
1234 * Web interface is disabled. Show an appropriate message...
1237 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1239 cupsdCloseClient(con
);
1246 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1252 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1254 if (!is_cgi(con
, filename
, &filestats
, type
))
1257 * Only POST to CGI's...
1260 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1262 cupsdCloseClient(con
);
1267 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))
1273 if (!strncmp(con
->uri
, "/admin", 6))
1275 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1276 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1278 else if (!strncmp(con
->uri
, "/printers", 9))
1280 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1281 if (con
->uri
[9] && con
->uri
[10])
1282 cupsdSetString(&con
->options
, con
->uri
+ 9);
1284 cupsdSetString(&con
->options
, NULL
);
1286 else if (!strncmp(con
->uri
, "/classes", 8))
1288 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1289 if (con
->uri
[8] && con
->uri
[9])
1290 cupsdSetString(&con
->options
, con
->uri
+ 8);
1292 cupsdSetString(&con
->options
, NULL
);
1294 else if (!strncmp(con
->uri
, "/jobs", 5))
1296 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1297 if (con
->uri
[5] && con
->uri
[6])
1298 cupsdSetString(&con
->options
, con
->uri
+ 5);
1300 cupsdSetString(&con
->options
, NULL
);
1304 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1305 if (con
->uri
[5] && con
->uri
[6])
1306 cupsdSetString(&con
->options
, con
->uri
+ 5);
1308 cupsdSetString(&con
->options
, NULL
);
1311 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1312 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1316 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1318 cupsdCloseClient(con
);
1324 case HTTP_STATE_PUT_RECV
:
1326 * Validate the resource name...
1329 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1332 * PUT can only be done to the cupsd.conf file...
1335 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Disallowed PUT request for \"%s\".", con
->uri
);
1337 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1339 cupsdCloseClient(con
);
1347 * See if the PUT request includes a Content-Length field, and if
1348 * so check the length against any limits that are set...
1351 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] && MaxRequestSize
> 0 && httpGetLength2(con
->http
) > MaxRequestSize
)
1354 * Request too large...
1357 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1359 cupsdCloseClient(con
);
1365 else if (httpGetLength2(con
->http
) < 0)
1368 * Negative content lengths are invalid!
1371 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1373 cupsdCloseClient(con
);
1381 * Open a temporary file to hold the request...
1384 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1385 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1389 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to create request file \"%s\": %s", con
->filename
, strerror(errno
));
1391 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1393 cupsdCloseClient(con
);
1398 fchmod(con
->file
, 0640);
1399 fchown(con
->file
, RunUser
, Group
);
1400 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1403 case HTTP_STATE_DELETE
:
1404 case HTTP_STATE_TRACE
:
1405 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1406 cupsdCloseClient(con
);
1409 case HTTP_STATE_HEAD
:
1410 if ((filename
= get_file(con
, &filestats
, buf
, sizeof(buf
))) != NULL
)
1412 if (!check_if_modified(con
, &filestats
))
1414 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1416 cupsdCloseClient(con
);
1420 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1428 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1430 strlcpy(line
, "text/plain", sizeof(line
));
1432 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1434 httpClearFields(con
->http
);
1436 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
, httpGetDateString(filestats
.st_mtime
));
1437 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1439 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1441 cupsdCloseClient(con
);
1445 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1448 else if (!WebInterface
)
1450 httpClearFields(con
->http
);
1452 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1454 cupsdCloseClient(con
);
1458 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1462 if (!buf
[0] && (!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)))
1468 httpClearFields(con
->http
);
1470 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1472 cupsdCloseClient(con
);
1476 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1480 httpClearFields(con
->http
);
1482 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1484 cupsdCloseClient(con
);
1488 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1493 break; /* Anti-compiler-warning-code */
1499 * Handle any incoming data...
1502 switch (httpGetState(con
->http
))
1504 case HTTP_STATE_PUT_RECV
:
1507 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1509 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1510 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1511 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1512 httpError(con
->http
), strerror(httpError(con
->http
)));
1514 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1515 "HTTP_STATE_PUT_RECV Closing on EOF.");
1517 cupsdCloseClient(con
);
1522 con
->bytes
+= bytes
;
1524 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1528 unlink(con
->filename
);
1529 cupsdClearString(&con
->filename
);
1531 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1533 cupsdCloseClient(con
);
1538 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1540 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1541 "Unable to write %d bytes to \"%s\": %s", bytes
,
1542 con
->filename
, strerror(errno
));
1546 unlink(con
->filename
);
1547 cupsdClearString(&con
->filename
);
1549 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1551 cupsdCloseClient(con
);
1556 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1558 cupsdCloseClient(con
);
1562 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1564 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1567 * End of file, see how big it is...
1570 fstat(con
->file
, &filestats
);
1575 if (filestats
.st_size
> MaxRequestSize
&&
1579 * Request is too big; remove it and send an error...
1582 unlink(con
->filename
);
1583 cupsdClearString(&con
->filename
);
1585 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1587 cupsdCloseClient(con
);
1593 * Install the configuration file...
1596 status
= install_cupsd_conf(con
);
1599 * Return the status to the client...
1602 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1604 cupsdCloseClient(con
);
1610 case HTTP_STATE_POST_RECV
:
1613 if (con
->request
&& con
->file
< 0)
1616 * Grab any request data from the connection...
1619 if (!httpWait(con
->http
, 0))
1622 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1624 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1625 cupsLastErrorString());
1627 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1628 cupsdCloseClient(con
);
1631 else if (ipp_state
!= IPP_STATE_DATA
)
1633 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1635 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1636 cupsdCloseClient(con
);
1640 if (httpGetReady(con
->http
))
1646 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1647 con
->request
->request
.op
.version
[0],
1648 con
->request
->request
.op
.version
[1],
1649 ippOpString(con
->request
->request
.op
.operation_id
),
1650 con
->request
->request
.op
.request_id
);
1651 con
->bytes
+= (off_t
)ippLength(con
->request
);
1655 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1658 * Create a file as needed for the request data...
1661 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1663 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1667 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1668 "Unable to create request file \"%s\": %s",
1669 con
->filename
, strerror(errno
));
1671 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1673 cupsdCloseClient(con
);
1678 fchmod(con
->file
, 0640);
1679 fchown(con
->file
, RunUser
, Group
);
1680 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1683 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1685 if (!httpWait(con
->http
, 0))
1687 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1689 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1690 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1691 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1692 httpError(con
->http
), strerror(httpError(con
->http
)));
1694 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1695 "HTTP_STATE_POST_SEND Closing on EOF.");
1697 cupsdCloseClient(con
);
1702 con
->bytes
+= bytes
;
1704 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1708 unlink(con
->filename
);
1709 cupsdClearString(&con
->filename
);
1711 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1713 cupsdCloseClient(con
);
1718 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1720 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1721 "Unable to write %d bytes to \"%s\": %s",
1722 bytes
, con
->filename
, strerror(errno
));
1726 unlink(con
->filename
);
1727 cupsdClearString(&con
->filename
);
1729 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1732 cupsdCloseClient(con
);
1737 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1739 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1741 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1742 "Closing on unexpected state %s.",
1743 httpStateString(httpGetState(con
->http
)));
1744 cupsdCloseClient(con
);
1749 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1751 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1755 fstat(con
->file
, &filestats
);
1760 if (filestats
.st_size
> MaxRequestSize
&&
1764 * Request is too big; remove it and send an error...
1767 unlink(con
->filename
);
1768 cupsdClearString(&con
->filename
);
1773 * Delete any IPP request data...
1776 ippDelete(con
->request
);
1777 con
->request
= NULL
;
1780 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1782 cupsdCloseClient(con
);
1786 else if (filestats
.st_size
== 0)
1789 * Don't allow empty file...
1792 unlink(con
->filename
);
1793 cupsdClearString(&con
->filename
);
1798 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1800 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1802 cupsdCloseClient(con
);
1807 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1813 cupsdProcessIPPRequest(con
);
1817 unlink(con
->filename
);
1818 cupsdClearString(&con
->filename
);
1827 break; /* Anti-compiler-warning-code */
1830 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
1832 if (!httpGetKeepAlive(con
->http
))
1834 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1835 "Closing because Keep-Alive is disabled.");
1836 cupsdCloseClient(con
);
1840 cupsArrayRemove(ActiveClients
, con
);
1841 cupsdSetBusyState(0);
1848 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1851 int /* O - 1 on success, 0 on failure */
1853 cupsd_client_t
*con
, /* I - Client connection */
1854 char *command
, /* I - Command to run */
1855 char *options
, /* I - Command-line options */
1856 int root
) /* I - Run as root? */
1858 int fd
; /* Standard input file descriptor */
1863 fd
= open(con
->filename
, O_RDONLY
);
1867 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1868 "Unable to open \"%s\" for reading: %s",
1869 con
->filename
? con
->filename
: "/dev/null",
1874 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1879 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1880 con
->pipe_status
= HTTP_STATUS_OK
;
1882 httpClearFields(con
->http
);
1887 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
1888 command
, con
->pipe_pid
, con
->file
);
1890 if (con
->pipe_pid
== 0)
1893 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1895 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
1897 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
1899 con
->sent_header
= 0;
1900 con
->file_ready
= 0;
1901 con
->got_fields
= 0;
1902 con
->header_used
= 0;
1909 * 'cupsdSendError()' - Send an error message via HTTP.
1912 int /* O - 1 if successful, 0 otherwise */
1913 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1914 http_status_t code
, /* I - Error code */
1915 int auth_type
)/* I - Authentication type */
1917 char location
[HTTP_MAX_VALUE
]; /* Location field */
1920 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
1924 * Force client to upgrade for authentication if that is how the
1925 * server is configured...
1928 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
1929 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
1930 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
1931 !httpIsEncrypted(con
->http
))
1933 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
1935 #endif /* HAVE_SSL */
1938 * Put the request in the access_log file...
1941 cupsdLogRequest(con
, code
);
1944 * To work around bugs in some proxies, don't use Keep-Alive for some
1947 * Kerberos authentication doesn't work without Keep-Alive, so
1948 * never disable it in that case.
1951 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
1953 httpClearFields(con
->http
);
1954 httpClearCookie(con
->http
);
1956 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
1958 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
1959 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1961 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
1962 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
1963 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
1965 if (code
>= HTTP_STATUS_BAD_REQUEST
)
1968 * Send a human-readable error message.
1971 char message
[4096], /* Message for user */
1972 urltext
[1024], /* URL redirection text */
1973 redirect
[1024]; /* Redirection link */
1974 const char *text
; /* Status-specific text */
1979 if (code
== HTTP_STATUS_UNAUTHORIZED
)
1981 text
= _cupsLangString(con
->language
,
1982 _("Enter your username and password or the "
1983 "root username and password to access this "
1984 "page. If you are using Kerberos authentication, "
1985 "make sure you have a valid Kerberos ticket."));
1987 else if (code
== HTTP_STATUS_FORBIDDEN
)
1989 if (con
->username
[0])
1990 text
= _cupsLangString(con
->language
, _("Your account does not have the necessary privileges."));
1992 text
= _cupsLangString(con
->language
, _("You cannot access this page."));
1994 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
1998 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
);
2000 snprintf(redirect
, sizeof(redirect
), "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;URL=https://%s:%d%s\">\n", con
->servername
, con
->serverport
, con
->uri
);
2002 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2003 text
= _cupsLangString(con
->language
,
2004 _("The web interface is currently disabled. Run "
2005 "\"cupsctl WebInterface=yes\" to enable it."));
2009 snprintf(message
, sizeof(message
),
2010 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2011 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2014 "\t<META HTTP-EQUIV=\"Content-Type\" "
2015 "CONTENT=\"text/html; charset=utf-8\">\n"
2016 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2017 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2018 "HREF=\"/cups.css\">\n"
2026 _httpStatus(con
->language
, code
), redirect
,
2027 _httpStatus(con
->language
, code
), text
);
2030 * Send an error message back to the client. If the error code is a
2031 * 400 or 500 series, make sure the message contains some text, too!
2034 size_t length
= strlen(message
); /* Length of message */
2036 httpSetLength(con
->http
, length
);
2038 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2041 if (httpWrite2(con
->http
, message
, length
) < 0)
2044 if (httpFlushWrite(con
->http
) < 0)
2049 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2051 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2060 * 'cupsdSendHeader()' - Send an HTTP request.
2063 int /* O - 1 on success, 0 on failure */
2065 cupsd_client_t
*con
, /* I - Client to send to */
2066 http_status_t code
, /* I - HTTP status code */
2067 char *type
, /* I - MIME type of document */
2068 int auth_type
) /* I - Type of authentication */
2070 char auth_str
[1024]; /* Authorization string */
2073 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2076 * Send the HTTP status header...
2079 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2082 * Treat our special "web interface is disabled" status as "200 OK" for web
2086 code
= HTTP_STATUS_OK
;
2090 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2092 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2093 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2095 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2097 if (auth_type
== CUPSD_AUTH_NONE
)
2099 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2100 auth_type
= cupsdDefaultAuthType();
2102 auth_type
= con
->best
->type
;
2107 if (auth_type
== CUPSD_AUTH_BASIC
)
2109 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2111 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2113 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2116 if (con
->best
&& !con
->is_browser
&& !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2119 * Add a "trc" (try root certification) parameter for local
2120 * requests when the request requires system group membership - then the
2121 * client knows the root certificate can/should be used.
2123 * Also, for macOS we also look for @AUTHKEY and add an "AuthRef key=foo"
2124 * method as needed...
2127 char *name
, /* Current user name */
2128 *auth_key
; /* Auth key buffer */
2129 size_t auth_size
; /* Size of remaining buffer */
2130 int need_local
= 1; /* Do we need to list "Local" method? */
2132 auth_key
= auth_str
+ strlen(auth_str
);
2133 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2135 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
2136 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2138 strlcpy(auth_key
, ", PeerCred", auth_size
);
2142 #endif /* SO_PEERCRED && AF_LOCAL */
2144 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2146 name
= (char *)cupsArrayNext(con
->best
->names
))
2148 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendHeader: require \"%s\"", name
);
2150 #ifdef HAVE_AUTHORIZATION_H
2151 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2153 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\", Local trc=\"y\"", name
+ 9);
2155 /* end parenthesis is stripped in conf.c */
2159 #endif /* HAVE_AUTHORIZATION_H */
2160 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2162 #ifdef HAVE_AUTHORIZATION_H
2163 if (SystemGroupAuthKey
)
2164 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\", Local trc=\"y\"", SystemGroupAuthKey
);
2166 #endif /* HAVE_AUTHORIZATION_H */
2167 strlcpy(auth_key
, ", Local trc=\"y\"", auth_size
);
2174 strlcat(auth_key
, ", Local", auth_size
);
2179 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2181 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2185 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2186 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2190 if (!strcmp(type
, "text/html"))
2191 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2193 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2196 return (!httpWriteResponse(con
->http
, code
));
2201 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2205 cupsdUpdateCGI(void)
2207 char *ptr
, /* Pointer to end of line in buffer */
2208 message
[1024]; /* Pointer to message text */
2209 int loglevel
; /* Log level for message */
2212 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2213 message
, sizeof(message
))) != NULL
)
2215 if (loglevel
== CUPSD_LOG_INFO
)
2216 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2218 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2222 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2225 * Fatal error on pipe - should never happen!
2228 cupsdLogMessage(CUPSD_LOG_CRIT
,
2229 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2236 * 'cupsdWriteClient()' - Write data to a client as needed.
2240 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2242 int bytes
, /* Number of bytes written */
2243 field_col
; /* Current column */
2244 char *bufptr
, /* Pointer into buffer */
2245 *bufend
; /* Pointer to end of buffer */
2246 ipp_state_t ipp_state
; /* IPP state value */
2249 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2250 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2255 "data_encoding=HTTP_ENCODING_%s, "
2256 "data_remaining=" CUPS_LLFMT
", "
2260 httpError(con
->http
), (int)httpGetReady(con
->http
),
2261 httpStateString(httpGetState(con
->http
)),
2262 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2263 CUPS_LLCAST
httpGetLength2(con
->http
),
2265 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2266 con
->pipe_pid
, con
->file
);
2268 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2269 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2272 * If we get called in the wrong state, then something went wrong with the
2273 * connection and we need to shut it down...
2276 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2277 httpStateString(httpGetState(con
->http
)));
2278 cupsdCloseClient(con
);
2285 * Make sure we select on the CGI output...
2288 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2290 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2292 if (!con
->file_ready
)
2295 * Try again later when there is CGI output available...
2298 cupsdRemoveSelect(httpGetFd(con
->http
));
2302 con
->file_ready
= 0;
2305 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2307 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2310 * Limit GET bytes to original size of file (STR #3265)...
2313 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2316 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2318 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2323 * Write a single attribute or the IPP message header...
2326 ipp_state
= ippWrite(con
->http
, con
->response
);
2329 * If the write buffer has been flushed, stop buffering up attributes...
2332 if (httpGetPending(con
->http
) <= wused
)
2335 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2337 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2338 "Writing IPP response, ipp_state=%s, old "
2339 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2340 ippStateString(ipp_state
),
2341 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2343 if (httpGetPending(con
->http
) > 0)
2344 httpFlushWrite(con
->http
);
2346 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2347 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2349 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2350 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2351 (int)bytes
, httpGetState(con
->http
),
2352 CUPS_LLCAST
httpGetLength2(con
->http
));
2354 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2356 con
->header_used
+= bytes
;
2358 if (con
->pipe_pid
&& !con
->got_fields
)
2361 * Inspect the data for Content-Type and other fields.
2364 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2366 !con
->got_fields
&& bufptr
< bufend
;
2369 if (*bufptr
== '\n')
2372 * Send line to client...
2375 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2379 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2381 if (!con
->sent_header
)
2384 * Handle redirection and CGI status codes...
2387 http_field_t field
; /* HTTP field */
2388 char *value
= strchr(con
->header
, ':');
2389 /* Value of field */
2394 while (isspace(*value
& 255))
2398 field
= httpFieldValue(con
->header
);
2400 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2402 httpSetField(con
->http
, field
, value
);
2404 if (field
== HTTP_FIELD_LOCATION
)
2406 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2407 con
->sent_header
= 2;
2410 con
->sent_header
= 1;
2412 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2414 con
->pipe_status
= (http_status_t
)atoi(value
);
2415 con
->sent_header
= 2;
2417 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2419 httpSetCookie(con
->http
, value
);
2420 con
->sent_header
= 1;
2428 con
->header_used
-= bufptr
- con
->header
;
2430 if (con
->header_used
> 0)
2431 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2433 bufptr
= con
->header
- 1;
2436 * See if the line was empty...
2441 con
->got_fields
= 1;
2443 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2444 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2445 httpSetLength(con
->http
, 0);
2447 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2449 if (con
->pipe_status
== HTTP_STATUS_OK
)
2451 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2453 cupsdCloseClient(con
);
2459 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2461 cupsdCloseClient(con
);
2469 else if (*bufptr
!= '\r')
2473 if (!con
->got_fields
)
2477 if (con
->header_used
> 0)
2479 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2481 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2482 httpError(con
->http
), strerror(httpError(con
->http
)));
2483 cupsdCloseClient(con
);
2487 if (httpIsChunked(con
->http
))
2488 httpFlushWrite(con
->http
);
2490 con
->bytes
+= con
->header_used
;
2492 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2495 bytes
= con
->header_used
;
2497 con
->header_used
= 0;
2502 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2503 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2505 if (!con
->sent_header
&& con
->pipe_pid
)
2506 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2509 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2511 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2513 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2515 if (httpWrite2(con
->http
, "", 0) < 0)
2517 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2518 httpError(con
->http
), strerror(httpError(con
->http
)));
2519 cupsdCloseClient(con
);
2524 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2525 httpFlushWrite(con
->http
);
2526 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2529 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2531 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2535 cupsdRemoveSelect(con
->file
);
2538 cupsdEndProcess(con
->pipe_pid
, 0);
2547 unlink(con
->filename
);
2548 cupsdClearString(&con
->filename
);
2553 ippDelete(con
->request
);
2554 con
->request
= NULL
;
2559 ippDelete(con
->response
);
2560 con
->response
= NULL
;
2563 cupsdClearString(&con
->command
);
2564 cupsdClearString(&con
->options
);
2565 cupsdClearString(&con
->query_string
);
2567 if (!httpGetKeepAlive(con
->http
))
2569 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2570 "Closing because Keep-Alive is disabled.");
2571 cupsdCloseClient(con
);
2576 cupsArrayRemove(ActiveClients
, con
);
2577 cupsdSetBusyState(0);
2584 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2587 static int /* O - 1 if modified since */
2589 cupsd_client_t
*con
, /* I - Client connection */
2590 struct stat
*filestats
) /* I - File information */
2592 const char *ptr
; /* Pointer into field */
2593 time_t date
; /* Time/date value */
2594 off_t size
; /* Size/length value */
2599 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2604 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
);
2606 while (*ptr
!= '\0')
2608 while (isspace(*ptr
) || *ptr
== ';')
2611 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2614 size
= strtoll(ptr
, NULL
, 10);
2616 while (isdigit(*ptr
))
2619 else if (isalpha(*ptr
))
2621 date
= httpGetDateTime(ptr
);
2622 while (*ptr
!= '\0' && *ptr
!= ';')
2629 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2630 (date
< filestats
->st_mtime
&& date
!= 0) ||
2631 (size
== 0 && date
== 0));
2636 * 'compare_clients()' - Compare two client connections.
2639 static int /* O - Result of comparison */
2640 compare_clients(cupsd_client_t
*a
, /* I - First client */
2641 cupsd_client_t
*b
, /* I - Second client */
2642 void *data
) /* I - User data (not used) */
2657 * 'cupsd_start_tls()' - Start encryption on a connection.
2660 static int /* O - 0 on success, -1 on error */
2661 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2662 http_encryption_t e
) /* I - Encryption mode */
2664 if (httpEncryption(con
->http
, e
))
2666 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2667 cupsLastErrorString());
2671 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Connection now encrypted.");
2674 #endif /* HAVE_SSL */
2678 * 'get_file()' - Get a filename and state info.
2681 static char * /* O - Real filename */
2682 get_file(cupsd_client_t
*con
, /* I - Client connection */
2683 struct stat
*filestats
, /* O - File information */
2684 char *filename
, /* IO - Filename buffer */
2685 size_t len
) /* I - Buffer length */
2687 int status
; /* Status of filesystem calls */
2688 char *ptr
; /* Pointer info filename */
2689 size_t plen
; /* Remaining length after pointer */
2690 char language
[7], /* Language subdirectory, if any */
2691 dest
[1024]; /* Destination name */
2692 int perm_check
= 1; /* Do permissions check? */
2693 cupsd_printer_t
*p
; /* Printer */
2697 * Figure out the real filename...
2703 if (!strncmp(con
->uri
, "/help", 5) && (con
->uri
[5] == '/' || !con
->uri
[5]))
2706 * All help files are served by the help.cgi program...
2711 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"))
2713 strlcpy(dest
, strchr(con
->uri
+ 1, '/') + 1, sizeof(dest
));
2714 dest
[strlen(dest
) - 4] = '\0'; /* Strip .ppd */
2716 if ((p
= cupsdFindDest(dest
)) == NULL
)
2718 strlcpy(filename
, "/", len
);
2719 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2723 if (p
->type
& CUPS_PRINTER_CLASS
)
2725 int i
; /* Looping var */
2727 for (i
= 0; i
< p
->num_printers
; i
++)
2729 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
2731 snprintf(filename
, len
, "%s/ppd/%s.ppd", ServerRoot
, p
->printers
[i
]->name
);
2732 if (!access(filename
, 0))
2740 if (i
>= p
->num_printers
)
2744 snprintf(filename
, len
, "%s/ppd/%s.ppd", ServerRoot
, p
->name
);
2748 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"))
2750 strlcpy(dest
, strchr(con
->uri
+ 1, '/') + 1, sizeof(dest
));
2751 dest
[strlen(dest
) - 4] = '\0'; /* Strip .png */
2753 if ((p
= cupsdFindDest(dest
)) == NULL
)
2755 strlcpy(filename
, "/", len
);
2756 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2760 if (p
->type
& CUPS_PRINTER_CLASS
)
2762 int i
; /* Looping var */
2764 for (i
= 0; i
< p
->num_printers
; i
++)
2766 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
2768 snprintf(filename
, len
, "%s/images/%s.png", CacheDir
, p
->printers
[i
]->name
);
2769 if (!access(filename
, 0))
2777 if (i
>= p
->num_printers
)
2781 snprintf(filename
, len
, "%s/images/%s.png", CacheDir
, p
->name
);
2783 if (access(filename
, F_OK
) < 0)
2784 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2788 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2790 strlcpy(filename
, ConfigurationFile
, len
);
2794 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2796 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2797 strlcpy(filename
, AccessLog
, len
);
2798 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2799 strlcpy(filename
, ErrorLog
, len
);
2800 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2801 strlcpy(filename
, PageLog
, len
);
2807 else if (!strncmp(con
->uri
, "/admin", 6) || !strncmp(con
->uri
, "/classes", 8) || !strncmp(con
->uri
, "/jobs", 5) || !strncmp(con
->uri
, "/printers", 9))
2810 * Admin/class/job/printer pages are served by CGI...
2815 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2816 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2817 else if (!strncmp(con
->uri
, "/strings/", 9) && !strcmp(con
->uri
+ strlen(con
->uri
) - 8, ".strings"))
2819 strlcpy(dest
, con
->uri
+ 9, sizeof(dest
));
2820 dest
[strlen(dest
) - 8] = '\0';
2822 if ((p
= cupsdFindDest(dest
)) == NULL
)
2824 strlcpy(filename
, "/", len
);
2825 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No destination \"%s\" found.", dest
);
2831 strlcpy(filename
, "/", len
);
2832 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No strings files for \"%s\".", dest
);
2836 strlcpy(filename
, p
->strings
, len
);
2840 else if (con
->language
)
2842 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2843 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2846 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2848 if ((ptr
= strchr(filename
, '?')) != NULL
)
2852 * Grab the status for this language; if there isn't a language-specific file
2853 * then fallback to the default one...
2856 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
2857 strncmp(con
->uri
, "/icons/", 7) &&
2858 strncmp(con
->uri
, "/ppd/", 5) &&
2859 strncmp(con
->uri
, "/rss/", 5) &&
2860 strncmp(con
->uri
, "/strings/", 9) &&
2861 strncmp(con
->uri
, "/admin/conf/", 12) &&
2862 strncmp(con
->uri
, "/admin/log/", 11))
2865 * Drop the country code...
2869 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2871 if ((ptr
= strchr(filename
, '?')) != NULL
)
2874 if ((status
= lstat(filename
, filestats
)) != 0)
2877 * Drop the language prefix and try the root directory...
2881 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2883 if ((ptr
= strchr(filename
, '?')) != NULL
)
2886 status
= lstat(filename
, filestats
);
2891 * If we've found a symlink, 404 the sucker to avoid disclosing information.
2894 if (!status
&& S_ISLNK(filestats
->st_mode
))
2896 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
2901 * Similarly, if the file/directory does not have world read permissions, do
2902 * not allow access...
2905 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
2907 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
2912 * If we've found a directory, get the index.html file instead...
2915 if (!status
&& S_ISDIR(filestats
->st_mode
))
2918 * Make sure the URI ends with a slash...
2921 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
2922 strlcat(con
->uri
, "/", sizeof(con
->uri
));
2925 * Find the directory index file, trying every language...
2930 if (status
&& language
[0])
2933 * Try a different language subset...
2937 language
[3] = '\0'; /* Strip country code */
2939 language
[0] = '\0'; /* Strip language */
2943 * Look for the index file...
2946 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2948 if ((ptr
= strchr(filename
, '?')) != NULL
)
2951 ptr
= filename
+ strlen(filename
);
2952 plen
= len
- (size_t)(ptr
- filename
);
2954 strlcpy(ptr
, "index.html", plen
);
2955 status
= lstat(filename
, filestats
);
2957 while (status
&& language
[0]);
2960 * If we've found a symlink, 404 the sucker to avoid disclosing information.
2963 if (!status
&& S_ISLNK(filestats
->st_mode
))
2965 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
2970 * Similarly, if the file/directory does not have world read permissions, do
2971 * not allow access...
2974 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
2976 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
2981 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
2991 * 'install_cupsd_conf()' - Install a configuration file.
2994 static http_status_t
/* O - Status */
2995 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
2997 char filename
[1024]; /* Configuration filename */
2998 cups_file_t
*in
, /* Input file */
2999 *out
; /* Output file */
3000 char buffer
[16384]; /* Copy buffer */
3001 ssize_t bytes
; /* Number of bytes */
3005 * Open the request file...
3008 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3010 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3011 con
->filename
, strerror(errno
));
3016 * Open the new config file...
3019 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3025 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3029 * Copy from the request to the new config file...
3032 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3033 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3035 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3036 "Unable to copy to config file \"%s\": %s",
3037 ConfigurationFile
, strerror(errno
));
3042 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3043 cupsdUnlinkOrRemoveFile(filename
);
3049 * Close the files...
3054 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3058 * Remove the request file...
3061 cupsdUnlinkOrRemoveFile(con
->filename
);
3062 cupsdClearString(&con
->filename
);
3065 * Set the NeedReload flag...
3068 NeedReload
= RELOAD_CUPSD
;
3069 ReloadTime
= time(NULL
);
3072 * Return that the file was created successfully...
3075 return (HTTP_STATUS_CREATED
);
3078 * Common exit for errors...
3083 cupsdUnlinkOrRemoveFile(con
->filename
);
3084 cupsdClearString(&con
->filename
);
3086 return (HTTP_STATUS_SERVER_ERROR
);
3091 * 'is_cgi()' - Is the resource a CGI script/program?
3094 static int /* O - 1 = CGI, 0 = file */
3095 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3096 const char *filename
, /* I - Real filename */
3097 struct stat
*filestats
, /* I - File information */
3098 mime_type_t
*type
) /* I - MIME type */
3100 const char *options
; /* Options on URL */
3104 * Get the options, if any...
3107 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3110 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3114 * Check for known types...
3117 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3119 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");
3123 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") && (filestats
->st_mode
& 0111) && (getuid() || !(filestats
->st_mode
& 022)))
3126 * "application/x-httpd-cgi" is a CGI script.
3129 cupsdSetString(&con
->command
, filename
);
3132 cupsdSetStringf(&con
->options
, " %s", options
);
3134 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3138 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
->super
, type
->type
);
3144 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3147 static int /* O - 0 if relative, 1 if absolute */
3148 is_path_absolute(const char *path
) /* I - Input path */
3151 * Check for a leading slash...
3158 * Check for "<" or quotes in the path and reject since this is probably
3159 * someone trying to inject HTML...
3162 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3166 * Check for "/.." in the path...
3169 while ((path
= strstr(path
, "/..")) != NULL
)
3171 if (!path
[3] || path
[3] == '/')
3178 * If we haven't found any relative paths, return 1 indicating an
3187 * 'pipe_command()' - Pipe the output of a command to the remote client.
3190 static int /* O - Process ID */
3191 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3192 int infile
, /* I - Standard input for command */
3193 int *outfile
, /* O - Standard output for command */
3194 char *command
, /* I - Command to run */
3195 char *options
, /* I - Options for command */
3196 int root
) /* I - Run as root? */
3198 int i
; /* Looping var */
3199 int pid
; /* Process ID */
3200 char *commptr
, /* Command string pointer */
3201 commch
; /* Command string character */
3202 char *uriptr
; /* URI string pointer */
3203 int fds
[2]; /* Pipe FDs */
3204 int argc
; /* Number of arguments */
3205 int envc
; /* Number of environment variables */
3206 char argbuf
[10240], /* Argument buffer */
3207 *argv
[100], /* Argument strings */
3208 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3209 char auth_type
[256], /* AUTH_TYPE environment variable */
3210 content_length
[1024], /* CONTENT_LENGTH environment variable */
3211 content_type
[1024], /* CONTENT_TYPE environment variable */
3212 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3213 http_referer
[1024], /* HTTP_REFERER environment variable */
3214 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3215 lang
[1024], /* LANG environment variable */
3216 path_info
[1024], /* PATH_INFO environment variable */
3217 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3218 remote_host
[1024], /* REMOTE_HOST environment variable */
3219 remote_user
[1024], /* REMOTE_USER environment variable */
3220 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3221 script_name
[1024], /* SCRIPT_NAME environment variable */
3222 server_name
[1024], /* SERVER_NAME environment variable */
3223 server_port
[1024]; /* SERVER_PORT environment variable */
3224 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3228 * Parse a copy of the options string, which is of the form:
3230 * argument+argument+argument
3231 * ?argument+argument+argument
3232 * param=value¶m=value
3233 * ?param=value¶m=value
3234 * /name?argument+argument+argument
3235 * /name?param=value¶m=value
3237 * If the string contains an "=" character after the initial name,
3238 * then we treat it as a HTTP GET form request and make a copy of
3239 * the remaining string for the environment variable.
3241 * The string is always parsed out as command-line arguments, to
3242 * be consistent with Apache...
3245 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, outfile
, command
, options
? options
: "(null)", root
);
3250 strlcpy(argbuf
, options
, sizeof(argbuf
));
3254 if (argbuf
[0] == '/')
3257 * Found some trailing path information, set PATH_INFO...
3260 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3261 commptr
= argbuf
+ strlen(argbuf
);
3265 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3271 path_info
[0] = '\0';
3273 if (*commptr
== ' ')
3277 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3280 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3287 argv
[argc
++] = commptr
;
3289 for (; *commptr
&& argc
< 99; commptr
++)
3292 * Break arguments whenever we see a + or space...
3295 if (*commptr
== ' ' || *commptr
== '+')
3297 while (*commptr
== ' ' || *commptr
== '+')
3301 * If we don't have a blank string, save it as another argument...
3306 argv
[argc
] = commptr
;
3312 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3313 isxdigit(commptr
[2] & 255))
3316 * Convert the %xx notation to the individual character.
3319 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3320 *commptr
= (char)((commptr
[1] - '0') << 4);
3322 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3324 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3325 *commptr
|= commptr
[2] - '0';
3327 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3329 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3332 * Check for a %00 and break if that is the case...
3344 * Setup the environment variables as needed...
3347 if (con
->username
[0])
3349 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3350 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3352 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3356 auth_type
[0] = '\0';
3358 if (con
->request
&& (attr
= ippFindAttribute(con
->request
, "attributes-natural-language", IPP_TAG_LANGUAGE
)) != NULL
)
3360 cups_lang_t
*language
= cupsLangGet(ippGetString(attr
, 0, NULL
));
3362 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", language
->language
);
3363 cupsLangFree(language
);
3365 else if (con
->language
)
3366 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3368 strlcpy(lang
, "LANG=C", sizeof(lang
));
3370 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3371 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3372 sizeof(remote_addr
) - 12);
3374 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3375 httpGetHostname(con
->http
, NULL
, 0));
3377 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3378 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3381 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3382 DocumentRoot
, script_name
+ 12);
3384 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3386 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3388 char *nameptr
; /* Pointer to ":port" */
3390 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3391 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3392 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3393 *nameptr
= '\0'; /* Strip trailing ":port" */
3396 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3399 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3402 envp
[envc
++] = auth_type
;
3404 envp
[envc
++] = lang
;
3405 envp
[envc
++] = "REDIRECT_STATUS=1";
3406 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3407 envp
[envc
++] = server_name
;
3408 envp
[envc
++] = server_port
;
3409 envp
[envc
++] = remote_addr
;
3410 envp
[envc
++] = remote_host
;
3411 envp
[envc
++] = script_name
;
3412 envp
[envc
++] = script_filename
;
3415 envp
[envc
++] = path_info
;
3417 if (con
->username
[0])
3419 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3421 envp
[envc
++] = remote_user
;
3424 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3425 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3426 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3427 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3429 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3431 if (httpGetCookie(con
->http
))
3433 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3434 httpGetCookie(con
->http
));
3435 envp
[envc
++] = http_cookie
;
3438 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3440 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3441 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3442 envp
[envc
++] = http_user_agent
;
3445 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3447 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3448 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3449 envp
[envc
++] = http_referer
;
3452 if (con
->operation
== HTTP_STATE_GET
)
3454 envp
[envc
++] = "REQUEST_METHOD=GET";
3456 if (con
->query_string
)
3459 * Add GET form variables after ?...
3462 envp
[envc
++] = con
->query_string
;
3465 envp
[envc
++] = "QUERY_STRING=";
3469 snprintf(content_length
, sizeof(content_length
), "CONTENT_LENGTH=" CUPS_LLFMT
, CUPS_LLCAST con
->bytes
);
3470 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3471 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3473 envp
[envc
++] = "REQUEST_METHOD=POST";
3474 envp
[envc
++] = content_length
;
3475 envp
[envc
++] = content_type
;
3479 * Tell the CGI if we are using encryption...
3482 if (httpIsEncrypted(con
->http
))
3483 envp
[envc
++] = "HTTPS=ON";
3486 * Terminate the environment array...
3491 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3493 for (i
= 0; i
< argc
; i
++)
3494 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3495 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3496 for (i
= 0; i
< envc
; i
++)
3497 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3498 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3502 * Create a pipe for the output...
3505 if (cupsdOpenPipe(fds
))
3507 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3508 argv
[0], strerror(errno
));
3513 * Then execute the command...
3516 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3517 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3520 * Error - can't fork!
3523 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3526 cupsdClosePipe(fds
);
3532 * Fork successful - return the PID...
3535 if (con
->username
[0])
3536 cupsdAddCert(pid
, con
->username
, con
->type
);
3538 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3549 * 'valid_host()' - Is the Host: field valid?
3552 static int /* O - 1 if valid, 0 if not */
3553 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3555 cupsd_alias_t
*a
; /* Current alias */
3556 cupsd_netif_t
*netif
; /* Current network interface */
3557 const char *end
; /* End character */
3558 char *ptr
; /* Pointer into host value */
3562 * Copy the Host: header for later use...
3565 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3566 sizeof(con
->clientname
));
3567 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3570 con
->clientport
= atoi(ptr
);
3573 con
->clientport
= con
->serverport
;
3579 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3582 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3583 * addresses when accessing CUPS via the loopback interface...
3586 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3587 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3588 !strcmp(con
->clientname
, "127.0.0.1") ||
3589 !strcmp(con
->clientname
, "[::1]"));
3592 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3594 * Check if the hostname is something.local (Bonjour); if so, allow it.
3597 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3601 * "." on end, work back to second-to-last "."...
3604 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3607 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3608 !_cups_strcasecmp(end
, ".local.")))
3610 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3613 * Check if the hostname is an IP address...
3616 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3619 * Possible IPv4/IPv6 address...
3622 http_addrlist_t
*addrlist
; /* List of addresses */
3625 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3628 * Good IPv4/IPv6 address...
3631 httpAddrFreeList(addrlist
);
3637 * Check for (alias) name matches...
3640 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3642 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3645 * "ServerAlias *" allows all host values through...
3648 if (!strcmp(a
->name
, "*"))
3651 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3654 * Prefix matches; check the character at the end - it must be "." or nul.
3657 end
= con
->clientname
+ a
->namelen
;
3659 if (!*end
|| (*end
== '.' && !end
[1]))
3664 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3665 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3667 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3670 * "ServerAlias *" allows all host values through...
3673 if (!strcmp(a
->name
, "*"))
3676 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3679 * Prefix matches; check the character at the end - it must be "." or nul.
3682 end
= con
->clientname
+ a
->namelen
;
3684 if (!*end
|| (*end
== '.' && !end
[1]))
3688 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3691 * Check for interface hostname matches...
3694 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3696 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3698 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3701 * Prefix matches; check the character at the end - it must be "." or nul.
3704 end
= con
->clientname
+ netif
->hostlen
;
3706 if (!*end
|| (*end
== '.' && !end
[1]))
3716 * 'write_file()' - Send a file via HTTP.
3719 static int /* O - 0 on failure, 1 on success */
3720 write_file(cupsd_client_t
*con
, /* I - Client connection */
3721 http_status_t code
, /* I - HTTP status */
3722 char *filename
, /* I - Filename */
3723 char *type
, /* I - File type */
3724 struct stat
*filestats
) /* O - File information */
3726 con
->file
= open(filename
, O_RDONLY
);
3728 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3733 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3736 con
->sent_header
= 1;
3738 httpClearFields(con
->http
);
3740 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
3742 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3743 httpGetDateString(filestats
->st_mtime
));
3745 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3748 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3750 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3757 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3761 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3763 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
3765 con
->file_ready
= 1;
3767 cupsdRemoveSelect(con
->file
);
3768 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3770 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");