2 * Client routines for the CUPS scheduler.
4 * Copyright 2007-2017 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * This file contains Kerberos support code, copyright 2006 by
10 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
14 * Include necessary headers...
17 #define _CUPS_NO_DEPRECATED
18 #define _HTTP_NO_PRIVATE
23 #endif /* __APPLE__ */
26 #endif /* HAVE_TCPD_H */
33 static int check_if_modified(cupsd_client_t
*con
,
34 struct stat
*filestats
);
35 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
38 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
40 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
41 char *filename
, size_t len
);
42 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
43 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
44 struct stat
*filestats
, mime_type_t
*type
);
45 static int is_path_absolute(const char *path
);
46 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
47 char *command
, char *options
, int root
);
48 static int valid_host(cupsd_client_t
*con
);
49 static int write_file(cupsd_client_t
*con
, http_status_t code
,
50 char *filename
, char *type
,
51 struct stat
*filestats
);
52 static void write_pipe(cupsd_client_t
*con
);
56 * 'cupsdAcceptClient()' - Accept a new client.
60 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
62 const char *hostname
; /* Hostname of client */
63 char name
[256]; /* Hostname of client */
64 int count
; /* Count of connections on a host */
65 cupsd_client_t
*con
, /* New client pointer */
66 *tempcon
; /* Temporary client pointer */
67 socklen_t addrlen
; /* Length of address */
68 http_addr_t temp
; /* Temporary address variable */
69 static time_t last_dos
= 0; /* Time of last DoS attack */
71 struct request_info wrap_req
; /* TCP wrappers request information */
72 #endif /* HAVE_TCPD_H */
75 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis
, lis
->fd
, cupsArrayCount(Clients
));
78 * Make sure we don't have a full set of clients already...
81 if (cupsArrayCount(Clients
) == MaxClients
)
87 * Get a pointer to the next available client...
91 Clients
= cupsArrayNew(NULL
, NULL
);
95 cupsdLogMessage(CUPSD_LOG_ERROR
,
96 "Unable to allocate memory for clients array!");
97 cupsdPauseListening();
102 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
106 cupsdLogMessage(CUPSD_LOG_ERROR
,
107 "Unable to allocate memory for active clients array!");
108 cupsdPauseListening();
112 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
114 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
115 cupsdPauseListening();
120 * Accept the client and get the remote address...
123 con
->number
= ++ LastClientNumber
;
126 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
128 if (errno
== ENFILE
|| errno
== EMFILE
)
129 cupsdPauseListening();
131 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
139 * Save the connected address and port number...
142 addrlen
= sizeof(con
->clientaddr
);
144 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&con
->clientaddr
, &addrlen
) || addrlen
== 0)
145 con
->clientaddr
= lis
->address
;
147 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Server address is \"%s\".", httpAddrString(&con
->clientaddr
, name
, sizeof(name
)));
150 * Check the number of clients on the same address...
153 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
155 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
156 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
159 if (count
>= MaxClientsPerHost
)
163 if (count
>= MaxClientsPerHost
)
165 if ((time(NULL
) - last_dos
) >= 60)
167 last_dos
= time(NULL
);
168 cupsdLogMessage(CUPSD_LOG_WARN
,
169 "Possible DoS attack - more than %d clients connecting "
172 httpGetHostname(con
->http
, name
, sizeof(name
)));
175 httpClose(con
->http
);
181 * Get the hostname or format the IP address as needed...
185 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
187 hostname
= httpGetHostname(con
->http
, NULL
, 0);
189 if (hostname
== NULL
&& HostNameLookups
== 2)
192 * Can't have an unresolved IP address with double-lookups enabled...
195 httpClose(con
->http
);
197 cupsdLogClient(con
, CUPSD_LOG_WARN
,
198 "Name lookup failed - connection from %s closed!",
199 httpGetHostname(con
->http
, NULL
, 0));
205 if (HostNameLookups
== 2)
208 * Do double lookups as needed...
211 http_addrlist_t
*addrlist
, /* List of addresses */
212 *addr
; /* Current address */
214 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
217 * See if the hostname maps to the same IP address...
220 for (addr
= addrlist
; addr
; addr
= addr
->next
)
221 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
227 httpAddrFreeList(addrlist
);
232 * Can't have a hostname that doesn't resolve to the same IP address
233 * with double-lookups enabled...
236 httpClose(con
->http
);
238 cupsdLogClient(con
, CUPSD_LOG_WARN
,
239 "IP lookup failed - connection from %s closed!",
240 httpGetHostname(con
->http
, NULL
, 0));
248 * See if the connection is denied by TCP wrappers...
251 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
255 if (!hosts_access(&wrap_req
))
257 httpClose(con
->http
);
259 cupsdLogClient(con
, CUPSD_LOG_WARN
,
260 "Connection from %s refused by /etc/hosts.allow and "
261 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
265 #endif /* HAVE_TCPD_H */
268 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
271 socklen_t peersize
; /* Size of peer credentials */
272 pid_t peerpid
; /* Peer process ID */
273 char peername
[256]; /* Name of process */
275 peersize
= sizeof(peerpid
);
276 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
279 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
280 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
281 "Accepted from %s (Domain ???[%d])",
282 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
284 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
285 "Accepted from %s (Domain %s[%d])",
286 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
289 # endif /* __APPLE__ */
291 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
292 httpGetHostname(con
->http
, NULL
, 0));
295 #endif /* AF_LOCAL */
296 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
297 httpGetHostname(con
->http
, NULL
, 0),
298 httpAddrPort(httpGetAddress(con
->http
)),
299 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
302 * Get the local address the client connected to...
305 addrlen
= sizeof(temp
);
306 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
308 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
311 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
312 con
->serverport
= LocalPort
;
315 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
317 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
318 con
->serverport
= LocalPort
;
320 #endif /* AF_LOCAL */
323 if (httpAddrLocalhost(&temp
))
324 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
325 else if (HostNameLookups
)
326 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
328 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
330 con
->serverport
= httpAddrPort(&(lis
->address
));
334 * Add the connection to the array of active clients...
337 cupsArrayAdd(Clients
, con
);
340 * Add the socket to the server select.
343 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
346 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
349 * Temporarily suspend accept()'s until we lose a client...
352 if (cupsArrayCount(Clients
) == MaxClients
)
353 cupsdPauseListening();
357 * See if we are connecting on a secure port...
360 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
363 * https connection; go secure...
366 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
367 cupsdCloseClient(con
);
371 #endif /* HAVE_SSL */
376 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
380 cupsdCloseAllClients(void)
382 cupsd_client_t
*con
; /* Current client */
385 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients
));
387 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
389 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
390 if (cupsdCloseClient(con
))
391 cupsdCloseClient(con
);
396 * 'cupsdCloseClient()' - Close a remote client.
399 int /* O - 1 if partial close, 0 if fully closed */
400 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
402 int partial
; /* Do partial close for SSL? */
405 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
408 * Flush pending writes before closing...
411 httpFlushWrite(con
->http
);
415 if (con
->pipe_pid
!= 0)
418 * Stop any CGI process...
421 cupsdEndProcess(con
->pipe_pid
, 1);
427 cupsdRemoveSelect(con
->file
);
434 * Close the socket and clear the file from the input set for select()...
437 if (httpGetFd(con
->http
) >= 0)
439 cupsArrayRemove(ActiveClients
, con
);
440 cupsdSetBusyState(0);
444 * Shutdown encryption as needed...
447 if (httpIsEncrypted(con
->http
))
449 #endif /* HAVE_SSL */
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 (cupsArrayCount(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 *ptr
; /* Pointer into strings */
552 http_status_t status
; /* Transfer status */
553 ipp_state_t ipp_state
; /* State of IPP transfer */
554 int bytes
; /* Number of bytes to POST */
555 char *filename
; /* Name of file for GET/HEAD */
556 char buf
[1024]; /* Buffer for real filename */
557 struct stat filestats
; /* File information */
558 mime_type_t
*type
; /* MIME type of file */
559 cupsd_printer_t
*p
; /* Printer */
560 static unsigned request_id
= 0; /* Request ID for temp files */
563 status
= HTTP_STATUS_CONTINUE
;
565 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=" CUPS_LLFMT
", request=%p(%s), file=%d", httpError(con
->http
), (int)httpGetReady(con
->http
), httpStateString(httpGetState(con
->http
)), httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH", CUPS_LLCAST
httpGetRemaining(con
->http
), con
->request
, con
->request
? ippStateString(ippGetState(con
->request
)) : "", con
->file
);
567 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
568 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
569 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
572 * If we get called in the wrong state, then something went wrong with the
573 * connection and we need to shut it down...
576 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
579 * Connection closed...
582 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
583 cupsdCloseClient(con
);
587 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con
->http
)));
588 cupsdCloseClient(con
);
596 * Automatically check for a SSL/TLS handshake...
601 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
602 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
605 * Encrypt this connection...
608 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf
[0] & 255);
610 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
611 cupsdCloseClient(con
);
616 #endif /* HAVE_SSL */
618 switch (httpGetState(con
->http
))
620 case HTTP_STATE_WAITING
:
622 * See if we've received a request line...
625 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
626 if (con
->operation
== HTTP_STATE_ERROR
||
627 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
628 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
630 if (httpError(con
->http
))
631 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
632 "HTTP_STATE_WAITING Closing for error %d (%s)",
633 httpError(con
->http
), strerror(httpError(con
->http
)));
635 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
636 "HTTP_STATE_WAITING Closing on error: %s",
637 cupsLastErrorString());
639 cupsdCloseClient(con
);
644 * Ignore blank request lines...
647 if (con
->operation
== HTTP_STATE_WAITING
)
651 * Clear other state variables...
658 con
->username
[0] = '\0';
659 con
->password
[0] = '\0';
661 cupsdClearString(&con
->command
);
662 cupsdClearString(&con
->options
);
663 cupsdClearString(&con
->query_string
);
667 ippDelete(con
->request
);
673 ippDelete(con
->response
);
674 con
->response
= NULL
;
679 cupsLangFree(con
->language
);
680 con
->language
= NULL
;
686 #endif /* HAVE_GSSAPI */
689 * Handle full URLs in the request line...
692 if (strcmp(con
->uri
, "*"))
694 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
695 userpass
[HTTP_MAX_URI
], /* Username:password */
696 hostname
[HTTP_MAX_URI
], /* Hostname */
697 resource
[HTTP_MAX_URI
]; /* Resource path */
698 int port
; /* Port number */
701 * Separate the URI into its components...
704 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
705 scheme
, sizeof(scheme
),
706 userpass
, sizeof(userpass
),
707 hostname
, sizeof(hostname
), &port
,
708 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
710 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
712 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
713 cupsdCloseClient(con
);
718 * Only allow URIs with the servername, localhost, or an IP
722 if (strcmp(scheme
, "file") &&
723 _cups_strcasecmp(hostname
, ServerName
) &&
724 _cups_strcasecmp(hostname
, "localhost") &&
725 !cupsArrayFind(ServerAlias
, hostname
) &&
726 !isdigit(hostname
[0]) && hostname
[0] != '[')
729 * Nope, we don't do proxies...
732 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
734 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
735 cupsdCloseClient(con
);
740 * Copy the resource portion back into the URI; both resource and
741 * con->uri are HTTP_MAX_URI bytes in size...
744 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
748 * Process the request...
751 gettimeofday(&(con
->start
), NULL
);
753 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
754 httpStateString(con
->operation
) + 11, con
->uri
,
755 httpGetVersion(con
->http
) / 100,
756 httpGetVersion(con
->http
) % 100);
758 if (!cupsArrayFind(ActiveClients
, con
))
760 cupsArrayAdd(ActiveClients
, con
);
761 cupsdSetBusyState(0);
764 case HTTP_STATE_OPTIONS
:
765 case HTTP_STATE_DELETE
:
766 case HTTP_STATE_GET
:
767 case HTTP_STATE_HEAD
:
768 case HTTP_STATE_POST
:
769 case HTTP_STATE_PUT
:
770 case HTTP_STATE_TRACE
:
772 * Parse incoming parameters until the status changes...
775 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
776 if (!httpGetReady(con
->http
))
779 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
781 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
782 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
783 "Closing for error %d (%s) while reading headers.",
784 httpError(con
->http
), strerror(httpError(con
->http
)));
786 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
787 "Closing on EOF while reading headers.");
789 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
790 cupsdCloseClient(con
);
796 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
799 * Connection closed...
802 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
803 cupsdCloseClient(con
);
806 break; /* Anti-compiler-warning-code */
810 * Handle new transfers...
813 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d, state=%d", status
, httpGetState(con
->http
));
815 if (status
== HTTP_STATUS_OK
)
817 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
820 * Figure out the locale from the Accept-Language and Content-Type
824 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
828 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
832 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
833 "charset=")) != NULL
)
836 * Combine language and charset, and trim any extra params in the
840 snprintf(locale
, sizeof(locale
), "%s.%s",
841 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
843 if ((ptr
= strchr(locale
, ',')) != NULL
)
847 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
848 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
850 con
->language
= cupsLangGet(locale
);
853 con
->language
= cupsLangGet(DefaultLocale
);
857 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
858 "Keep-Alive", 10) && KeepAlive
)
859 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
860 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
862 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
864 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
865 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
868 * HTTP/1.1 and higher require the "Host:" field...
871 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
873 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
874 cupsdCloseClient(con
);
878 else if (!valid_host(con
))
881 * Access to localhost must use "localhost" or the corresponding IPv4
882 * or IPv6 values in the Host: field.
885 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
886 "Request from \"%s\" using invalid Host: field \"%s\".",
887 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
889 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
891 cupsdCloseClient(con
);
895 else if (con
->operation
== HTTP_STATE_OPTIONS
)
898 * Do OPTIONS command...
901 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
903 httpClearFields(con
->http
);
905 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
907 cupsdCloseClient(con
);
912 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
916 * Do encryption stuff...
919 httpClearFields(con
->http
);
921 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
923 cupsdCloseClient(con
);
927 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
929 cupsdCloseClient(con
);
933 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
935 cupsdCloseClient(con
);
938 #endif /* HAVE_SSL */
941 httpClearFields(con
->http
);
942 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
943 "GET, HEAD, OPTIONS, POST, PUT");
944 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
946 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
948 cupsdCloseClient(con
);
952 else if (!is_path_absolute(con
->uri
))
955 * Protect against malicious users!
958 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
959 "Request for non-absolute resource \"%s\".", con
->uri
);
961 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
963 cupsdCloseClient(con
);
969 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
970 "Upgrade") && !httpIsEncrypted(con
->http
))
974 * Do encryption stuff...
977 httpClearFields(con
->http
);
979 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
982 cupsdCloseClient(con
);
986 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
988 cupsdCloseClient(con
);
992 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
994 cupsdCloseClient(con
);
997 #endif /* HAVE_SSL */
1000 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1002 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1003 cupsdCloseClient(con
);
1007 if (httpGetExpect(con
->http
) &&
1008 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1010 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1013 * Send 100-continue header...
1016 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1018 cupsdCloseClient(con
);
1025 * Send 417-expectation-failed header...
1028 httpClearFields(con
->http
);
1029 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1031 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1032 cupsdCloseClient(con
);
1037 switch (httpGetState(con
->http
))
1039 case HTTP_STATE_GET_SEND
:
1040 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1042 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1043 !strncmp(con
->uri
, "/printers/", 10) ||
1044 !strncmp(con
->uri
, "/classes/", 9)) &&
1045 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1048 * Send PPD file - get the real printer name since printer
1049 * names are not case sensitive but filenames can be...
1052 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1054 if (!strncmp(con
->uri
, "/ppd/", 5))
1055 p
= cupsdFindPrinter(con
->uri
+ 5);
1056 else if (!strncmp(con
->uri
, "/printers/", 10))
1057 p
= cupsdFindPrinter(con
->uri
+ 10);
1060 p
= cupsdFindClass(con
->uri
+ 9);
1064 int i
; /* Looping var */
1066 for (i
= 0; i
< p
->num_printers
; i
++)
1068 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1070 char ppdname
[1024];/* PPD filename */
1072 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1073 ServerRoot
, p
->printers
[i
]->name
);
1074 if (!access(ppdname
, 0))
1082 if (i
>= p
->num_printers
)
1089 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1093 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1095 cupsdCloseClient(con
);
1102 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1103 !strncmp(con
->uri
, "/printers/", 10) ||
1104 !strncmp(con
->uri
, "/classes/", 9)) &&
1105 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1108 * Send icon file - get the real queue name since queue names are
1109 * not case sensitive but filenames can be...
1112 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1114 if (!strncmp(con
->uri
, "/icons/", 7))
1115 p
= cupsdFindPrinter(con
->uri
+ 7);
1116 else if (!strncmp(con
->uri
, "/printers/", 10))
1117 p
= cupsdFindPrinter(con
->uri
+ 10);
1120 p
= cupsdFindClass(con
->uri
+ 9);
1124 int i
; /* Looping var */
1126 for (i
= 0; i
< p
->num_printers
; i
++)
1128 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1130 char ppdname
[1024];/* PPD filename */
1132 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1133 ServerRoot
, p
->printers
[i
]->name
);
1134 if (!access(ppdname
, 0))
1142 if (i
>= p
->num_printers
)
1148 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1151 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1153 cupsdCloseClient(con
);
1161 if ((!strncmp(con
->uri
, "/admin", 6) && strcmp(con
->uri
, "/admin/conf/cupsd.conf") && strncmp(con
->uri
, "/admin/log/", 11)) ||
1162 !strncmp(con
->uri
, "/printers", 9) ||
1163 !strncmp(con
->uri
, "/classes", 8) ||
1164 !strncmp(con
->uri
, "/help", 5) ||
1165 !strncmp(con
->uri
, "/jobs", 5))
1170 * Web interface is disabled. Show an appropriate message...
1173 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1175 cupsdCloseClient(con
);
1183 * Send CGI output...
1186 if (!strncmp(con
->uri
, "/admin", 6))
1188 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1191 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1193 else if (!strncmp(con
->uri
, "/printers", 9))
1195 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1198 if (con
->uri
[9] && con
->uri
[10])
1199 cupsdSetString(&con
->options
, con
->uri
+ 9);
1201 cupsdSetString(&con
->options
, NULL
);
1203 else if (!strncmp(con
->uri
, "/classes", 8))
1205 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1208 if (con
->uri
[8] && con
->uri
[9])
1209 cupsdSetString(&con
->options
, con
->uri
+ 8);
1211 cupsdSetString(&con
->options
, NULL
);
1213 else if (!strncmp(con
->uri
, "/jobs", 5))
1215 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1218 if (con
->uri
[5] && con
->uri
[6])
1219 cupsdSetString(&con
->options
, con
->uri
+ 5);
1221 cupsdSetString(&con
->options
, NULL
);
1225 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1228 if (con
->uri
[5] && con
->uri
[6])
1229 cupsdSetString(&con
->options
, con
->uri
+ 5);
1231 cupsdSetString(&con
->options
, NULL
);
1234 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1236 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1238 cupsdCloseClient(con
);
1243 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1245 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1246 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1248 else if (!strncmp(con
->uri
, "/admin/log/", 11) && (strchr(con
->uri
+ 11, '/') || strlen(con
->uri
) == 11))
1251 * GET can only be done to configuration files directly under
1255 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Request for subdirectory \"%s\".", con
->uri
);
1257 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1259 cupsdCloseClient(con
);
1271 if ((filename
= get_file(con
, &filestats
, buf
,
1272 sizeof(buf
))) == NULL
)
1274 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1276 cupsdCloseClient(con
);
1283 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1285 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1287 if (is_cgi(con
, filename
, &filestats
, type
))
1290 * Note: con->command and con->options were set by
1294 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1296 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1298 cupsdCloseClient(con
);
1303 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1305 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1306 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1310 if (!check_if_modified(con
, &filestats
))
1312 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1314 cupsdCloseClient(con
);
1321 strlcpy(line
, "text/plain", sizeof(line
));
1323 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1325 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1327 cupsdCloseClient(con
);
1334 case HTTP_STATE_POST_RECV
:
1336 * See if the POST request includes a Content-Length field, and if
1337 * so check the length against any limits that are set...
1340 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1341 MaxRequestSize
> 0 &&
1342 httpGetLength2(con
->http
) > MaxRequestSize
)
1345 * Request too large...
1348 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1350 cupsdCloseClient(con
);
1356 else if (httpGetLength2(con
->http
) < 0)
1359 * Negative content lengths are invalid!
1362 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1364 cupsdCloseClient(con
);
1372 * See what kind of POST request this is; for IPP requests the
1373 * content-type field will be "application/ipp"...
1376 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1378 con
->request
= ippNew();
1379 else if (!WebInterface
)
1382 * Web interface is disabled. Show an appropriate message...
1385 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1387 cupsdCloseClient(con
);
1393 else if ((!strncmp(con
->uri
, "/admin", 6) && strncmp(con
->uri
, "/admin/log/", 11)) ||
1394 !strncmp(con
->uri
, "/printers", 9) ||
1395 !strncmp(con
->uri
, "/classes", 8) ||
1396 !strncmp(con
->uri
, "/help", 5) ||
1397 !strncmp(con
->uri
, "/jobs", 5))
1403 if (!strncmp(con
->uri
, "/admin", 6))
1405 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1408 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1410 else if (!strncmp(con
->uri
, "/printers", 9))
1412 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1415 if (con
->uri
[9] && con
->uri
[10])
1416 cupsdSetString(&con
->options
, con
->uri
+ 9);
1418 cupsdSetString(&con
->options
, NULL
);
1420 else if (!strncmp(con
->uri
, "/classes", 8))
1422 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1425 if (con
->uri
[8] && con
->uri
[9])
1426 cupsdSetString(&con
->options
, con
->uri
+ 8);
1428 cupsdSetString(&con
->options
, NULL
);
1430 else if (!strncmp(con
->uri
, "/jobs", 5))
1432 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1435 if (con
->uri
[5] && con
->uri
[6])
1436 cupsdSetString(&con
->options
, con
->uri
+ 5);
1438 cupsdSetString(&con
->options
, NULL
);
1442 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1445 if (con
->uri
[5] && con
->uri
[6])
1446 cupsdSetString(&con
->options
, con
->uri
+ 5);
1448 cupsdSetString(&con
->options
, NULL
);
1451 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1452 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1460 if ((filename
= get_file(con
, &filestats
, buf
,
1461 sizeof(buf
))) == NULL
)
1463 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1465 cupsdCloseClient(con
);
1472 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1474 if (!is_cgi(con
, filename
, &filestats
, type
))
1477 * Only POST to CGI's...
1480 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1482 cupsdCloseClient(con
);
1489 case HTTP_STATE_PUT_RECV
:
1491 * Validate the resource name...
1494 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1497 * PUT can only be done to the cupsd.conf file...
1500 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1501 "Disallowed PUT request for \"%s\".", con
->uri
);
1503 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1505 cupsdCloseClient(con
);
1513 * See if the PUT request includes a Content-Length field, and if
1514 * so check the length against any limits that are set...
1517 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1518 MaxRequestSize
> 0 &&
1519 httpGetLength2(con
->http
) > MaxRequestSize
)
1522 * Request too large...
1525 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1527 cupsdCloseClient(con
);
1533 else if (httpGetLength2(con
->http
) < 0)
1536 * Negative content lengths are invalid!
1539 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1541 cupsdCloseClient(con
);
1549 * Open a temporary file to hold the request...
1552 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1554 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1558 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1559 "Unable to create request file \"%s\": %s",
1560 con
->filename
, strerror(errno
));
1562 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1564 cupsdCloseClient(con
);
1569 fchmod(con
->file
, 0640);
1570 fchown(con
->file
, RunUser
, Group
);
1571 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1574 case HTTP_STATE_DELETE
:
1575 case HTTP_STATE_TRACE
:
1576 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1577 cupsdCloseClient(con
);
1580 case HTTP_STATE_HEAD
:
1581 if (!strncmp(con
->uri
, "/printers/", 10) &&
1582 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1585 * Send PPD file - get the real printer name since printer
1586 * names are not case sensitive but filenames can be...
1589 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1591 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1592 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1595 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1597 cupsdCloseClient(con
);
1601 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1605 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1606 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1609 * Send PNG file - get the real printer name since printer
1610 * names are not case sensitive but filenames can be...
1613 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1615 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1616 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1619 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1621 cupsdCloseClient(con
);
1625 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1629 else if (!WebInterface
)
1631 httpClearFields(con
->http
);
1633 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1635 cupsdCloseClient(con
);
1639 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1643 if ((!strncmp(con
->uri
, "/admin", 6) && strcmp(con
->uri
, "/admin/conf/cupsd.conf") && strncmp(con
->uri
, "/admin/log/", 11)) ||
1644 !strncmp(con
->uri
, "/printers", 9) ||
1645 !strncmp(con
->uri
, "/classes", 8) ||
1646 !strncmp(con
->uri
, "/help", 5) ||
1647 !strncmp(con
->uri
, "/jobs", 5))
1653 httpClearFields(con
->http
);
1655 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1657 cupsdCloseClient(con
);
1661 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1663 else if (!strncmp(con
->uri
, "/admin/log/", 11) && (strchr(con
->uri
+ 11, '/') || strlen(con
->uri
) == 11))
1666 * HEAD can only be done to configuration files under
1670 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1671 "Request for subdirectory \"%s\".", con
->uri
);
1673 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1675 cupsdCloseClient(con
);
1679 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1682 else if ((filename
= get_file(con
, &filestats
, buf
,
1683 sizeof(buf
))) == NULL
)
1685 httpClearFields(con
->http
);
1687 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1690 cupsdCloseClient(con
);
1694 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1696 else if (!check_if_modified(con
, &filestats
))
1698 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1700 cupsdCloseClient(con
);
1704 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1712 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1714 strlcpy(line
, "text/plain", sizeof(line
));
1716 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1718 httpClearFields(con
->http
);
1720 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1721 httpGetDateString(filestats
.st_mtime
));
1722 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1724 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1726 cupsdCloseClient(con
);
1730 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1735 break; /* Anti-compiler-warning-code */
1741 * Handle any incoming data...
1744 switch (httpGetState(con
->http
))
1746 case HTTP_STATE_PUT_RECV
:
1749 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1751 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1752 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1753 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1754 httpError(con
->http
), strerror(httpError(con
->http
)));
1756 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1757 "HTTP_STATE_PUT_RECV Closing on EOF.");
1759 cupsdCloseClient(con
);
1764 con
->bytes
+= bytes
;
1766 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1770 unlink(con
->filename
);
1771 cupsdClearString(&con
->filename
);
1773 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1775 cupsdCloseClient(con
);
1780 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1782 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1783 "Unable to write %d bytes to \"%s\": %s", bytes
,
1784 con
->filename
, strerror(errno
));
1788 unlink(con
->filename
);
1789 cupsdClearString(&con
->filename
);
1791 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1793 cupsdCloseClient(con
);
1798 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1800 cupsdCloseClient(con
);
1804 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1806 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1809 * End of file, see how big it is...
1812 fstat(con
->file
, &filestats
);
1817 if (filestats
.st_size
> MaxRequestSize
&&
1821 * Request is too big; remove it and send an error...
1824 unlink(con
->filename
);
1825 cupsdClearString(&con
->filename
);
1827 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1829 cupsdCloseClient(con
);
1835 * Install the configuration file...
1838 status
= install_cupsd_conf(con
);
1841 * Return the status to the client...
1844 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1846 cupsdCloseClient(con
);
1852 case HTTP_STATE_POST_RECV
:
1855 if (con
->request
&& con
->file
< 0)
1858 * Grab any request data from the connection...
1861 if (!httpWait(con
->http
, 0))
1864 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1866 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1867 cupsLastErrorString());
1869 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1870 cupsdCloseClient(con
);
1873 else if (ipp_state
!= IPP_STATE_DATA
)
1875 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1877 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1878 cupsdCloseClient(con
);
1882 if (httpGetReady(con
->http
))
1888 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1889 con
->request
->request
.op
.version
[0],
1890 con
->request
->request
.op
.version
[1],
1891 ippOpString(con
->request
->request
.op
.operation_id
),
1892 con
->request
->request
.op
.request_id
);
1893 con
->bytes
+= (off_t
)ippLength(con
->request
);
1897 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1900 * Create a file as needed for the request data...
1903 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1905 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1909 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1910 "Unable to create request file \"%s\": %s",
1911 con
->filename
, strerror(errno
));
1913 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1915 cupsdCloseClient(con
);
1920 fchmod(con
->file
, 0640);
1921 fchown(con
->file
, RunUser
, Group
);
1922 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1925 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1927 if (!httpWait(con
->http
, 0))
1929 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1931 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1932 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1933 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1934 httpError(con
->http
), strerror(httpError(con
->http
)));
1936 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1937 "HTTP_STATE_POST_SEND Closing on EOF.");
1939 cupsdCloseClient(con
);
1944 con
->bytes
+= bytes
;
1946 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1950 unlink(con
->filename
);
1951 cupsdClearString(&con
->filename
);
1953 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1955 cupsdCloseClient(con
);
1960 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1962 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1963 "Unable to write %d bytes to \"%s\": %s",
1964 bytes
, con
->filename
, strerror(errno
));
1968 unlink(con
->filename
);
1969 cupsdClearString(&con
->filename
);
1971 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1974 cupsdCloseClient(con
);
1979 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1981 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1983 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1984 "Closing on unexpected state %s.",
1985 httpStateString(httpGetState(con
->http
)));
1986 cupsdCloseClient(con
);
1991 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1993 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1997 fstat(con
->file
, &filestats
);
2002 if (filestats
.st_size
> MaxRequestSize
&&
2006 * Request is too big; remove it and send an error...
2009 unlink(con
->filename
);
2010 cupsdClearString(&con
->filename
);
2015 * Delete any IPP request data...
2018 ippDelete(con
->request
);
2019 con
->request
= NULL
;
2022 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2024 cupsdCloseClient(con
);
2028 else if (filestats
.st_size
== 0)
2031 * Don't allow empty file...
2034 unlink(con
->filename
);
2035 cupsdClearString(&con
->filename
);
2040 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2042 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2044 cupsdCloseClient(con
);
2049 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2055 cupsdProcessIPPRequest(con
);
2059 unlink(con
->filename
);
2060 cupsdClearString(&con
->filename
);
2069 break; /* Anti-compiler-warning-code */
2072 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2074 if (!httpGetKeepAlive(con
->http
))
2076 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2077 "Closing because Keep-Alive is disabled.");
2078 cupsdCloseClient(con
);
2082 cupsArrayRemove(ActiveClients
, con
);
2083 cupsdSetBusyState(0);
2090 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2093 int /* O - 1 on success, 0 on failure */
2095 cupsd_client_t
*con
, /* I - Client connection */
2096 char *command
, /* I - Command to run */
2097 char *options
, /* I - Command-line options */
2098 int root
) /* I - Run as root? */
2100 int fd
; /* Standard input file descriptor */
2105 fd
= open(con
->filename
, O_RDONLY
);
2109 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2110 "Unable to open \"%s\" for reading: %s",
2111 con
->filename
? con
->filename
: "/dev/null",
2116 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2121 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2122 con
->pipe_status
= HTTP_STATUS_OK
;
2124 httpClearFields(con
->http
);
2129 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2130 command
, con
->pipe_pid
, con
->file
);
2132 if (con
->pipe_pid
== 0)
2135 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2137 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2139 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2141 con
->sent_header
= 0;
2142 con
->file_ready
= 0;
2143 con
->got_fields
= 0;
2144 con
->header_used
= 0;
2151 * 'cupsdSendError()' - Send an error message via HTTP.
2154 int /* O - 1 if successful, 0 otherwise */
2155 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2156 http_status_t code
, /* I - Error code */
2157 int auth_type
)/* I - Authentication type */
2159 char location
[HTTP_MAX_VALUE
]; /* Location field */
2162 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
2166 * Force client to upgrade for authentication if that is how the
2167 * server is configured...
2170 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2171 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2172 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2173 !httpIsEncrypted(con
->http
))
2175 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2177 #endif /* HAVE_SSL */
2180 * Put the request in the access_log file...
2183 cupsdLogRequest(con
, code
);
2186 * To work around bugs in some proxies, don't use Keep-Alive for some
2189 * Kerberos authentication doesn't work without Keep-Alive, so
2190 * never disable it in that case.
2193 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
2195 httpClearFields(con
->http
);
2197 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
2199 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2200 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2202 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2203 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2204 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2206 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2209 * Send a human-readable error message.
2212 char message
[4096], /* Message for user */
2213 urltext
[1024], /* URL redirection text */
2214 redirect
[1024]; /* Redirection link */
2215 const char *text
; /* Status-specific text */
2220 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2221 text
= _cupsLangString(con
->language
,
2222 _("Enter your username and password or the "
2223 "root username and password to access this "
2224 "page. If you are using Kerberos authentication, "
2225 "make sure you have a valid Kerberos ticket."));
2226 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2230 snprintf(urltext
, sizeof(urltext
),
2231 _cupsLangString(con
->language
,
2232 _("You must access this page using the URL "
2233 "<A HREF=\"https://%s:%d%s\">"
2234 "https://%s:%d%s</A>.")),
2235 con
->servername
, con
->serverport
, con
->uri
,
2236 con
->servername
, con
->serverport
, con
->uri
);
2238 snprintf(redirect
, sizeof(redirect
),
2239 "<META HTTP-EQUIV=\"Refresh\" "
2240 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2241 con
->servername
, con
->serverport
, con
->uri
);
2243 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2244 text
= _cupsLangString(con
->language
,
2245 _("The web interface is currently disabled. Run "
2246 "\"cupsctl WebInterface=yes\" to enable it."));
2250 snprintf(message
, sizeof(message
),
2251 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2252 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2255 "\t<META HTTP-EQUIV=\"Content-Type\" "
2256 "CONTENT=\"text/html; charset=utf-8\">\n"
2257 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2258 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2259 "HREF=\"/cups.css\">\n"
2267 _httpStatus(con
->language
, code
), redirect
,
2268 _httpStatus(con
->language
, code
), text
);
2271 * Send an error message back to the client. If the error code is a
2272 * 400 or 500 series, make sure the message contains some text, too!
2275 size_t length
= strlen(message
); /* Length of message */
2277 httpSetLength(con
->http
, length
);
2279 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2282 if (httpWrite2(con
->http
, message
, length
) < 0)
2285 if (httpFlushWrite(con
->http
) < 0)
2290 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2292 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2301 * 'cupsdSendHeader()' - Send an HTTP request.
2304 int /* O - 1 on success, 0 on failure */
2306 cupsd_client_t
*con
, /* I - Client to send to */
2307 http_status_t code
, /* I - HTTP status code */
2308 char *type
, /* I - MIME type of document */
2309 int auth_type
) /* I - Type of authentication */
2311 char auth_str
[1024]; /* Authorization string */
2314 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2317 * Send the HTTP status header...
2320 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2323 * Treat our special "web interface is disabled" status as "200 OK" for web
2327 code
= HTTP_STATUS_OK
;
2331 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2333 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2334 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2336 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2338 if (auth_type
== CUPSD_AUTH_NONE
)
2340 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2341 auth_type
= cupsdDefaultAuthType();
2343 auth_type
= con
->best
->type
;
2348 if (auth_type
== CUPSD_AUTH_BASIC
)
2349 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2350 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2353 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2354 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2356 #endif /* AF_LOCAL */
2357 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2360 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2361 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2364 * Add a "trc" (try root certification) parameter for local non-Kerberos
2365 * requests when the request requires system group membership - then the
2366 * client knows the root certificate can/should be used.
2368 * Also, for macOS we also look for @AUTHKEY and add an "AuthRef key=foo"
2369 * method as needed...
2372 char *name
, /* Current user name */
2373 *auth_key
; /* Auth key buffer */
2374 size_t auth_size
; /* Size of remaining buffer */
2375 int need_local
= 1; /* Do we need to list "Local" method? */
2377 auth_key
= auth_str
+ strlen(auth_str
);
2378 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2380 #if defined(SO_PEERCRED) && defined(AF_LOCAL)
2381 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2383 strlcpy(auth_key
, ", PeerCred", auth_size
);
2387 #endif /* SO_PEERCRED && AF_LOCAL */
2389 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2391 name
= (char *)cupsArrayNext(con
->best
->names
))
2393 #ifdef HAVE_AUTHORIZATION_H
2394 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2396 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\"", name
+ 9);
2398 /* end parenthesis is stripped in conf.c */
2402 #endif /* HAVE_AUTHORIZATION_H */
2403 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2405 #ifdef HAVE_AUTHORIZATION_H
2406 if (SystemGroupAuthKey
)
2407 snprintf(auth_key
, auth_size
, ", AuthRef key=\"%s\"", SystemGroupAuthKey
);
2410 strlcpy(auth_key
, ", Local trc=\"y\"", auth_size
);
2411 #endif /* HAVE_AUTHORIZATION_H */
2418 strlcpy(auth_key
, ", Local", auth_size
);
2423 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2425 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2429 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2430 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2434 if (!strcmp(type
, "text/html"))
2435 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2437 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2440 return (!httpWriteResponse(con
->http
, code
));
2445 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2449 cupsdUpdateCGI(void)
2451 char *ptr
, /* Pointer to end of line in buffer */
2452 message
[1024]; /* Pointer to message text */
2453 int loglevel
; /* Log level for message */
2456 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2457 message
, sizeof(message
))) != NULL
)
2459 if (loglevel
== CUPSD_LOG_INFO
)
2460 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2462 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2466 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2469 * Fatal error on pipe - should never happen!
2472 cupsdLogMessage(CUPSD_LOG_CRIT
,
2473 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2480 * 'cupsdWriteClient()' - Write data to a client as needed.
2484 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2486 int bytes
, /* Number of bytes written */
2487 field_col
; /* Current column */
2488 char *bufptr
, /* Pointer into buffer */
2489 *bufend
; /* Pointer to end of buffer */
2490 ipp_state_t ipp_state
; /* IPP state value */
2493 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2494 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2499 "data_encoding=HTTP_ENCODING_%s, "
2500 "data_remaining=" CUPS_LLFMT
", "
2504 httpError(con
->http
), (int)httpGetReady(con
->http
),
2505 httpStateString(httpGetState(con
->http
)),
2506 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2507 CUPS_LLCAST
httpGetLength2(con
->http
),
2509 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2510 con
->pipe_pid
, con
->file
);
2512 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2513 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2516 * If we get called in the wrong state, then something went wrong with the
2517 * connection and we need to shut it down...
2520 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2521 httpStateString(httpGetState(con
->http
)));
2522 cupsdCloseClient(con
);
2529 * Make sure we select on the CGI output...
2532 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2534 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2536 if (!con
->file_ready
)
2539 * Try again later when there is CGI output available...
2542 cupsdRemoveSelect(httpGetFd(con
->http
));
2546 con
->file_ready
= 0;
2549 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2551 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2554 * Limit GET bytes to original size of file (STR #3265)...
2557 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2560 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2562 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2567 * Write a single attribute or the IPP message header...
2570 ipp_state
= ippWrite(con
->http
, con
->response
);
2573 * If the write buffer has been flushed, stop buffering up attributes...
2576 if (httpGetPending(con
->http
) <= wused
)
2579 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2581 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2582 "Writing IPP response, ipp_state=%s, old "
2583 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2584 ippStateString(ipp_state
),
2585 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2587 if (httpGetPending(con
->http
) > 0)
2588 httpFlushWrite(con
->http
);
2590 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2591 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2593 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2594 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2595 (int)bytes
, httpGetState(con
->http
),
2596 CUPS_LLCAST
httpGetLength2(con
->http
));
2598 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2600 con
->header_used
+= bytes
;
2602 if (con
->pipe_pid
&& !con
->got_fields
)
2605 * Inspect the data for Content-Type and other fields.
2608 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2610 !con
->got_fields
&& bufptr
< bufend
;
2613 if (*bufptr
== '\n')
2616 * Send line to client...
2619 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2623 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2625 if (!con
->sent_header
)
2628 * Handle redirection and CGI status codes...
2631 http_field_t field
; /* HTTP field */
2632 char *value
= strchr(con
->header
, ':');
2633 /* Value of field */
2638 while (isspace(*value
& 255))
2642 field
= httpFieldValue(con
->header
);
2644 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2646 httpSetField(con
->http
, field
, value
);
2648 if (field
== HTTP_FIELD_LOCATION
)
2650 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2651 con
->sent_header
= 2;
2654 con
->sent_header
= 1;
2656 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2658 con
->pipe_status
= (http_status_t
)atoi(value
);
2659 con
->sent_header
= 2;
2661 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2663 httpSetCookie(con
->http
, value
);
2664 con
->sent_header
= 1;
2672 con
->header_used
-= bufptr
- con
->header
;
2674 if (con
->header_used
> 0)
2675 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2677 bufptr
= con
->header
- 1;
2680 * See if the line was empty...
2685 con
->got_fields
= 1;
2687 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2688 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2689 httpSetLength(con
->http
, 0);
2691 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2693 if (con
->pipe_status
== HTTP_STATUS_OK
)
2695 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2697 cupsdCloseClient(con
);
2703 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2705 cupsdCloseClient(con
);
2713 else if (*bufptr
!= '\r')
2717 if (!con
->got_fields
)
2721 if (con
->header_used
> 0)
2723 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2725 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2726 httpError(con
->http
), strerror(httpError(con
->http
)));
2727 cupsdCloseClient(con
);
2731 if (httpIsChunked(con
->http
))
2732 httpFlushWrite(con
->http
);
2734 con
->bytes
+= con
->header_used
;
2736 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2739 bytes
= con
->header_used
;
2741 con
->header_used
= 0;
2746 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2747 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2749 if (!con
->sent_header
&& con
->pipe_pid
)
2750 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2753 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2755 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2757 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2759 if (httpWrite2(con
->http
, "", 0) < 0)
2761 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2762 httpError(con
->http
), strerror(httpError(con
->http
)));
2763 cupsdCloseClient(con
);
2768 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2769 httpFlushWrite(con
->http
);
2770 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2773 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2775 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2779 cupsdRemoveSelect(con
->file
);
2782 cupsdEndProcess(con
->pipe_pid
, 0);
2791 unlink(con
->filename
);
2792 cupsdClearString(&con
->filename
);
2797 ippDelete(con
->request
);
2798 con
->request
= NULL
;
2803 ippDelete(con
->response
);
2804 con
->response
= NULL
;
2807 cupsdClearString(&con
->command
);
2808 cupsdClearString(&con
->options
);
2809 cupsdClearString(&con
->query_string
);
2811 if (!httpGetKeepAlive(con
->http
))
2813 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2814 "Closing because Keep-Alive is disabled.");
2815 cupsdCloseClient(con
);
2820 cupsArrayRemove(ActiveClients
, con
);
2821 cupsdSetBusyState(0);
2828 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2831 static int /* O - 1 if modified since */
2833 cupsd_client_t
*con
, /* I - Client connection */
2834 struct stat
*filestats
) /* I - File information */
2836 const char *ptr
; /* Pointer into field */
2837 time_t date
; /* Time/date value */
2838 off_t size
; /* Size/length value */
2843 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2848 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
);
2850 while (*ptr
!= '\0')
2852 while (isspace(*ptr
) || *ptr
== ';')
2855 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2858 size
= strtoll(ptr
, NULL
, 10);
2860 while (isdigit(*ptr
))
2863 else if (isalpha(*ptr
))
2865 date
= httpGetDateTime(ptr
);
2866 while (*ptr
!= '\0' && *ptr
!= ';')
2873 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2874 (date
< filestats
->st_mtime
&& date
!= 0) ||
2875 (size
== 0 && date
== 0));
2880 * 'compare_clients()' - Compare two client connections.
2883 static int /* O - Result of comparison */
2884 compare_clients(cupsd_client_t
*a
, /* I - First client */
2885 cupsd_client_t
*b
, /* I - Second client */
2886 void *data
) /* I - User data (not used) */
2901 * 'cupsd_start_tls()' - Start encryption on a connection.
2904 static int /* O - 0 on success, -1 on error */
2905 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2906 http_encryption_t e
) /* I - Encryption mode */
2908 if (httpEncryption(con
->http
, e
))
2910 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2911 cupsLastErrorString());
2915 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Connection now encrypted.");
2918 #endif /* HAVE_SSL */
2922 * 'get_file()' - Get a filename and state info.
2925 static char * /* O - Real filename */
2926 get_file(cupsd_client_t
*con
, /* I - Client connection */
2927 struct stat
*filestats
, /* O - File information */
2928 char *filename
, /* IO - Filename buffer */
2929 size_t len
) /* I - Buffer length */
2931 int status
; /* Status of filesystem calls */
2932 char *ptr
; /* Pointer info filename */
2933 size_t plen
; /* Remaining length after pointer */
2934 char language
[7], /* Language subdirectory, if any */
2935 dest
[1024]; /* Destination name */
2936 int perm_check
= 1; /* Do permissions check? */
2940 * Figure out the real filename...
2945 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2947 strlcpy(dest
, con
->uri
+ 5, sizeof(dest
));
2948 ptr
= dest
+ strlen(dest
) - 4;
2950 if (ptr
<= dest
|| strcmp(ptr
, ".ppd"))
2952 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2957 if (!cupsdFindPrinter(dest
))
2959 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2963 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2967 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2969 strlcpy(dest
, con
->uri
+ 7, sizeof(dest
));
2970 ptr
= dest
+ strlen(dest
) - 4;
2972 if (ptr
<= dest
|| strcmp(ptr
, ".png"))
2974 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2979 if (!cupsdFindDest(dest
))
2981 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2985 snprintf(filename
, len
, "%s/%s.png", CacheDir
, dest
);
2986 if (access(filename
, F_OK
) < 0)
2987 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2991 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2992 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2993 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2995 strlcpy(filename
, ConfigurationFile
, len
);
2999 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3001 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3002 strlcpy(filename
, AccessLog
, len
);
3003 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3004 strlcpy(filename
, ErrorLog
, len
);
3005 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3006 strlcpy(filename
, PageLog
, len
);
3012 else if (con
->language
)
3014 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3015 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3018 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3020 if ((ptr
= strchr(filename
, '?')) != NULL
)
3024 * Grab the status for this language; if there isn't a language-specific file
3025 * then fallback to the default one...
3028 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
3029 strncmp(con
->uri
, "/icons/", 7) &&
3030 strncmp(con
->uri
, "/ppd/", 5) &&
3031 strncmp(con
->uri
, "/rss/", 5) &&
3032 strncmp(con
->uri
, "/admin/conf/", 12) &&
3033 strncmp(con
->uri
, "/admin/log/", 11))
3036 * Drop the country code...
3040 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3042 if ((ptr
= strchr(filename
, '?')) != NULL
)
3045 if ((status
= lstat(filename
, filestats
)) != 0)
3048 * Drop the language prefix and try the root directory...
3052 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3054 if ((ptr
= strchr(filename
, '?')) != NULL
)
3057 status
= lstat(filename
, filestats
);
3062 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3065 if (!status
&& S_ISLNK(filestats
->st_mode
))
3067 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3072 * Similarly, if the file/directory does not have world read permissions, do
3073 * not allow access...
3076 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3078 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3083 * If we've found a directory, get the index.html file instead...
3086 if (!status
&& S_ISDIR(filestats
->st_mode
))
3089 * Make sure the URI ends with a slash...
3092 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3093 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3096 * Find the directory index file, trying every language...
3101 if (status
&& language
[0])
3104 * Try a different language subset...
3108 language
[0] = '\0'; /* Strip country code */
3110 language
[0] = '\0'; /* Strip language */
3114 * Look for the index file...
3117 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3119 if ((ptr
= strchr(filename
, '?')) != NULL
)
3122 ptr
= filename
+ strlen(filename
);
3123 plen
= len
- (size_t)(ptr
- filename
);
3125 strlcpy(ptr
, "index.html", plen
);
3126 status
= lstat(filename
, filestats
);
3128 while (status
&& language
[0]);
3131 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3134 if (!status
&& S_ISLNK(filestats
->st_mode
))
3136 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3141 * Similarly, if the file/directory does not have world read permissions, do
3142 * not allow access...
3145 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3147 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3152 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3162 * 'install_cupsd_conf()' - Install a configuration file.
3165 static http_status_t
/* O - Status */
3166 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3168 char filename
[1024]; /* Configuration filename */
3169 cups_file_t
*in
, /* Input file */
3170 *out
; /* Output file */
3171 char buffer
[16384]; /* Copy buffer */
3172 ssize_t bytes
; /* Number of bytes */
3176 * Open the request file...
3179 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3181 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3182 con
->filename
, strerror(errno
));
3187 * Open the new config file...
3190 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3196 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3200 * Copy from the request to the new config file...
3203 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3204 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3206 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3207 "Unable to copy to config file \"%s\": %s",
3208 ConfigurationFile
, strerror(errno
));
3213 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3214 cupsdUnlinkOrRemoveFile(filename
);
3220 * Close the files...
3225 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3229 * Remove the request file...
3232 cupsdUnlinkOrRemoveFile(con
->filename
);
3233 cupsdClearString(&con
->filename
);
3236 * Set the NeedReload flag...
3239 NeedReload
= RELOAD_CUPSD
;
3240 ReloadTime
= time(NULL
);
3243 * Return that the file was created successfully...
3246 return (HTTP_STATUS_CREATED
);
3249 * Common exit for errors...
3254 cupsdUnlinkOrRemoveFile(con
->filename
);
3255 cupsdClearString(&con
->filename
);
3257 return (HTTP_STATUS_SERVER_ERROR
);
3262 * 'is_cgi()' - Is the resource a CGI script/program?
3265 static int /* O - 1 = CGI, 0 = file */
3266 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3267 const char *filename
, /* I - Real filename */
3268 struct stat
*filestats
, /* I - File information */
3269 mime_type_t
*type
) /* I - MIME type */
3271 const char *options
; /* Options on URL */
3275 * Get the options, if any...
3278 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3281 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3285 * Check for known types...
3288 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3290 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");
3294 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3295 (filestats
->st_mode
& 0111))
3298 * "application/x-httpd-cgi" is a CGI script.
3301 cupsdSetString(&con
->command
, filename
);
3304 cupsdSetStringf(&con
->options
, " %s", options
);
3306 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3310 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
->super
, type
->type
);
3316 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3319 static int /* O - 0 if relative, 1 if absolute */
3320 is_path_absolute(const char *path
) /* I - Input path */
3323 * Check for a leading slash...
3330 * Check for "<" or quotes in the path and reject since this is probably
3331 * someone trying to inject HTML...
3334 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3338 * Check for "/.." in the path...
3341 while ((path
= strstr(path
, "/..")) != NULL
)
3343 if (!path
[3] || path
[3] == '/')
3350 * If we haven't found any relative paths, return 1 indicating an
3359 * 'pipe_command()' - Pipe the output of a command to the remote client.
3362 static int /* O - Process ID */
3363 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3364 int infile
, /* I - Standard input for command */
3365 int *outfile
, /* O - Standard output for command */
3366 char *command
, /* I - Command to run */
3367 char *options
, /* I - Options for command */
3368 int root
) /* I - Run as root? */
3370 int i
; /* Looping var */
3371 int pid
; /* Process ID */
3372 char *commptr
, /* Command string pointer */
3373 commch
; /* Command string character */
3374 char *uriptr
; /* URI string pointer */
3375 int fds
[2]; /* Pipe FDs */
3376 int argc
; /* Number of arguments */
3377 int envc
; /* Number of environment variables */
3378 char argbuf
[10240], /* Argument buffer */
3379 *argv
[100], /* Argument strings */
3380 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3381 char auth_type
[256], /* AUTH_TYPE environment variable */
3382 content_length
[1024], /* CONTENT_LENGTH environment variable */
3383 content_type
[1024], /* CONTENT_TYPE environment variable */
3384 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3385 http_referer
[1024], /* HTTP_REFERER environment variable */
3386 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3387 lang
[1024], /* LANG environment variable */
3388 path_info
[1024], /* PATH_INFO environment variable */
3389 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3390 remote_host
[1024], /* REMOTE_HOST environment variable */
3391 remote_user
[1024], /* REMOTE_USER environment variable */
3392 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3393 script_name
[1024], /* SCRIPT_NAME environment variable */
3394 server_name
[1024], /* SERVER_NAME environment variable */
3395 server_port
[1024]; /* SERVER_PORT environment variable */
3396 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3400 * Parse a copy of the options string, which is of the form:
3402 * argument+argument+argument
3403 * ?argument+argument+argument
3404 * param=value¶m=value
3405 * ?param=value¶m=value
3406 * /name?argument+argument+argument
3407 * /name?param=value¶m=value
3409 * If the string contains an "=" character after the initial name,
3410 * then we treat it as a HTTP GET form request and make a copy of
3411 * the remaining string for the environment variable.
3413 * The string is always parsed out as command-line arguments, to
3414 * be consistent with Apache...
3417 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, outfile
, command
, options
? options
: "(null)", root
);
3422 strlcpy(argbuf
, options
, sizeof(argbuf
));
3426 if (argbuf
[0] == '/')
3429 * Found some trailing path information, set PATH_INFO...
3432 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3433 commptr
= argbuf
+ strlen(argbuf
);
3437 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3443 path_info
[0] = '\0';
3445 if (*commptr
== ' ')
3449 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3452 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3459 argv
[argc
++] = commptr
;
3461 for (; *commptr
&& argc
< 99; commptr
++)
3464 * Break arguments whenever we see a + or space...
3467 if (*commptr
== ' ' || *commptr
== '+')
3469 while (*commptr
== ' ' || *commptr
== '+')
3473 * If we don't have a blank string, save it as another argument...
3478 argv
[argc
] = commptr
;
3484 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3485 isxdigit(commptr
[2] & 255))
3488 * Convert the %xx notation to the individual character.
3491 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3492 *commptr
= (char)((commptr
[1] - '0') << 4);
3494 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3496 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3497 *commptr
|= commptr
[2] - '0';
3499 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3501 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3504 * Check for a %00 and break if that is the case...
3516 * Setup the environment variables as needed...
3519 if (con
->username
[0])
3521 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3522 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3524 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3528 auth_type
[0] = '\0';
3530 if (con
->request
&& (attr
= ippFindAttribute(con
->request
, "attributes-natural-language", IPP_TAG_LANGUAGE
)) != NULL
)
3532 cups_lang_t
*language
= cupsLangGet(ippGetString(attr
, 0, NULL
));
3534 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", language
->language
);
3535 cupsLangFree(language
);
3537 else if (con
->language
)
3538 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3540 strlcpy(lang
, "LANG=C", sizeof(lang
));
3542 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3543 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3544 sizeof(remote_addr
) - 12);
3546 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3547 httpGetHostname(con
->http
, NULL
, 0));
3549 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3550 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3553 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3554 DocumentRoot
, script_name
+ 12);
3556 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3558 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3560 char *nameptr
; /* Pointer to ":port" */
3562 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3563 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3564 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3565 *nameptr
= '\0'; /* Strip trailing ":port" */
3568 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3571 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3574 envp
[envc
++] = auth_type
;
3576 envp
[envc
++] = lang
;
3577 envp
[envc
++] = "REDIRECT_STATUS=1";
3578 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3579 envp
[envc
++] = server_name
;
3580 envp
[envc
++] = server_port
;
3581 envp
[envc
++] = remote_addr
;
3582 envp
[envc
++] = remote_host
;
3583 envp
[envc
++] = script_name
;
3584 envp
[envc
++] = script_filename
;
3587 envp
[envc
++] = path_info
;
3589 if (con
->username
[0])
3591 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3593 envp
[envc
++] = remote_user
;
3596 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3597 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3598 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3599 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3601 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3603 if (httpGetCookie(con
->http
))
3605 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3606 httpGetCookie(con
->http
));
3607 envp
[envc
++] = http_cookie
;
3610 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3612 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3613 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3614 envp
[envc
++] = http_user_agent
;
3617 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3619 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3620 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3621 envp
[envc
++] = http_referer
;
3624 if (con
->operation
== HTTP_STATE_GET
)
3626 envp
[envc
++] = "REQUEST_METHOD=GET";
3628 if (con
->query_string
)
3631 * Add GET form variables after ?...
3634 envp
[envc
++] = con
->query_string
;
3637 envp
[envc
++] = "QUERY_STRING=";
3641 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3642 CUPS_LLCAST con
->bytes
);
3643 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3644 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3646 envp
[envc
++] = "REQUEST_METHOD=POST";
3647 envp
[envc
++] = content_length
;
3648 envp
[envc
++] = content_type
;
3652 * Tell the CGI if we are using encryption...
3655 if (httpIsEncrypted(con
->http
))
3656 envp
[envc
++] = "HTTPS=ON";
3659 * Terminate the environment array...
3664 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3666 for (i
= 0; i
< argc
; i
++)
3667 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3668 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3669 for (i
= 0; i
< envc
; i
++)
3670 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3671 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3675 * Create a pipe for the output...
3678 if (cupsdOpenPipe(fds
))
3680 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3681 argv
[0], strerror(errno
));
3686 * Then execute the command...
3689 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3690 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3693 * Error - can't fork!
3696 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3699 cupsdClosePipe(fds
);
3705 * Fork successful - return the PID...
3708 if (con
->username
[0])
3709 cupsdAddCert(pid
, con
->username
, con
->type
);
3711 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3722 * 'valid_host()' - Is the Host: field valid?
3725 static int /* O - 1 if valid, 0 if not */
3726 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3728 cupsd_alias_t
*a
; /* Current alias */
3729 cupsd_netif_t
*netif
; /* Current network interface */
3730 const char *end
; /* End character */
3731 char *ptr
; /* Pointer into host value */
3735 * Copy the Host: header for later use...
3738 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3739 sizeof(con
->clientname
));
3740 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3743 con
->clientport
= atoi(ptr
);
3746 con
->clientport
= con
->serverport
;
3752 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3755 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3756 * addresses when accessing CUPS via the loopback interface...
3759 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3760 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3761 !strcmp(con
->clientname
, "127.0.0.1") ||
3762 !strcmp(con
->clientname
, "[::1]"));
3765 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3767 * Check if the hostname is something.local (Bonjour); if so, allow it.
3770 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3774 * "." on end, work back to second-to-last "."...
3777 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3780 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3781 !_cups_strcasecmp(end
, ".local.")))
3783 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3786 * Check if the hostname is an IP address...
3789 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3792 * Possible IPv4/IPv6 address...
3795 http_addrlist_t
*addrlist
; /* List of addresses */
3798 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3801 * Good IPv4/IPv6 address...
3804 httpAddrFreeList(addrlist
);
3810 * Check for (alias) name matches...
3813 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3815 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3818 * "ServerAlias *" allows all host values through...
3821 if (!strcmp(a
->name
, "*"))
3824 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3827 * Prefix matches; check the character at the end - it must be "." or nul.
3830 end
= con
->clientname
+ a
->namelen
;
3832 if (!*end
|| (*end
== '.' && !end
[1]))
3837 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3838 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3840 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3843 * "ServerAlias *" allows all host values through...
3846 if (!strcmp(a
->name
, "*"))
3849 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3852 * Prefix matches; check the character at the end - it must be "." or nul.
3855 end
= con
->clientname
+ a
->namelen
;
3857 if (!*end
|| (*end
== '.' && !end
[1]))
3861 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3864 * Check for interface hostname matches...
3867 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3869 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3871 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3874 * Prefix matches; check the character at the end - it must be "." or nul.
3877 end
= con
->clientname
+ netif
->hostlen
;
3879 if (!*end
|| (*end
== '.' && !end
[1]))
3889 * 'write_file()' - Send a file via HTTP.
3892 static int /* O - 0 on failure, 1 on success */
3893 write_file(cupsd_client_t
*con
, /* I - Client connection */
3894 http_status_t code
, /* I - HTTP status */
3895 char *filename
, /* I - Filename */
3896 char *type
, /* I - File type */
3897 struct stat
*filestats
) /* O - File information */
3899 con
->file
= open(filename
, O_RDONLY
);
3901 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3906 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3909 con
->sent_header
= 1;
3911 httpClearFields(con
->http
);
3913 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
3915 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3916 httpGetDateString(filestats
->st_mtime
));
3918 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3921 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3923 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3930 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3934 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3936 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
3938 con
->file_ready
= 1;
3940 cupsdRemoveSelect(con
->file
);
3941 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3943 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");