4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2015 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * Include necessary headers...
23 #define _CUPS_NO_DEPRECATED
24 #define _HTTP_NO_PRIVATE
29 #endif /* __APPLE__ */
32 #endif /* HAVE_TCPD_H */
39 static int check_if_modified(cupsd_client_t
*con
,
40 struct stat
*filestats
);
41 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
44 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
46 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
47 char *filename
, size_t len
);
48 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
49 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
50 struct stat
*filestats
, mime_type_t
*type
);
51 static int is_path_absolute(const char *path
);
52 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
53 char *command
, char *options
, int root
);
54 static int valid_host(cupsd_client_t
*con
);
55 static int write_file(cupsd_client_t
*con
, http_status_t code
,
56 char *filename
, char *type
,
57 struct stat
*filestats
);
58 static void write_pipe(cupsd_client_t
*con
);
62 * 'cupsdAcceptClient()' - Accept a new client.
66 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
68 const char *hostname
; /* Hostname of client */
69 char name
[256]; /* Hostname of client */
70 int count
; /* Count of connections on a host */
71 cupsd_client_t
*con
, /* New client pointer */
72 *tempcon
; /* Temporary client pointer */
73 socklen_t addrlen
; /* Length of address */
74 http_addr_t temp
; /* Temporary address variable */
75 static time_t last_dos
= 0; /* Time of last DoS attack */
77 struct request_info wrap_req
; /* TCP wrappers request information */
78 #endif /* HAVE_TCPD_H */
81 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis
, lis
->fd
, cupsArrayCount(Clients
));
84 * Make sure we don't have a full set of clients already...
87 if (cupsArrayCount(Clients
) == MaxClients
)
91 * Get a pointer to the next available client...
95 Clients
= cupsArrayNew(NULL
, NULL
);
99 cupsdLogMessage(CUPSD_LOG_ERROR
,
100 "Unable to allocate memory for clients array!");
101 cupsdPauseListening();
106 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
110 cupsdLogMessage(CUPSD_LOG_ERROR
,
111 "Unable to allocate memory for active clients array!");
112 cupsdPauseListening();
116 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
118 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
119 cupsdPauseListening();
124 * Accept the client and get the remote address...
127 con
->number
= ++ LastClientNumber
;
130 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
132 if (errno
== ENFILE
|| errno
== EMFILE
)
133 cupsdPauseListening();
135 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
143 * Save the connected address and port number...
146 con
->clientaddr
= lis
->address
;
149 * Check the number of clients on the same address...
152 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
154 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
155 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
158 if (count
>= MaxClientsPerHost
)
162 if (count
>= MaxClientsPerHost
)
164 if ((time(NULL
) - last_dos
) >= 60)
166 last_dos
= time(NULL
);
167 cupsdLogMessage(CUPSD_LOG_WARN
,
168 "Possible DoS attack - more than %d clients connecting "
171 httpGetHostname(con
->http
, name
, sizeof(name
)));
174 httpClose(con
->http
);
180 * Get the hostname or format the IP address as needed...
184 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
186 hostname
= httpGetHostname(con
->http
, NULL
, 0);
188 if (hostname
== NULL
&& HostNameLookups
== 2)
191 * Can't have an unresolved IP address with double-lookups enabled...
194 httpClose(con
->http
);
196 cupsdLogClient(con
, CUPSD_LOG_WARN
,
197 "Name lookup failed - connection from %s closed!",
198 httpGetHostname(con
->http
, NULL
, 0));
204 if (HostNameLookups
== 2)
207 * Do double lookups as needed...
210 http_addrlist_t
*addrlist
, /* List of addresses */
211 *addr
; /* Current address */
213 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
216 * See if the hostname maps to the same IP address...
219 for (addr
= addrlist
; addr
; addr
= addr
->next
)
220 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
226 httpAddrFreeList(addrlist
);
231 * Can't have a hostname that doesn't resolve to the same IP address
232 * with double-lookups enabled...
235 httpClose(con
->http
);
237 cupsdLogClient(con
, CUPSD_LOG_WARN
,
238 "IP lookup failed - connection from %s closed!",
239 httpGetHostname(con
->http
, NULL
, 0));
247 * See if the connection is denied by TCP wrappers...
250 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
254 if (!hosts_access(&wrap_req
))
256 httpClose(con
->http
);
258 cupsdLogClient(con
, CUPSD_LOG_WARN
,
259 "Connection from %s refused by /etc/hosts.allow and "
260 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
264 #endif /* HAVE_TCPD_H */
267 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
270 socklen_t peersize
; /* Size of peer credentials */
271 pid_t peerpid
; /* Peer process ID */
272 char peername
[256]; /* Name of process */
274 peersize
= sizeof(peerpid
);
275 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
278 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
279 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
280 "Accepted from %s (Domain ???[%d])",
281 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
283 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
284 "Accepted from %s (Domain %s[%d])",
285 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
288 # endif /* __APPLE__ */
290 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
291 httpGetHostname(con
->http
, NULL
, 0));
294 #endif /* AF_LOCAL */
295 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
296 httpGetHostname(con
->http
, NULL
, 0),
297 httpAddrPort(httpGetAddress(con
->http
)),
298 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
301 * Get the local address the client connected to...
304 addrlen
= sizeof(temp
);
305 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
307 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
310 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
311 con
->serverport
= LocalPort
;
314 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
316 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
317 con
->serverport
= LocalPort
;
319 #endif /* AF_LOCAL */
322 if (httpAddrLocalhost(&temp
))
323 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
324 else if (HostNameLookups
)
325 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
327 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
329 con
->serverport
= httpAddrPort(&(lis
->address
));
333 * Add the connection to the array of active clients...
336 cupsArrayAdd(Clients
, con
);
339 * Add the socket to the server select.
342 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
345 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
348 * Temporarily suspend accept()'s until we lose a client...
351 if (cupsArrayCount(Clients
) == MaxClients
)
352 cupsdPauseListening();
356 * See if we are connecting on a secure port...
359 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
362 * https connection; go secure...
365 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
366 cupsdCloseClient(con
);
370 #endif /* HAVE_SSL */
375 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
379 cupsdCloseAllClients(void)
381 cupsd_client_t
*con
; /* Current client */
384 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients
));
386 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
388 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
389 if (cupsdCloseClient(con
))
390 cupsdCloseClient(con
);
395 * 'cupsdCloseClient()' - Close a remote client.
398 int /* O - 1 if partial close, 0 if fully closed */
399 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
401 int partial
; /* Do partial close for SSL? */
404 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
407 * Flush pending writes before closing...
410 httpFlushWrite(con
->http
);
414 if (con
->pipe_pid
!= 0)
417 * Stop any CGI process...
420 cupsdEndProcess(con
->pipe_pid
, 1);
426 cupsdRemoveSelect(con
->file
);
433 * Close the socket and clear the file from the input set for select()...
436 if (httpGetFd(con
->http
) >= 0)
438 cupsArrayRemove(ActiveClients
, con
);
443 * Shutdown encryption as needed...
446 if (httpIsEncrypted(con
->http
))
448 #endif /* HAVE_SSL */
453 * Only do a partial close so that the encrypted client gets everything.
456 httpShutdown(con
->http
);
457 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
460 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
465 * Shut the socket down fully...
468 cupsdRemoveSelect(httpGetFd(con
->http
));
469 httpClose(con
->http
);
480 cupsdRemoveSelect(httpGetFd(con
->http
));
482 httpClose(con
->http
);
486 unlink(con
->filename
);
487 cupsdClearString(&con
->filename
);
490 cupsdClearString(&con
->command
);
491 cupsdClearString(&con
->options
);
492 cupsdClearString(&con
->query_string
);
496 ippDelete(con
->request
);
502 ippDelete(con
->response
);
503 con
->response
= NULL
;
508 cupsLangFree(con
->language
);
509 con
->language
= NULL
;
512 #ifdef HAVE_AUTHORIZATION_H
515 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
518 #endif /* HAVE_AUTHORIZATION_H */
521 * Re-enable new client connections if we are going back under the
525 if (cupsArrayCount(Clients
) == MaxClients
)
526 cupsdResumeListening();
529 * Compact the list of clients as necessary...
532 cupsArrayRemove(Clients
, con
);
542 * 'cupsdReadClient()' - Read data from a client.
546 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
548 char line
[32768], /* Line from client... */
549 locale
[64], /* Locale */
550 *ptr
; /* Pointer into strings */
551 http_status_t status
; /* Transfer status */
552 ipp_state_t ipp_state
; /* State of IPP transfer */
553 int bytes
; /* Number of bytes to POST */
554 char *filename
; /* Name of file for GET/HEAD */
555 char buf
[1024]; /* Buffer for real filename */
556 struct stat filestats
; /* File information */
557 mime_type_t
*type
; /* MIME type of file */
558 cupsd_printer_t
*p
; /* Printer */
559 static unsigned request_id
= 0; /* Request ID for temp files */
562 status
= HTTP_STATUS_CONTINUE
;
564 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
);
566 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
567 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
568 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
571 * If we get called in the wrong state, then something went wrong with the
572 * connection and we need to shut it down...
575 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
578 * Connection closed...
581 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
582 cupsdCloseClient(con
);
586 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con
->http
)));
587 cupsdCloseClient(con
);
595 * Automatically check for a SSL/TLS handshake...
600 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
601 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
604 * Encrypt this connection...
607 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf
[0] & 255);
609 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
610 cupsdCloseClient(con
);
615 #endif /* HAVE_SSL */
617 switch (httpGetState(con
->http
))
619 case HTTP_STATE_WAITING
:
621 * See if we've received a request line...
624 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
625 if (con
->operation
== HTTP_STATE_ERROR
||
626 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
627 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
629 if (httpError(con
->http
))
630 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
631 "HTTP_STATE_WAITING Closing for error %d (%s)",
632 httpError(con
->http
), strerror(httpError(con
->http
)));
634 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
635 "HTTP_STATE_WAITING Closing on error: %s",
636 cupsLastErrorString());
638 cupsdCloseClient(con
);
643 * Ignore blank request lines...
646 if (con
->operation
== HTTP_STATE_WAITING
)
650 * Clear other state variables...
657 con
->username
[0] = '\0';
658 con
->password
[0] = '\0';
660 cupsdClearString(&con
->command
);
661 cupsdClearString(&con
->options
);
662 cupsdClearString(&con
->query_string
);
666 ippDelete(con
->request
);
672 ippDelete(con
->response
);
673 con
->response
= NULL
;
678 cupsLangFree(con
->language
);
679 con
->language
= NULL
;
685 #endif /* HAVE_GSSAPI */
688 * Handle full URLs in the request line...
691 if (strcmp(con
->uri
, "*"))
693 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
694 userpass
[HTTP_MAX_URI
], /* Username:password */
695 hostname
[HTTP_MAX_URI
], /* Hostname */
696 resource
[HTTP_MAX_URI
]; /* Resource path */
697 int port
; /* Port number */
700 * Separate the URI into its components...
703 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
704 scheme
, sizeof(scheme
),
705 userpass
, sizeof(userpass
),
706 hostname
, sizeof(hostname
), &port
,
707 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
709 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
711 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
712 cupsdCloseClient(con
);
717 * Only allow URIs with the servername, localhost, or an IP
721 if (strcmp(scheme
, "file") &&
722 _cups_strcasecmp(hostname
, ServerName
) &&
723 _cups_strcasecmp(hostname
, "localhost") &&
724 !cupsArrayFind(ServerAlias
, hostname
) &&
725 !isdigit(hostname
[0]) && hostname
[0] != '[')
728 * Nope, we don't do proxies...
731 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
733 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
734 cupsdCloseClient(con
);
739 * Copy the resource portion back into the URI; both resource and
740 * con->uri are HTTP_MAX_URI bytes in size...
743 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
747 * Process the request...
750 gettimeofday(&(con
->start
), NULL
);
752 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
753 httpStateString(con
->operation
) + 11, con
->uri
,
754 httpGetVersion(con
->http
) / 100,
755 httpGetVersion(con
->http
) % 100);
757 if (!cupsArrayFind(ActiveClients
, con
))
759 cupsArrayAdd(ActiveClients
, con
);
763 case HTTP_STATE_OPTIONS
:
764 case HTTP_STATE_DELETE
:
765 case HTTP_STATE_GET
:
766 case HTTP_STATE_HEAD
:
767 case HTTP_STATE_POST
:
768 case HTTP_STATE_PUT
:
769 case HTTP_STATE_TRACE
:
771 * Parse incoming parameters until the status changes...
774 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
775 if (!httpGetReady(con
->http
))
778 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
780 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
781 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
782 "Closing for error %d (%s) while reading headers.",
783 httpError(con
->http
), strerror(httpError(con
->http
)));
785 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
786 "Closing on EOF while reading headers.");
788 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
789 cupsdCloseClient(con
);
795 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
798 * Connection closed...
801 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
802 cupsdCloseClient(con
);
805 break; /* Anti-compiler-warning-code */
809 * Handle new transfers...
812 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d", status
);
814 if (status
== HTTP_STATUS_OK
)
816 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
819 * Figure out the locale from the Accept-Language and Content-Type
823 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
827 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
831 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
832 "charset=")) != NULL
)
835 * Combine language and charset, and trim any extra params in the
839 snprintf(locale
, sizeof(locale
), "%s.%s",
840 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
842 if ((ptr
= strchr(locale
, ',')) != NULL
)
846 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
847 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
849 con
->language
= cupsLangGet(locale
);
852 con
->language
= cupsLangGet(DefaultLocale
);
856 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
857 "Keep-Alive", 10) && KeepAlive
)
858 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
859 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
861 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
863 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
864 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
867 * HTTP/1.1 and higher require the "Host:" field...
870 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
872 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
873 cupsdCloseClient(con
);
877 else if (!valid_host(con
))
880 * Access to localhost must use "localhost" or the corresponding IPv4
881 * or IPv6 values in the Host: field.
884 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
885 "Request from \"%s\" using invalid Host: field \"%s\".",
886 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
888 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
890 cupsdCloseClient(con
);
894 else if (con
->operation
== HTTP_STATE_OPTIONS
)
897 * Do OPTIONS command...
900 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
902 httpClearFields(con
->http
);
904 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
906 cupsdCloseClient(con
);
911 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
915 * Do encryption stuff...
918 httpClearFields(con
->http
);
920 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
922 cupsdCloseClient(con
);
926 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
928 cupsdCloseClient(con
);
932 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
934 cupsdCloseClient(con
);
937 #endif /* HAVE_SSL */
940 httpClearFields(con
->http
);
941 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
942 "GET, HEAD, OPTIONS, POST, PUT");
943 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
945 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
947 cupsdCloseClient(con
);
951 else if (!is_path_absolute(con
->uri
))
954 * Protect against malicious users!
957 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
958 "Request for non-absolute resource \"%s\".", con
->uri
);
960 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
962 cupsdCloseClient(con
);
968 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
969 "Upgrade") && !httpIsEncrypted(con
->http
))
973 * Do encryption stuff...
976 httpClearFields(con
->http
);
978 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
981 cupsdCloseClient(con
);
985 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
987 cupsdCloseClient(con
);
991 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
993 cupsdCloseClient(con
);
996 #endif /* HAVE_SSL */
999 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1001 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1002 cupsdCloseClient(con
);
1006 if (httpGetExpect(con
->http
) &&
1007 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1009 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1012 * Send 100-continue header...
1015 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1017 cupsdCloseClient(con
);
1024 * Send 417-expectation-failed header...
1027 httpClearFields(con
->http
);
1028 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1030 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1031 cupsdCloseClient(con
);
1036 switch (httpGetState(con
->http
))
1038 case HTTP_STATE_GET_SEND
:
1039 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1041 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1042 !strncmp(con
->uri
, "/printers/", 10) ||
1043 !strncmp(con
->uri
, "/classes/", 9)) &&
1044 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1047 * Send PPD file - get the real printer name since printer
1048 * names are not case sensitive but filenames can be...
1051 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1053 if (!strncmp(con
->uri
, "/ppd/", 5))
1054 p
= cupsdFindPrinter(con
->uri
+ 5);
1055 else if (!strncmp(con
->uri
, "/printers/", 10))
1056 p
= cupsdFindPrinter(con
->uri
+ 10);
1059 p
= cupsdFindClass(con
->uri
+ 9);
1063 int i
; /* Looping var */
1065 for (i
= 0; i
< p
->num_printers
; i
++)
1067 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1069 char ppdname
[1024];/* PPD filename */
1071 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1072 ServerRoot
, p
->printers
[i
]->name
);
1073 if (!access(ppdname
, 0))
1081 if (i
>= p
->num_printers
)
1088 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1092 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1094 cupsdCloseClient(con
);
1101 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1102 !strncmp(con
->uri
, "/printers/", 10) ||
1103 !strncmp(con
->uri
, "/classes/", 9)) &&
1104 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1107 * Send icon file - get the real queue name since queue names are
1108 * not case sensitive but filenames can be...
1111 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1113 if (!strncmp(con
->uri
, "/icons/", 7))
1114 p
= cupsdFindPrinter(con
->uri
+ 7);
1115 else if (!strncmp(con
->uri
, "/printers/", 10))
1116 p
= cupsdFindPrinter(con
->uri
+ 10);
1119 p
= cupsdFindClass(con
->uri
+ 9);
1123 int i
; /* Looping var */
1125 for (i
= 0; i
< p
->num_printers
; i
++)
1127 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1129 char ppdname
[1024];/* PPD filename */
1131 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1132 ServerRoot
, p
->printers
[i
]->name
);
1133 if (!access(ppdname
, 0))
1141 if (i
>= p
->num_printers
)
1147 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1150 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1152 cupsdCloseClient(con
);
1159 else if (!WebInterface
)
1162 * Web interface is disabled. Show an appropriate message...
1165 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1167 cupsdCloseClient(con
);
1174 if ((!strncmp(con
->uri
, "/admin", 6) &&
1175 strncmp(con
->uri
, "/admin/conf/", 12) &&
1176 strncmp(con
->uri
, "/admin/log/", 11)) ||
1177 !strncmp(con
->uri
, "/printers", 9) ||
1178 !strncmp(con
->uri
, "/classes", 8) ||
1179 !strncmp(con
->uri
, "/help", 5) ||
1180 !strncmp(con
->uri
, "/jobs", 5))
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/conf/", 12) &&
1249 (strchr(con
->uri
+ 12, '/') ||
1250 strlen(con
->uri
) == 12)) ||
1251 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1252 (strchr(con
->uri
+ 11, '/') ||
1253 strlen(con
->uri
) == 11)))
1256 * GET can only be done to configuration files directly under
1260 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1261 "Request for subdirectory \"%s\"!", con
->uri
);
1263 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1265 cupsdCloseClient(con
);
1277 if ((filename
= get_file(con
, &filestats
, buf
,
1278 sizeof(buf
))) == NULL
)
1280 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1282 cupsdCloseClient(con
);
1289 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1291 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1293 if (is_cgi(con
, filename
, &filestats
, type
))
1296 * Note: con->command and con->options were set by
1300 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1302 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1304 cupsdCloseClient(con
);
1309 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1311 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1312 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1316 if (!check_if_modified(con
, &filestats
))
1318 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1320 cupsdCloseClient(con
);
1327 strlcpy(line
, "text/plain", sizeof(line
));
1329 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1331 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1333 cupsdCloseClient(con
);
1340 case HTTP_STATE_POST_RECV
:
1342 * See if the POST request includes a Content-Length field, and if
1343 * so check the length against any limits that are set...
1346 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1347 MaxRequestSize
> 0 &&
1348 httpGetLength2(con
->http
) > MaxRequestSize
)
1351 * Request too large...
1354 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1356 cupsdCloseClient(con
);
1362 else if (httpGetLength2(con
->http
) < 0)
1365 * Negative content lengths are invalid!
1368 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1370 cupsdCloseClient(con
);
1378 * See what kind of POST request this is; for IPP requests the
1379 * content-type field will be "application/ipp"...
1382 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1384 con
->request
= ippNew();
1385 else if (!WebInterface
)
1388 * Web interface is disabled. Show an appropriate message...
1391 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1393 cupsdCloseClient(con
);
1399 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1400 strncmp(con
->uri
, "/admin/conf/", 12) &&
1401 strncmp(con
->uri
, "/admin/log/", 11)) ||
1402 !strncmp(con
->uri
, "/printers", 9) ||
1403 !strncmp(con
->uri
, "/classes", 8) ||
1404 !strncmp(con
->uri
, "/help", 5) ||
1405 !strncmp(con
->uri
, "/jobs", 5))
1411 if (!strncmp(con
->uri
, "/admin", 6))
1413 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1416 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1418 else if (!strncmp(con
->uri
, "/printers", 9))
1420 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1423 if (con
->uri
[9] && con
->uri
[10])
1424 cupsdSetString(&con
->options
, con
->uri
+ 9);
1426 cupsdSetString(&con
->options
, NULL
);
1428 else if (!strncmp(con
->uri
, "/classes", 8))
1430 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1433 if (con
->uri
[8] && con
->uri
[9])
1434 cupsdSetString(&con
->options
, con
->uri
+ 8);
1436 cupsdSetString(&con
->options
, NULL
);
1438 else if (!strncmp(con
->uri
, "/jobs", 5))
1440 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1443 if (con
->uri
[5] && con
->uri
[6])
1444 cupsdSetString(&con
->options
, con
->uri
+ 5);
1446 cupsdSetString(&con
->options
, NULL
);
1450 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1453 if (con
->uri
[5] && con
->uri
[6])
1454 cupsdSetString(&con
->options
, con
->uri
+ 5);
1456 cupsdSetString(&con
->options
, NULL
);
1459 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1460 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1468 if ((filename
= get_file(con
, &filestats
, buf
,
1469 sizeof(buf
))) == NULL
)
1471 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1473 cupsdCloseClient(con
);
1480 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1482 if (!is_cgi(con
, filename
, &filestats
, type
))
1485 * Only POST to CGI's...
1488 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1490 cupsdCloseClient(con
);
1497 case HTTP_STATE_PUT_RECV
:
1499 * Validate the resource name...
1502 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1505 * PUT can only be done to the cupsd.conf file...
1508 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1509 "Disallowed PUT request for \"%s\".", con
->uri
);
1511 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1513 cupsdCloseClient(con
);
1521 * See if the PUT request includes a Content-Length field, and if
1522 * so check the length against any limits that are set...
1525 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1526 MaxRequestSize
> 0 &&
1527 httpGetLength2(con
->http
) > MaxRequestSize
)
1530 * Request too large...
1533 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1535 cupsdCloseClient(con
);
1541 else if (httpGetLength2(con
->http
) < 0)
1544 * Negative content lengths are invalid!
1547 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1549 cupsdCloseClient(con
);
1557 * Open a temporary file to hold the request...
1560 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1562 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1566 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1567 "Unable to create request file \"%s\": %s",
1568 con
->filename
, strerror(errno
));
1570 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1572 cupsdCloseClient(con
);
1577 fchmod(con
->file
, 0640);
1578 fchown(con
->file
, RunUser
, Group
);
1579 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1582 case HTTP_STATE_DELETE
:
1583 case HTTP_STATE_TRACE
:
1584 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1585 cupsdCloseClient(con
);
1588 case HTTP_STATE_HEAD
:
1589 if (!strncmp(con
->uri
, "/printers/", 10) &&
1590 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1593 * Send PPD file - get the real printer name since printer
1594 * names are not case sensitive but filenames can be...
1597 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1599 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1600 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1603 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1605 cupsdCloseClient(con
);
1609 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1613 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1614 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1617 * Send PNG file - get the real printer name since printer
1618 * names are not case sensitive but filenames can be...
1621 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1623 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1624 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1627 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1629 cupsdCloseClient(con
);
1633 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1637 else if (!WebInterface
)
1639 httpClearFields(con
->http
);
1641 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1643 cupsdCloseClient(con
);
1647 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1651 if ((!strncmp(con
->uri
, "/admin", 6) &&
1652 strncmp(con
->uri
, "/admin/conf/", 12) &&
1653 strncmp(con
->uri
, "/admin/log/", 11)) ||
1654 !strncmp(con
->uri
, "/printers", 9) ||
1655 !strncmp(con
->uri
, "/classes", 8) ||
1656 !strncmp(con
->uri
, "/help", 5) ||
1657 !strncmp(con
->uri
, "/jobs", 5))
1663 httpClearFields(con
->http
);
1665 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1667 cupsdCloseClient(con
);
1671 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1673 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1674 (strchr(con
->uri
+ 12, '/') ||
1675 strlen(con
->uri
) == 12)) ||
1676 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1677 (strchr(con
->uri
+ 11, '/') ||
1678 strlen(con
->uri
) == 11)))
1681 * HEAD can only be done to configuration files under
1685 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1686 "Request for subdirectory \"%s\".", con
->uri
);
1688 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1690 cupsdCloseClient(con
);
1694 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1697 else if ((filename
= get_file(con
, &filestats
, buf
,
1698 sizeof(buf
))) == NULL
)
1700 httpClearFields(con
->http
);
1702 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1705 cupsdCloseClient(con
);
1709 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1711 else if (!check_if_modified(con
, &filestats
))
1713 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1715 cupsdCloseClient(con
);
1719 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1727 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1729 strlcpy(line
, "text/plain", sizeof(line
));
1731 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1733 httpClearFields(con
->http
);
1735 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1736 httpGetDateString(filestats
.st_mtime
));
1737 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1739 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1741 cupsdCloseClient(con
);
1745 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1750 break; /* Anti-compiler-warning-code */
1756 * Handle any incoming data...
1759 switch (httpGetState(con
->http
))
1761 case HTTP_STATE_PUT_RECV
:
1764 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1766 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1767 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1768 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1769 httpError(con
->http
), strerror(httpError(con
->http
)));
1771 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1772 "HTTP_STATE_PUT_RECV Closing on EOF.");
1774 cupsdCloseClient(con
);
1779 con
->bytes
+= bytes
;
1781 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1785 unlink(con
->filename
);
1786 cupsdClearString(&con
->filename
);
1788 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1790 cupsdCloseClient(con
);
1795 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1797 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1798 "Unable to write %d bytes to \"%s\": %s", bytes
,
1799 con
->filename
, strerror(errno
));
1803 unlink(con
->filename
);
1804 cupsdClearString(&con
->filename
);
1806 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1808 cupsdCloseClient(con
);
1813 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1815 cupsdCloseClient(con
);
1819 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1821 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1824 * End of file, see how big it is...
1827 fstat(con
->file
, &filestats
);
1832 if (filestats
.st_size
> MaxRequestSize
&&
1836 * Request is too big; remove it and send an error...
1839 unlink(con
->filename
);
1840 cupsdClearString(&con
->filename
);
1842 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1844 cupsdCloseClient(con
);
1850 * Install the configuration file...
1853 status
= install_cupsd_conf(con
);
1856 * Return the status to the client...
1859 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1861 cupsdCloseClient(con
);
1867 case HTTP_STATE_POST_RECV
:
1870 if (con
->request
&& con
->file
< 0)
1873 * Grab any request data from the connection...
1876 if (!httpWait(con
->http
, 0))
1879 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1881 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1882 cupsLastErrorString());
1884 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1885 cupsdCloseClient(con
);
1888 else if (ipp_state
!= IPP_STATE_DATA
)
1890 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1892 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1893 cupsdCloseClient(con
);
1897 if (httpGetReady(con
->http
))
1903 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1904 con
->request
->request
.op
.version
[0],
1905 con
->request
->request
.op
.version
[1],
1906 ippOpString(con
->request
->request
.op
.operation_id
),
1907 con
->request
->request
.op
.request_id
);
1908 con
->bytes
+= (off_t
)ippLength(con
->request
);
1912 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1915 * Create a file as needed for the request data...
1918 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1920 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1924 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1925 "Unable to create request file \"%s\": %s",
1926 con
->filename
, strerror(errno
));
1928 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1930 cupsdCloseClient(con
);
1935 fchmod(con
->file
, 0640);
1936 fchown(con
->file
, RunUser
, Group
);
1937 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1940 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1942 if (!httpWait(con
->http
, 0))
1944 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1946 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1947 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1948 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1949 httpError(con
->http
), strerror(httpError(con
->http
)));
1951 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1952 "HTTP_STATE_POST_SEND Closing on EOF.");
1954 cupsdCloseClient(con
);
1959 con
->bytes
+= bytes
;
1961 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1965 unlink(con
->filename
);
1966 cupsdClearString(&con
->filename
);
1968 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1970 cupsdCloseClient(con
);
1975 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1977 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1978 "Unable to write %d bytes to \"%s\": %s",
1979 bytes
, con
->filename
, strerror(errno
));
1983 unlink(con
->filename
);
1984 cupsdClearString(&con
->filename
);
1986 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1989 cupsdCloseClient(con
);
1994 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1996 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1998 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1999 "Closing on unexpected state %s.",
2000 httpStateString(httpGetState(con
->http
)));
2001 cupsdCloseClient(con
);
2006 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
2008 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2012 fstat(con
->file
, &filestats
);
2017 if (filestats
.st_size
> MaxRequestSize
&&
2021 * Request is too big; remove it and send an error...
2024 unlink(con
->filename
);
2025 cupsdClearString(&con
->filename
);
2030 * Delete any IPP request data...
2033 ippDelete(con
->request
);
2034 con
->request
= NULL
;
2037 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2039 cupsdCloseClient(con
);
2043 else if (filestats
.st_size
== 0)
2046 * Don't allow empty file...
2049 unlink(con
->filename
);
2050 cupsdClearString(&con
->filename
);
2055 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2057 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2059 cupsdCloseClient(con
);
2064 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2070 cupsdProcessIPPRequest(con
);
2074 unlink(con
->filename
);
2075 cupsdClearString(&con
->filename
);
2084 break; /* Anti-compiler-warning-code */
2087 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2089 if (!httpGetKeepAlive(con
->http
))
2091 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2092 "Closing because Keep-Alive is disabled.");
2093 cupsdCloseClient(con
);
2097 cupsArrayRemove(ActiveClients
, con
);
2098 cupsdSetBusyState();
2105 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2108 int /* O - 1 on success, 0 on failure */
2110 cupsd_client_t
*con
, /* I - Client connection */
2111 char *command
, /* I - Command to run */
2112 char *options
, /* I - Command-line options */
2113 int root
) /* I - Run as root? */
2115 int fd
; /* Standard input file descriptor */
2120 fd
= open(con
->filename
, O_RDONLY
);
2124 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2125 "Unable to open \"%s\" for reading: %s",
2126 con
->filename
? con
->filename
: "/dev/null",
2131 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2136 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2137 con
->pipe_status
= HTTP_STATUS_OK
;
2139 httpClearFields(con
->http
);
2144 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2145 command
, con
->pipe_pid
, con
->file
);
2147 if (con
->pipe_pid
== 0)
2150 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2152 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2154 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2156 con
->sent_header
= 0;
2157 con
->file_ready
= 0;
2158 con
->got_fields
= 0;
2159 con
->header_used
= 0;
2166 * 'cupsdSendError()' - Send an error message via HTTP.
2169 int /* O - 1 if successful, 0 otherwise */
2170 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2171 http_status_t code
, /* I - Error code */
2172 int auth_type
)/* I - Authentication type */
2174 char location
[HTTP_MAX_VALUE
]; /* Location field */
2177 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
2181 * Force client to upgrade for authentication if that is how the
2182 * server is configured...
2185 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2186 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2187 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2188 !httpIsEncrypted(con
->http
))
2190 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2192 #endif /* HAVE_SSL */
2195 * Put the request in the access_log file...
2198 cupsdLogRequest(con
, code
);
2201 * To work around bugs in some proxies, don't use Keep-Alive for some
2204 * Kerberos authentication doesn't work without Keep-Alive, so
2205 * never disable it in that case.
2208 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
2210 httpClearFields(con
->http
);
2212 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
2214 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2215 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2217 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2218 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2219 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2221 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2224 * Send a human-readable error message.
2227 char message
[4096], /* Message for user */
2228 urltext
[1024], /* URL redirection text */
2229 redirect
[1024]; /* Redirection link */
2230 const char *text
; /* Status-specific text */
2235 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2236 text
= _cupsLangString(con
->language
,
2237 _("Enter your username and password or the "
2238 "root username and password to access this "
2239 "page. If you are using Kerberos authentication, "
2240 "make sure you have a valid Kerberos ticket."));
2241 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2245 snprintf(urltext
, sizeof(urltext
),
2246 _cupsLangString(con
->language
,
2247 _("You must access this page using the URL "
2248 "<A HREF=\"https://%s:%d%s\">"
2249 "https://%s:%d%s</A>.")),
2250 con
->servername
, con
->serverport
, con
->uri
,
2251 con
->servername
, con
->serverport
, con
->uri
);
2253 snprintf(redirect
, sizeof(redirect
),
2254 "<META HTTP-EQUIV=\"Refresh\" "
2255 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2256 con
->servername
, con
->serverport
, con
->uri
);
2258 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2259 text
= _cupsLangString(con
->language
,
2260 _("The web interface is currently disabled. Run "
2261 "\"cupsctl WebInterface=yes\" to enable it."));
2265 snprintf(message
, sizeof(message
),
2266 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2267 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2270 "\t<META HTTP-EQUIV=\"Content-Type\" "
2271 "CONTENT=\"text/html; charset=utf-8\">\n"
2272 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2273 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2274 "HREF=\"/cups.css\">\n"
2282 _httpStatus(con
->language
, code
), redirect
,
2283 _httpStatus(con
->language
, code
), text
);
2286 * Send an error message back to the client. If the error code is a
2287 * 400 or 500 series, make sure the message contains some text, too!
2290 size_t length
= strlen(message
); /* Length of message */
2292 httpSetLength(con
->http
, length
);
2294 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2297 if (httpWrite2(con
->http
, message
, length
) < 0)
2300 if (httpFlushWrite(con
->http
) < 0)
2305 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2307 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2316 * 'cupsdSendHeader()' - Send an HTTP request.
2319 int /* O - 1 on success, 0 on failure */
2321 cupsd_client_t
*con
, /* I - Client to send to */
2322 http_status_t code
, /* I - HTTP status code */
2323 char *type
, /* I - MIME type of document */
2324 int auth_type
) /* I - Type of authentication */
2326 char auth_str
[1024]; /* Authorization string */
2329 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2332 * Send the HTTP status header...
2335 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2338 * Treat our special "web interface is disabled" status as "200 OK" for web
2342 code
= HTTP_STATUS_OK
;
2346 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2348 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2349 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2351 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2353 if (auth_type
== CUPSD_AUTH_NONE
)
2355 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2356 auth_type
= cupsdDefaultAuthType();
2358 auth_type
= con
->best
->type
;
2363 if (auth_type
== CUPSD_AUTH_BASIC
)
2364 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2366 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2369 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2370 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2372 # endif /* AF_LOCAL */
2373 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2375 #endif /* HAVE_GSSAPI */
2377 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2378 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2381 * Add a "trc" (try root certification) parameter for local non-Kerberos
2382 * requests when the request requires system group membership - then the
2383 * client knows the root certificate can/should be used.
2385 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2386 * parameter as needed...
2389 char *name
, /* Current user name */
2390 *auth_key
; /* Auth key buffer */
2391 size_t auth_size
; /* Size of remaining buffer */
2393 auth_key
= auth_str
+ strlen(auth_str
);
2394 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2396 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2398 name
= (char *)cupsArrayNext(con
->best
->names
))
2400 #ifdef HAVE_AUTHORIZATION_H
2401 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2403 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2404 /* end parenthesis is stripped in conf.c */
2408 #endif /* HAVE_AUTHORIZATION_H */
2409 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2411 #ifdef HAVE_AUTHORIZATION_H
2412 if (SystemGroupAuthKey
)
2413 snprintf(auth_key
, auth_size
,
2415 SystemGroupAuthKey
);
2418 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2419 #endif /* HAVE_AUTHORIZATION_H */
2427 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2429 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2433 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2434 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2438 if (!strcmp(type
, "text/html"))
2439 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2441 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2444 return (!httpWriteResponse(con
->http
, code
));
2449 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2453 cupsdUpdateCGI(void)
2455 char *ptr
, /* Pointer to end of line in buffer */
2456 message
[1024]; /* Pointer to message text */
2457 int loglevel
; /* Log level for message */
2460 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2461 message
, sizeof(message
))) != NULL
)
2463 if (loglevel
== CUPSD_LOG_INFO
)
2464 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2466 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2470 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2473 * Fatal error on pipe - should never happen!
2476 cupsdLogMessage(CUPSD_LOG_CRIT
,
2477 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2484 * 'cupsdWriteClient()' - Write data to a client as needed.
2488 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2490 int bytes
, /* Number of bytes written */
2491 field_col
; /* Current column */
2492 char *bufptr
, /* Pointer into buffer */
2493 *bufend
; /* Pointer to end of buffer */
2494 ipp_state_t ipp_state
; /* IPP state value */
2497 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2498 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2503 "data_encoding=HTTP_ENCODING_%s, "
2504 "data_remaining=" CUPS_LLFMT
", "
2508 httpError(con
->http
), (int)httpGetReady(con
->http
),
2509 httpStateString(httpGetState(con
->http
)),
2510 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2511 CUPS_LLCAST
httpGetLength2(con
->http
),
2513 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2514 con
->pipe_pid
, con
->file
);
2516 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2517 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2520 * If we get called in the wrong state, then something went wrong with the
2521 * connection and we need to shut it down...
2524 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2525 httpStateString(httpGetState(con
->http
)));
2526 cupsdCloseClient(con
);
2533 * Make sure we select on the CGI output...
2536 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2538 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2540 if (!con
->file_ready
)
2543 * Try again later when there is CGI output available...
2546 cupsdRemoveSelect(httpGetFd(con
->http
));
2550 con
->file_ready
= 0;
2553 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2555 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2558 * Limit GET bytes to original size of file (STR #3265)...
2561 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2564 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2566 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2571 * Write a single attribute or the IPP message header...
2574 ipp_state
= ippWrite(con
->http
, con
->response
);
2577 * If the write buffer has been flushed, stop buffering up attributes...
2580 if (httpGetPending(con
->http
) <= wused
)
2583 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2585 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2586 "Writing IPP response, ipp_state=%s, old "
2587 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2588 ippStateString(ipp_state
),
2589 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2591 if (httpGetPending(con
->http
) > 0)
2592 httpFlushWrite(con
->http
);
2594 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2595 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2597 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2598 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2599 (int)bytes
, httpGetState(con
->http
),
2600 CUPS_LLCAST
httpGetLength2(con
->http
));
2602 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2604 con
->header_used
+= bytes
;
2606 if (con
->pipe_pid
&& !con
->got_fields
)
2609 * Inspect the data for Content-Type and other fields.
2612 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2614 !con
->got_fields
&& bufptr
< bufend
;
2617 if (*bufptr
== '\n')
2620 * Send line to client...
2623 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2627 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2629 if (!con
->sent_header
)
2632 * Handle redirection and CGI status codes...
2635 http_field_t field
; /* HTTP field */
2636 char *value
= strchr(con
->header
, ':');
2637 /* Value of field */
2642 while (isspace(*value
& 255))
2646 field
= httpFieldValue(con
->header
);
2648 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2650 httpSetField(con
->http
, field
, value
);
2652 if (field
== HTTP_FIELD_LOCATION
)
2654 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2655 con
->sent_header
= 2;
2658 con
->sent_header
= 1;
2660 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2662 con
->pipe_status
= (http_status_t
)atoi(value
);
2663 con
->sent_header
= 2;
2665 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2667 httpSetCookie(con
->http
, value
);
2668 con
->sent_header
= 1;
2676 con
->header_used
-= bufptr
- con
->header
;
2678 if (con
->header_used
> 0)
2679 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2681 bufptr
= con
->header
- 1;
2684 * See if the line was empty...
2689 con
->got_fields
= 1;
2691 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2692 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2693 httpSetLength(con
->http
, 0);
2695 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2697 if (con
->pipe_status
== HTTP_STATUS_OK
)
2699 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2701 cupsdCloseClient(con
);
2707 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2709 cupsdCloseClient(con
);
2717 else if (*bufptr
!= '\r')
2721 if (!con
->got_fields
)
2725 if (con
->header_used
> 0)
2727 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2729 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2730 httpError(con
->http
), strerror(httpError(con
->http
)));
2731 cupsdCloseClient(con
);
2735 if (httpIsChunked(con
->http
))
2736 httpFlushWrite(con
->http
);
2738 con
->bytes
+= con
->header_used
;
2740 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2743 bytes
= con
->header_used
;
2745 con
->header_used
= 0;
2750 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2751 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2753 if (!con
->sent_header
&& con
->pipe_pid
)
2754 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2757 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2759 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2761 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2763 if (httpWrite2(con
->http
, "", 0) < 0)
2765 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2766 httpError(con
->http
), strerror(httpError(con
->http
)));
2767 cupsdCloseClient(con
);
2772 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2773 httpFlushWrite(con
->http
);
2774 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2777 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2779 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2783 cupsdRemoveSelect(con
->file
);
2786 cupsdEndProcess(con
->pipe_pid
, 0);
2795 unlink(con
->filename
);
2796 cupsdClearString(&con
->filename
);
2801 ippDelete(con
->request
);
2802 con
->request
= NULL
;
2807 ippDelete(con
->response
);
2808 con
->response
= NULL
;
2811 cupsdClearString(&con
->command
);
2812 cupsdClearString(&con
->options
);
2813 cupsdClearString(&con
->query_string
);
2815 if (!httpGetKeepAlive(con
->http
))
2817 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2818 "Closing because Keep-Alive is disabled.");
2819 cupsdCloseClient(con
);
2824 cupsArrayRemove(ActiveClients
, con
);
2825 cupsdSetBusyState();
2832 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2835 static int /* O - 1 if modified since */
2837 cupsd_client_t
*con
, /* I - Client connection */
2838 struct stat
*filestats
) /* I - File information */
2840 const char *ptr
; /* Pointer into field */
2841 time_t date
; /* Time/date value */
2842 off_t size
; /* Size/length value */
2847 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2852 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
);
2854 while (*ptr
!= '\0')
2856 while (isspace(*ptr
) || *ptr
== ';')
2859 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2862 size
= strtoll(ptr
, NULL
, 10);
2864 while (isdigit(*ptr
))
2867 else if (isalpha(*ptr
))
2869 date
= httpGetDateTime(ptr
);
2870 while (*ptr
!= '\0' && *ptr
!= ';')
2877 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2878 (date
< filestats
->st_mtime
&& date
!= 0) ||
2879 (size
== 0 && date
== 0));
2884 * 'compare_clients()' - Compare two client connections.
2887 static int /* O - Result of comparison */
2888 compare_clients(cupsd_client_t
*a
, /* I - First client */
2889 cupsd_client_t
*b
, /* I - Second client */
2890 void *data
) /* I - User data (not used) */
2905 * 'cupsd_start_tls()' - Start encryption on a connection.
2908 static int /* O - 0 on success, -1 on error */
2909 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2910 http_encryption_t e
) /* I - Encryption mode */
2912 if (httpEncryption(con
->http
, e
))
2914 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2915 cupsLastErrorString());
2919 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Connection now encrypted.");
2922 #endif /* HAVE_SSL */
2926 * 'get_file()' - Get a filename and state info.
2929 static char * /* O - Real filename */
2930 get_file(cupsd_client_t
*con
, /* I - Client connection */
2931 struct stat
*filestats
, /* O - File information */
2932 char *filename
, /* IO - Filename buffer */
2933 size_t len
) /* I - Buffer length */
2935 int status
; /* Status of filesystem calls */
2936 char *ptr
; /* Pointer info filename */
2937 size_t plen
; /* Remaining length after pointer */
2938 char language
[7], /* Language subdirectory, if any */
2939 dest
[1024]; /* Destination name */
2940 int perm_check
= 1; /* Do permissions check? */
2944 * Figure out the real filename...
2949 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2951 strlcpy(dest
, con
->uri
+ 5, sizeof(dest
));
2952 ptr
= dest
+ strlen(dest
) - 4;
2954 if (ptr
<= dest
|| strcmp(ptr
, ".ppd"))
2956 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2961 if (!cupsdFindPrinter(dest
))
2963 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2967 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2971 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2973 strlcpy(dest
, con
->uri
+ 7, sizeof(dest
));
2974 ptr
= dest
+ strlen(dest
) - 4;
2976 if (ptr
<= dest
|| strcmp(ptr
, ".png"))
2978 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2983 if (!cupsdFindDest(dest
))
2985 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2989 snprintf(filename
, len
, "%s/%s.png", CacheDir
, dest
);
2990 if (access(filename
, F_OK
) < 0)
2991 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2995 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2996 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2997 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2999 strlcpy(filename
, ConfigurationFile
, len
);
3003 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3005 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3006 strlcpy(filename
, AccessLog
, len
);
3007 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3008 strlcpy(filename
, ErrorLog
, len
);
3009 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3010 strlcpy(filename
, PageLog
, len
);
3016 else if (con
->language
)
3018 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3019 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3022 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3024 if ((ptr
= strchr(filename
, '?')) != NULL
)
3028 * Grab the status for this language; if there isn't a language-specific file
3029 * then fallback to the default one...
3032 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
3033 strncmp(con
->uri
, "/icons/", 7) &&
3034 strncmp(con
->uri
, "/ppd/", 5) &&
3035 strncmp(con
->uri
, "/rss/", 5) &&
3036 strncmp(con
->uri
, "/admin/conf/", 12) &&
3037 strncmp(con
->uri
, "/admin/log/", 11))
3040 * Drop the country code...
3044 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3046 if ((ptr
= strchr(filename
, '?')) != NULL
)
3049 if ((status
= lstat(filename
, filestats
)) != 0)
3052 * Drop the language prefix and try the root directory...
3056 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3058 if ((ptr
= strchr(filename
, '?')) != NULL
)
3061 status
= lstat(filename
, filestats
);
3066 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3069 if (!status
&& S_ISLNK(filestats
->st_mode
))
3071 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3076 * Similarly, if the file/directory does not have world read permissions, do
3077 * not allow access...
3080 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3082 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3087 * If we've found a directory, get the index.html file instead...
3090 if (!status
&& S_ISDIR(filestats
->st_mode
))
3093 * Make sure the URI ends with a slash...
3096 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3097 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3100 * Find the directory index file, trying every language...
3105 if (status
&& language
[0])
3108 * Try a different language subset...
3112 language
[0] = '\0'; /* Strip country code */
3114 language
[0] = '\0'; /* Strip language */
3118 * Look for the index file...
3121 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3123 if ((ptr
= strchr(filename
, '?')) != NULL
)
3126 ptr
= filename
+ strlen(filename
);
3127 plen
= len
- (size_t)(ptr
- filename
);
3129 strlcpy(ptr
, "index.html", plen
);
3130 status
= lstat(filename
, filestats
);
3135 strlcpy(ptr
, "index.class", plen
);
3136 status
= lstat(filename
, filestats
);
3138 #endif /* HAVE_JAVA */
3143 strlcpy(ptr
, "index.pl", plen
);
3144 status
= lstat(filename
, filestats
);
3146 #endif /* HAVE_PERL */
3151 strlcpy(ptr
, "index.php", plen
);
3152 status
= lstat(filename
, filestats
);
3154 #endif /* HAVE_PHP */
3159 strlcpy(ptr
, "index.pyc", plen
);
3160 status
= lstat(filename
, filestats
);
3165 strlcpy(ptr
, "index.py", plen
);
3166 status
= lstat(filename
, filestats
);
3168 #endif /* HAVE_PYTHON */
3171 while (status
&& language
[0]);
3174 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3177 if (!status
&& S_ISLNK(filestats
->st_mode
))
3179 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3184 * Similarly, if the file/directory does not have world read permissions, do
3185 * not allow access...
3188 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3190 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3195 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3205 * 'install_cupsd_conf()' - Install a configuration file.
3208 static http_status_t
/* O - Status */
3209 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3211 char filename
[1024]; /* Configuration filename */
3212 cups_file_t
*in
, /* Input file */
3213 *out
; /* Output file */
3214 char buffer
[16384]; /* Copy buffer */
3215 ssize_t bytes
; /* Number of bytes */
3219 * Open the request file...
3222 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3224 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3225 con
->filename
, strerror(errno
));
3230 * Open the new config file...
3233 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3239 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3243 * Copy from the request to the new config file...
3246 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3247 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3249 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3250 "Unable to copy to config file \"%s\": %s",
3251 ConfigurationFile
, strerror(errno
));
3256 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3257 cupsdUnlinkOrRemoveFile(filename
);
3263 * Close the files...
3268 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3272 * Remove the request file...
3275 cupsdUnlinkOrRemoveFile(con
->filename
);
3276 cupsdClearString(&con
->filename
);
3279 * Set the NeedReload flag...
3282 NeedReload
= RELOAD_CUPSD
;
3283 ReloadTime
= time(NULL
);
3286 * Return that the file was created successfully...
3289 return (HTTP_STATUS_CREATED
);
3292 * Common exit for errors...
3297 cupsdUnlinkOrRemoveFile(con
->filename
);
3298 cupsdClearString(&con
->filename
);
3300 return (HTTP_STATUS_SERVER_ERROR
);
3305 * 'is_cgi()' - Is the resource a CGI script/program?
3308 static int /* O - 1 = CGI, 0 = file */
3309 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3310 const char *filename
, /* I - Real filename */
3311 struct stat
*filestats
, /* I - File information */
3312 mime_type_t
*type
) /* I - MIME type */
3314 const char *options
; /* Options on URL */
3318 * Get the options, if any...
3321 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3324 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3328 * Check for known types...
3331 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3333 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");
3337 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3338 (filestats
->st_mode
& 0111))
3341 * "application/x-httpd-cgi" is a CGI script.
3344 cupsdSetString(&con
->command
, filename
);
3347 cupsdSetStringf(&con
->options
, " %s", options
);
3349 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3353 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3356 * "application/x-httpd-java" is a Java servlet.
3359 cupsdSetString(&con
->command
, CUPS_JAVA
);
3362 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3364 cupsdSetStringf(&con
->options
, " %s", filename
);
3366 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3369 #endif /* HAVE_JAVA */
3371 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3374 * "application/x-httpd-perl" is a Perl page.
3377 cupsdSetString(&con
->command
, CUPS_PERL
);
3380 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3382 cupsdSetStringf(&con
->options
, " %s", filename
);
3384 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3387 #endif /* HAVE_PERL */
3389 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3392 * "application/x-httpd-php" is a PHP page.
3395 cupsdSetString(&con
->command
, CUPS_PHP
);
3398 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3400 cupsdSetStringf(&con
->options
, " %s", filename
);
3402 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3405 #endif /* HAVE_PHP */
3407 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3410 * "application/x-httpd-python" is a Python page.
3413 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3416 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3418 cupsdSetStringf(&con
->options
, " %s", filename
);
3420 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3423 #endif /* HAVE_PYTHON */
3425 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
->super
, type
->type
);
3431 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3434 static int /* O - 0 if relative, 1 if absolute */
3435 is_path_absolute(const char *path
) /* I - Input path */
3438 * Check for a leading slash...
3445 * Check for "<" or quotes in the path and reject since this is probably
3446 * someone trying to inject HTML...
3449 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3453 * Check for "/.." in the path...
3456 while ((path
= strstr(path
, "/..")) != NULL
)
3458 if (!path
[3] || path
[3] == '/')
3465 * If we haven't found any relative paths, return 1 indicating an
3474 * 'pipe_command()' - Pipe the output of a command to the remote client.
3477 static int /* O - Process ID */
3478 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3479 int infile
, /* I - Standard input for command */
3480 int *outfile
, /* O - Standard output for command */
3481 char *command
, /* I - Command to run */
3482 char *options
, /* I - Options for command */
3483 int root
) /* I - Run as root? */
3485 int i
; /* Looping var */
3486 int pid
; /* Process ID */
3487 char *commptr
, /* Command string pointer */
3488 commch
; /* Command string character */
3489 char *uriptr
; /* URI string pointer */
3490 int fds
[2]; /* Pipe FDs */
3491 int argc
; /* Number of arguments */
3492 int envc
; /* Number of environment variables */
3493 char argbuf
[10240], /* Argument buffer */
3494 *argv
[100], /* Argument strings */
3495 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3496 char auth_type
[256], /* AUTH_TYPE environment variable */
3497 content_length
[1024], /* CONTENT_LENGTH environment variable */
3498 content_type
[1024], /* CONTENT_TYPE environment variable */
3499 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3500 http_referer
[1024], /* HTTP_REFERER environment variable */
3501 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3502 lang
[1024], /* LANG environment variable */
3503 path_info
[1024], /* PATH_INFO environment variable */
3504 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3505 remote_host
[1024], /* REMOTE_HOST environment variable */
3506 remote_user
[1024], /* REMOTE_USER environment variable */
3507 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3508 script_name
[1024], /* SCRIPT_NAME environment variable */
3509 server_name
[1024], /* SERVER_NAME environment variable */
3510 server_port
[1024]; /* SERVER_PORT environment variable */
3511 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3515 * Parse a copy of the options string, which is of the form:
3517 * argument+argument+argument
3518 * ?argument+argument+argument
3519 * param=value¶m=value
3520 * ?param=value¶m=value
3521 * /name?argument+argument+argument
3522 * /name?param=value¶m=value
3524 * If the string contains an "=" character after the initial name,
3525 * then we treat it as a HTTP GET form request and make a copy of
3526 * the remaining string for the environment variable.
3528 * The string is always parsed out as command-line arguments, to
3529 * be consistent with Apache...
3532 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, outfile
, command
, options
? options
: "(null)", root
);
3537 strlcpy(argbuf
, options
, sizeof(argbuf
));
3541 if (argbuf
[0] == '/')
3544 * Found some trailing path information, set PATH_INFO...
3547 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3548 commptr
= argbuf
+ strlen(argbuf
);
3552 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3558 path_info
[0] = '\0';
3560 if (*commptr
== ' ')
3564 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3567 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3574 argv
[argc
++] = commptr
;
3576 for (; *commptr
&& argc
< 99; commptr
++)
3579 * Break arguments whenever we see a + or space...
3582 if (*commptr
== ' ' || *commptr
== '+')
3584 while (*commptr
== ' ' || *commptr
== '+')
3588 * If we don't have a blank string, save it as another argument...
3593 argv
[argc
] = commptr
;
3599 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3600 isxdigit(commptr
[2] & 255))
3603 * Convert the %xx notation to the individual character.
3606 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3607 *commptr
= (char)((commptr
[1] - '0') << 4);
3609 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3611 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3612 *commptr
|= commptr
[2] - '0';
3614 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3616 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3619 * Check for a %00 and break if that is the case...
3631 * Setup the environment variables as needed...
3634 if (con
->username
[0])
3636 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3637 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3639 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3643 auth_type
[0] = '\0';
3646 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3647 IPP_TAG_LANGUAGE
)) != NULL
)
3649 switch (strlen(attr
->values
[0].string
.text
))
3653 * This is an unknown or badly formatted language code; use
3654 * the POSIX locale...
3657 strlcpy(lang
, "LANG=C", sizeof(lang
));
3662 * Just the language code (ll)...
3665 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3666 attr
->values
[0].string
.text
);
3671 * Language and country code (ll-cc)...
3674 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3675 attr
->values
[0].string
.text
[0],
3676 attr
->values
[0].string
.text
[1],
3677 toupper(attr
->values
[0].string
.text
[3] & 255),
3678 toupper(attr
->values
[0].string
.text
[4] & 255));
3682 else if (con
->language
)
3683 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3685 strlcpy(lang
, "LANG=C", sizeof(lang
));
3687 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3688 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3689 sizeof(remote_addr
) - 12);
3691 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3692 httpGetHostname(con
->http
, NULL
, 0));
3694 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3695 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3698 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3699 DocumentRoot
, script_name
+ 12);
3701 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3703 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3705 char *nameptr
; /* Pointer to ":port" */
3707 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3708 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3709 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3710 *nameptr
= '\0'; /* Strip trailing ":port" */
3713 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3716 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3719 envp
[envc
++] = auth_type
;
3721 envp
[envc
++] = lang
;
3722 envp
[envc
++] = "REDIRECT_STATUS=1";
3723 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3724 envp
[envc
++] = server_name
;
3725 envp
[envc
++] = server_port
;
3726 envp
[envc
++] = remote_addr
;
3727 envp
[envc
++] = remote_host
;
3728 envp
[envc
++] = script_name
;
3729 envp
[envc
++] = script_filename
;
3732 envp
[envc
++] = path_info
;
3734 if (con
->username
[0])
3736 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3738 envp
[envc
++] = remote_user
;
3741 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3742 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3743 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3744 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3746 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3748 if (httpGetCookie(con
->http
))
3750 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3751 httpGetCookie(con
->http
));
3752 envp
[envc
++] = http_cookie
;
3755 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3757 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3758 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3759 envp
[envc
++] = http_user_agent
;
3762 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3764 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3765 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3766 envp
[envc
++] = http_referer
;
3769 if (con
->operation
== HTTP_STATE_GET
)
3771 envp
[envc
++] = "REQUEST_METHOD=GET";
3773 if (con
->query_string
)
3776 * Add GET form variables after ?...
3779 envp
[envc
++] = con
->query_string
;
3782 envp
[envc
++] = "QUERY_STRING=";
3786 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3787 CUPS_LLCAST con
->bytes
);
3788 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3789 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3791 envp
[envc
++] = "REQUEST_METHOD=POST";
3792 envp
[envc
++] = content_length
;
3793 envp
[envc
++] = content_type
;
3797 * Tell the CGI if we are using encryption...
3800 if (httpIsEncrypted(con
->http
))
3801 envp
[envc
++] = "HTTPS=ON";
3804 * Terminate the environment array...
3809 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3811 for (i
= 0; i
< argc
; i
++)
3812 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3813 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3814 for (i
= 0; i
< envc
; i
++)
3815 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3816 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3820 * Create a pipe for the output...
3823 if (cupsdOpenPipe(fds
))
3825 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3826 argv
[0], strerror(errno
));
3831 * Then execute the command...
3834 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3835 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3838 * Error - can't fork!
3841 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3844 cupsdClosePipe(fds
);
3850 * Fork successful - return the PID...
3853 if (con
->username
[0])
3854 cupsdAddCert(pid
, con
->username
, con
->type
);
3856 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3867 * 'valid_host()' - Is the Host: field valid?
3870 static int /* O - 1 if valid, 0 if not */
3871 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3873 cupsd_alias_t
*a
; /* Current alias */
3874 cupsd_netif_t
*netif
; /* Current network interface */
3875 const char *end
; /* End character */
3876 char *ptr
; /* Pointer into host value */
3880 * Copy the Host: header for later use...
3883 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3884 sizeof(con
->clientname
));
3885 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3888 con
->clientport
= atoi(ptr
);
3891 con
->clientport
= con
->serverport
;
3897 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3900 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3901 * addresses when accessing CUPS via the loopback interface...
3904 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3905 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3907 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3908 #endif /* __linux */
3909 !strcmp(con
->clientname
, "127.0.0.1") ||
3910 !strcmp(con
->clientname
, "[::1]"));
3913 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3915 * Check if the hostname is something.local (Bonjour); if so, allow it.
3918 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3922 * "." on end, work back to second-to-last "."...
3925 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3928 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3929 !_cups_strcasecmp(end
, ".local.")))
3931 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3934 * Check if the hostname is an IP address...
3937 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3940 * Possible IPv4/IPv6 address...
3943 http_addrlist_t
*addrlist
; /* List of addresses */
3946 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3949 * Good IPv4/IPv6 address...
3952 httpAddrFreeList(addrlist
);
3958 * Check for (alias) name matches...
3961 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3963 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3966 * "ServerAlias *" allows all host values through...
3969 if (!strcmp(a
->name
, "*"))
3972 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3975 * Prefix matches; check the character at the end - it must be "." or nul.
3978 end
= con
->clientname
+ a
->namelen
;
3980 if (!*end
|| (*end
== '.' && !end
[1]))
3985 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3986 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3988 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3991 * "ServerAlias *" allows all host values through...
3994 if (!strcmp(a
->name
, "*"))
3997 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4000 * Prefix matches; check the character at the end - it must be "." or nul.
4003 end
= con
->clientname
+ a
->namelen
;
4005 if (!*end
|| (*end
== '.' && !end
[1]))
4009 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4012 * Check for interface hostname matches...
4015 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4017 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4019 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4022 * Prefix matches; check the character at the end - it must be "." or nul.
4025 end
= con
->clientname
+ netif
->hostlen
;
4027 if (!*end
|| (*end
== '.' && !end
[1]))
4037 * 'write_file()' - Send a file via HTTP.
4040 static int /* O - 0 on failure, 1 on success */
4041 write_file(cupsd_client_t
*con
, /* I - Client connection */
4042 http_status_t code
, /* I - HTTP status */
4043 char *filename
, /* I - Filename */
4044 char *type
, /* I - File type */
4045 struct stat
*filestats
) /* O - File information */
4047 con
->file
= open(filename
, O_RDONLY
);
4049 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4054 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4057 con
->sent_header
= 1;
4059 httpClearFields(con
->http
);
4061 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
4063 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
4064 httpGetDateString(filestats
->st_mtime
));
4066 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4069 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4071 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4078 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4082 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4084 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
4086 con
->file_ready
= 1;
4088 cupsdRemoveSelect(con
->file
);
4089 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4091 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");