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
);
1160 if ((!strncmp(con
->uri
, "/admin", 6) && strcmp(con
->uri
, "/admin/conf/cupsd.conf") && strncmp(con
->uri
, "/admin/log/", 11)) ||
1161 !strncmp(con
->uri
, "/printers", 9) ||
1162 !strncmp(con
->uri
, "/classes", 8) ||
1163 !strncmp(con
->uri
, "/help", 5) ||
1164 !strncmp(con
->uri
, "/jobs", 5))
1169 * Web interface is disabled. Show an appropriate message...
1172 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1174 cupsdCloseClient(con
);
1182 * Send CGI output...
1185 if (!strncmp(con
->uri
, "/admin", 6))
1187 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1190 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1192 else if (!strncmp(con
->uri
, "/printers", 9))
1194 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1197 if (con
->uri
[9] && con
->uri
[10])
1198 cupsdSetString(&con
->options
, con
->uri
+ 9);
1200 cupsdSetString(&con
->options
, NULL
);
1202 else if (!strncmp(con
->uri
, "/classes", 8))
1204 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1207 if (con
->uri
[8] && con
->uri
[9])
1208 cupsdSetString(&con
->options
, con
->uri
+ 8);
1210 cupsdSetString(&con
->options
, NULL
);
1212 else if (!strncmp(con
->uri
, "/jobs", 5))
1214 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1217 if (con
->uri
[5] && con
->uri
[6])
1218 cupsdSetString(&con
->options
, con
->uri
+ 5);
1220 cupsdSetString(&con
->options
, NULL
);
1224 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1227 if (con
->uri
[5] && con
->uri
[6])
1228 cupsdSetString(&con
->options
, con
->uri
+ 5);
1230 cupsdSetString(&con
->options
, NULL
);
1233 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1235 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1237 cupsdCloseClient(con
);
1242 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1244 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1245 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1247 else if (!strncmp(con
->uri
, "/admin/log/", 11) && (strchr(con
->uri
+ 11, '/') || strlen(con
->uri
) == 11))
1250 * GET can only be done to configuration files directly under
1254 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Request for subdirectory \"%s\".", con
->uri
);
1256 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1258 cupsdCloseClient(con
);
1270 if ((filename
= get_file(con
, &filestats
, buf
,
1271 sizeof(buf
))) == NULL
)
1273 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1275 cupsdCloseClient(con
);
1282 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1284 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1286 if (is_cgi(con
, filename
, &filestats
, type
))
1289 * Note: con->command and con->options were set by
1293 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1295 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1297 cupsdCloseClient(con
);
1302 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1304 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1305 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1309 if (!check_if_modified(con
, &filestats
))
1311 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1313 cupsdCloseClient(con
);
1320 strlcpy(line
, "text/plain", sizeof(line
));
1322 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1324 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1326 cupsdCloseClient(con
);
1333 case HTTP_STATE_POST_RECV
:
1335 * See if the POST request includes a Content-Length field, and if
1336 * so check the length against any limits that are set...
1339 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1340 MaxRequestSize
> 0 &&
1341 httpGetLength2(con
->http
) > MaxRequestSize
)
1344 * Request too large...
1347 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1349 cupsdCloseClient(con
);
1355 else if (httpGetLength2(con
->http
) < 0)
1358 * Negative content lengths are invalid!
1361 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1363 cupsdCloseClient(con
);
1371 * See what kind of POST request this is; for IPP requests the
1372 * content-type field will be "application/ipp"...
1375 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1377 con
->request
= ippNew();
1378 else if (!WebInterface
)
1381 * Web interface is disabled. Show an appropriate message...
1384 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1386 cupsdCloseClient(con
);
1392 else if ((!strncmp(con
->uri
, "/admin", 6) && strncmp(con
->uri
, "/admin/log/", 11)) ||
1393 !strncmp(con
->uri
, "/printers", 9) ||
1394 !strncmp(con
->uri
, "/classes", 8) ||
1395 !strncmp(con
->uri
, "/help", 5) ||
1396 !strncmp(con
->uri
, "/jobs", 5))
1402 if (!strncmp(con
->uri
, "/admin", 6))
1404 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1407 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1409 else if (!strncmp(con
->uri
, "/printers", 9))
1411 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1414 if (con
->uri
[9] && con
->uri
[10])
1415 cupsdSetString(&con
->options
, con
->uri
+ 9);
1417 cupsdSetString(&con
->options
, NULL
);
1419 else if (!strncmp(con
->uri
, "/classes", 8))
1421 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1424 if (con
->uri
[8] && con
->uri
[9])
1425 cupsdSetString(&con
->options
, con
->uri
+ 8);
1427 cupsdSetString(&con
->options
, NULL
);
1429 else if (!strncmp(con
->uri
, "/jobs", 5))
1431 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1434 if (con
->uri
[5] && con
->uri
[6])
1435 cupsdSetString(&con
->options
, con
->uri
+ 5);
1437 cupsdSetString(&con
->options
, NULL
);
1441 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1444 if (con
->uri
[5] && con
->uri
[6])
1445 cupsdSetString(&con
->options
, con
->uri
+ 5);
1447 cupsdSetString(&con
->options
, NULL
);
1450 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1451 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1459 if ((filename
= get_file(con
, &filestats
, buf
,
1460 sizeof(buf
))) == NULL
)
1462 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1464 cupsdCloseClient(con
);
1471 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1473 if (!is_cgi(con
, filename
, &filestats
, type
))
1476 * Only POST to CGI's...
1479 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1481 cupsdCloseClient(con
);
1488 case HTTP_STATE_PUT_RECV
:
1490 * Validate the resource name...
1493 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1496 * PUT can only be done to the cupsd.conf file...
1499 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1500 "Disallowed PUT request for \"%s\".", con
->uri
);
1502 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1504 cupsdCloseClient(con
);
1512 * See if the PUT request includes a Content-Length field, and if
1513 * so check the length against any limits that are set...
1516 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1517 MaxRequestSize
> 0 &&
1518 httpGetLength2(con
->http
) > MaxRequestSize
)
1521 * Request too large...
1524 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1526 cupsdCloseClient(con
);
1532 else if (httpGetLength2(con
->http
) < 0)
1535 * Negative content lengths are invalid!
1538 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1540 cupsdCloseClient(con
);
1548 * Open a temporary file to hold the request...
1551 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1553 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1557 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1558 "Unable to create request file \"%s\": %s",
1559 con
->filename
, strerror(errno
));
1561 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1563 cupsdCloseClient(con
);
1568 fchmod(con
->file
, 0640);
1569 fchown(con
->file
, RunUser
, Group
);
1570 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1573 case HTTP_STATE_DELETE
:
1574 case HTTP_STATE_TRACE
:
1575 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1576 cupsdCloseClient(con
);
1579 case HTTP_STATE_HEAD
:
1580 if (!strncmp(con
->uri
, "/printers/", 10) &&
1581 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1584 * Send PPD file - get the real printer name since printer
1585 * names are not case sensitive but filenames can be...
1588 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1590 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1591 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1594 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1596 cupsdCloseClient(con
);
1600 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1604 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1605 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1608 * Send PNG file - get the real printer name since printer
1609 * names are not case sensitive but filenames can be...
1612 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1614 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1615 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1618 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1620 cupsdCloseClient(con
);
1624 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1628 else if (!WebInterface
)
1630 httpClearFields(con
->http
);
1632 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1634 cupsdCloseClient(con
);
1638 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1642 if ((!strncmp(con
->uri
, "/admin", 6) && strcmp(con
->uri
, "/admin/conf/cupsd.conf") && strncmp(con
->uri
, "/admin/log/", 11)) ||
1643 !strncmp(con
->uri
, "/printers", 9) ||
1644 !strncmp(con
->uri
, "/classes", 8) ||
1645 !strncmp(con
->uri
, "/help", 5) ||
1646 !strncmp(con
->uri
, "/jobs", 5))
1652 httpClearFields(con
->http
);
1654 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1656 cupsdCloseClient(con
);
1660 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1662 else if (!strncmp(con
->uri
, "/admin/log/", 11) && (strchr(con
->uri
+ 11, '/') || strlen(con
->uri
) == 11))
1665 * HEAD can only be done to configuration files under
1669 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1670 "Request for subdirectory \"%s\".", con
->uri
);
1672 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1674 cupsdCloseClient(con
);
1678 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1681 else if ((filename
= get_file(con
, &filestats
, buf
,
1682 sizeof(buf
))) == NULL
)
1684 httpClearFields(con
->http
);
1686 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1689 cupsdCloseClient(con
);
1693 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1695 else if (!check_if_modified(con
, &filestats
))
1697 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1699 cupsdCloseClient(con
);
1703 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1711 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1713 strlcpy(line
, "text/plain", sizeof(line
));
1715 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1717 httpClearFields(con
->http
);
1719 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1720 httpGetDateString(filestats
.st_mtime
));
1721 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1723 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1725 cupsdCloseClient(con
);
1729 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1734 break; /* Anti-compiler-warning-code */
1740 * Handle any incoming data...
1743 switch (httpGetState(con
->http
))
1745 case HTTP_STATE_PUT_RECV
:
1748 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1750 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1751 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1752 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1753 httpError(con
->http
), strerror(httpError(con
->http
)));
1755 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1756 "HTTP_STATE_PUT_RECV Closing on EOF.");
1758 cupsdCloseClient(con
);
1763 con
->bytes
+= bytes
;
1765 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1769 unlink(con
->filename
);
1770 cupsdClearString(&con
->filename
);
1772 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1774 cupsdCloseClient(con
);
1779 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1781 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1782 "Unable to write %d bytes to \"%s\": %s", bytes
,
1783 con
->filename
, strerror(errno
));
1787 unlink(con
->filename
);
1788 cupsdClearString(&con
->filename
);
1790 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1792 cupsdCloseClient(con
);
1797 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1799 cupsdCloseClient(con
);
1803 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1805 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1808 * End of file, see how big it is...
1811 fstat(con
->file
, &filestats
);
1816 if (filestats
.st_size
> MaxRequestSize
&&
1820 * Request is too big; remove it and send an error...
1823 unlink(con
->filename
);
1824 cupsdClearString(&con
->filename
);
1826 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1828 cupsdCloseClient(con
);
1834 * Install the configuration file...
1837 status
= install_cupsd_conf(con
);
1840 * Return the status to the client...
1843 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1845 cupsdCloseClient(con
);
1851 case HTTP_STATE_POST_RECV
:
1854 if (con
->request
&& con
->file
< 0)
1857 * Grab any request data from the connection...
1860 if (!httpWait(con
->http
, 0))
1863 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1865 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1866 cupsLastErrorString());
1868 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1869 cupsdCloseClient(con
);
1872 else if (ipp_state
!= IPP_STATE_DATA
)
1874 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1876 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1877 cupsdCloseClient(con
);
1881 if (httpGetReady(con
->http
))
1887 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1888 con
->request
->request
.op
.version
[0],
1889 con
->request
->request
.op
.version
[1],
1890 ippOpString(con
->request
->request
.op
.operation_id
),
1891 con
->request
->request
.op
.request_id
);
1892 con
->bytes
+= (off_t
)ippLength(con
->request
);
1896 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1899 * Create a file as needed for the request data...
1902 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1904 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1908 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1909 "Unable to create request file \"%s\": %s",
1910 con
->filename
, strerror(errno
));
1912 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1914 cupsdCloseClient(con
);
1919 fchmod(con
->file
, 0640);
1920 fchown(con
->file
, RunUser
, Group
);
1921 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1924 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1926 if (!httpWait(con
->http
, 0))
1928 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1930 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1931 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1932 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1933 httpError(con
->http
), strerror(httpError(con
->http
)));
1935 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1936 "HTTP_STATE_POST_SEND Closing on EOF.");
1938 cupsdCloseClient(con
);
1943 con
->bytes
+= bytes
;
1945 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1949 unlink(con
->filename
);
1950 cupsdClearString(&con
->filename
);
1952 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1954 cupsdCloseClient(con
);
1959 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1961 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1962 "Unable to write %d bytes to \"%s\": %s",
1963 bytes
, con
->filename
, strerror(errno
));
1967 unlink(con
->filename
);
1968 cupsdClearString(&con
->filename
);
1970 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1973 cupsdCloseClient(con
);
1978 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1980 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1982 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1983 "Closing on unexpected state %s.",
1984 httpStateString(httpGetState(con
->http
)));
1985 cupsdCloseClient(con
);
1990 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1992 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1996 fstat(con
->file
, &filestats
);
2001 if (filestats
.st_size
> MaxRequestSize
&&
2005 * Request is too big; remove it and send an error...
2008 unlink(con
->filename
);
2009 cupsdClearString(&con
->filename
);
2014 * Delete any IPP request data...
2017 ippDelete(con
->request
);
2018 con
->request
= NULL
;
2021 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2023 cupsdCloseClient(con
);
2027 else if (filestats
.st_size
== 0)
2030 * Don't allow empty file...
2033 unlink(con
->filename
);
2034 cupsdClearString(&con
->filename
);
2039 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2041 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2043 cupsdCloseClient(con
);
2048 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2054 cupsdProcessIPPRequest(con
);
2058 unlink(con
->filename
);
2059 cupsdClearString(&con
->filename
);
2068 break; /* Anti-compiler-warning-code */
2071 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2073 if (!httpGetKeepAlive(con
->http
))
2075 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2076 "Closing because Keep-Alive is disabled.");
2077 cupsdCloseClient(con
);
2081 cupsArrayRemove(ActiveClients
, con
);
2082 cupsdSetBusyState();
2089 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2092 int /* O - 1 on success, 0 on failure */
2094 cupsd_client_t
*con
, /* I - Client connection */
2095 char *command
, /* I - Command to run */
2096 char *options
, /* I - Command-line options */
2097 int root
) /* I - Run as root? */
2099 int fd
; /* Standard input file descriptor */
2104 fd
= open(con
->filename
, O_RDONLY
);
2108 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2109 "Unable to open \"%s\" for reading: %s",
2110 con
->filename
? con
->filename
: "/dev/null",
2115 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2120 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2121 con
->pipe_status
= HTTP_STATUS_OK
;
2123 httpClearFields(con
->http
);
2128 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2129 command
, con
->pipe_pid
, con
->file
);
2131 if (con
->pipe_pid
== 0)
2134 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2136 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2138 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2140 con
->sent_header
= 0;
2141 con
->file_ready
= 0;
2142 con
->got_fields
= 0;
2143 con
->header_used
= 0;
2150 * 'cupsdSendError()' - Send an error message via HTTP.
2153 int /* O - 1 if successful, 0 otherwise */
2154 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2155 http_status_t code
, /* I - Error code */
2156 int auth_type
)/* I - Authentication type */
2158 char location
[HTTP_MAX_VALUE
]; /* Location field */
2161 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
2165 * Force client to upgrade for authentication if that is how the
2166 * server is configured...
2169 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2170 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2171 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2172 !httpIsEncrypted(con
->http
))
2174 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2176 #endif /* HAVE_SSL */
2179 * Put the request in the access_log file...
2182 cupsdLogRequest(con
, code
);
2185 * To work around bugs in some proxies, don't use Keep-Alive for some
2188 * Kerberos authentication doesn't work without Keep-Alive, so
2189 * never disable it in that case.
2192 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
2194 httpClearFields(con
->http
);
2196 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
2198 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2199 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2201 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2202 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2203 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2205 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2208 * Send a human-readable error message.
2211 char message
[4096], /* Message for user */
2212 urltext
[1024], /* URL redirection text */
2213 redirect
[1024]; /* Redirection link */
2214 const char *text
; /* Status-specific text */
2219 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2220 text
= _cupsLangString(con
->language
,
2221 _("Enter your username and password or the "
2222 "root username and password to access this "
2223 "page. If you are using Kerberos authentication, "
2224 "make sure you have a valid Kerberos ticket."));
2225 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2229 snprintf(urltext
, sizeof(urltext
),
2230 _cupsLangString(con
->language
,
2231 _("You must access this page using the URL "
2232 "<A HREF=\"https://%s:%d%s\">"
2233 "https://%s:%d%s</A>.")),
2234 con
->servername
, con
->serverport
, con
->uri
,
2235 con
->servername
, con
->serverport
, con
->uri
);
2237 snprintf(redirect
, sizeof(redirect
),
2238 "<META HTTP-EQUIV=\"Refresh\" "
2239 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2240 con
->servername
, con
->serverport
, con
->uri
);
2242 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2243 text
= _cupsLangString(con
->language
,
2244 _("The web interface is currently disabled. Run "
2245 "\"cupsctl WebInterface=yes\" to enable it."));
2249 snprintf(message
, sizeof(message
),
2250 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2251 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2254 "\t<META HTTP-EQUIV=\"Content-Type\" "
2255 "CONTENT=\"text/html; charset=utf-8\">\n"
2256 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2257 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2258 "HREF=\"/cups.css\">\n"
2266 _httpStatus(con
->language
, code
), redirect
,
2267 _httpStatus(con
->language
, code
), text
);
2270 * Send an error message back to the client. If the error code is a
2271 * 400 or 500 series, make sure the message contains some text, too!
2274 size_t length
= strlen(message
); /* Length of message */
2276 httpSetLength(con
->http
, length
);
2278 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2281 if (httpWrite2(con
->http
, message
, length
) < 0)
2284 if (httpFlushWrite(con
->http
) < 0)
2289 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2291 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2300 * 'cupsdSendHeader()' - Send an HTTP request.
2303 int /* O - 1 on success, 0 on failure */
2305 cupsd_client_t
*con
, /* I - Client to send to */
2306 http_status_t code
, /* I - HTTP status code */
2307 char *type
, /* I - MIME type of document */
2308 int auth_type
) /* I - Type of authentication */
2310 char auth_str
[1024]; /* Authorization string */
2313 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2316 * Send the HTTP status header...
2319 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2322 * Treat our special "web interface is disabled" status as "200 OK" for web
2326 code
= HTTP_STATUS_OK
;
2330 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2332 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2333 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2335 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2337 if (auth_type
== CUPSD_AUTH_NONE
)
2339 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2340 auth_type
= cupsdDefaultAuthType();
2342 auth_type
= con
->best
->type
;
2347 if (auth_type
== CUPSD_AUTH_BASIC
)
2348 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
));
2359 #endif /* HAVE_GSSAPI */
2361 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2362 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2365 * Add a "trc" (try root certification) parameter for local non-Kerberos
2366 * requests when the request requires system group membership - then the
2367 * client knows the root certificate can/should be used.
2369 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2370 * parameter as needed...
2373 char *name
, /* Current user name */
2374 *auth_key
; /* Auth key buffer */
2375 size_t auth_size
; /* Size of remaining buffer */
2377 auth_key
= auth_str
+ strlen(auth_str
);
2378 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2380 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2382 name
= (char *)cupsArrayNext(con
->best
->names
))
2384 #ifdef HAVE_AUTHORIZATION_H
2385 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2387 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2388 /* end parenthesis is stripped in conf.c */
2392 #endif /* HAVE_AUTHORIZATION_H */
2393 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2395 #ifdef HAVE_AUTHORIZATION_H
2396 if (SystemGroupAuthKey
)
2397 snprintf(auth_key
, auth_size
,
2399 SystemGroupAuthKey
);
2402 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2403 #endif /* HAVE_AUTHORIZATION_H */
2411 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2413 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2417 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2418 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2422 if (!strcmp(type
, "text/html"))
2423 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2425 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2428 return (!httpWriteResponse(con
->http
, code
));
2433 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2437 cupsdUpdateCGI(void)
2439 char *ptr
, /* Pointer to end of line in buffer */
2440 message
[1024]; /* Pointer to message text */
2441 int loglevel
; /* Log level for message */
2444 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2445 message
, sizeof(message
))) != NULL
)
2447 if (loglevel
== CUPSD_LOG_INFO
)
2448 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2450 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2454 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2457 * Fatal error on pipe - should never happen!
2460 cupsdLogMessage(CUPSD_LOG_CRIT
,
2461 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2468 * 'cupsdWriteClient()' - Write data to a client as needed.
2472 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2474 int bytes
, /* Number of bytes written */
2475 field_col
; /* Current column */
2476 char *bufptr
, /* Pointer into buffer */
2477 *bufend
; /* Pointer to end of buffer */
2478 ipp_state_t ipp_state
; /* IPP state value */
2481 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2482 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2487 "data_encoding=HTTP_ENCODING_%s, "
2488 "data_remaining=" CUPS_LLFMT
", "
2492 httpError(con
->http
), (int)httpGetReady(con
->http
),
2493 httpStateString(httpGetState(con
->http
)),
2494 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2495 CUPS_LLCAST
httpGetLength2(con
->http
),
2497 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2498 con
->pipe_pid
, con
->file
);
2500 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2501 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2504 * If we get called in the wrong state, then something went wrong with the
2505 * connection and we need to shut it down...
2508 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2509 httpStateString(httpGetState(con
->http
)));
2510 cupsdCloseClient(con
);
2517 * Make sure we select on the CGI output...
2520 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2522 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2524 if (!con
->file_ready
)
2527 * Try again later when there is CGI output available...
2530 cupsdRemoveSelect(httpGetFd(con
->http
));
2534 con
->file_ready
= 0;
2537 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2539 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2542 * Limit GET bytes to original size of file (STR #3265)...
2545 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2548 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2550 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2555 * Write a single attribute or the IPP message header...
2558 ipp_state
= ippWrite(con
->http
, con
->response
);
2561 * If the write buffer has been flushed, stop buffering up attributes...
2564 if (httpGetPending(con
->http
) <= wused
)
2567 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2569 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2570 "Writing IPP response, ipp_state=%s, old "
2571 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2572 ippStateString(ipp_state
),
2573 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2575 if (httpGetPending(con
->http
) > 0)
2576 httpFlushWrite(con
->http
);
2578 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2579 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2581 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2582 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2583 (int)bytes
, httpGetState(con
->http
),
2584 CUPS_LLCAST
httpGetLength2(con
->http
));
2586 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2588 con
->header_used
+= bytes
;
2590 if (con
->pipe_pid
&& !con
->got_fields
)
2593 * Inspect the data for Content-Type and other fields.
2596 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2598 !con
->got_fields
&& bufptr
< bufend
;
2601 if (*bufptr
== '\n')
2604 * Send line to client...
2607 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2611 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2613 if (!con
->sent_header
)
2616 * Handle redirection and CGI status codes...
2619 http_field_t field
; /* HTTP field */
2620 char *value
= strchr(con
->header
, ':');
2621 /* Value of field */
2626 while (isspace(*value
& 255))
2630 field
= httpFieldValue(con
->header
);
2632 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2634 httpSetField(con
->http
, field
, value
);
2636 if (field
== HTTP_FIELD_LOCATION
)
2638 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2639 con
->sent_header
= 2;
2642 con
->sent_header
= 1;
2644 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2646 con
->pipe_status
= (http_status_t
)atoi(value
);
2647 con
->sent_header
= 2;
2649 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2651 httpSetCookie(con
->http
, value
);
2652 con
->sent_header
= 1;
2660 con
->header_used
-= bufptr
- con
->header
;
2662 if (con
->header_used
> 0)
2663 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2665 bufptr
= con
->header
- 1;
2668 * See if the line was empty...
2673 con
->got_fields
= 1;
2675 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2676 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2677 httpSetLength(con
->http
, 0);
2679 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2681 if (con
->pipe_status
== HTTP_STATUS_OK
)
2683 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2685 cupsdCloseClient(con
);
2691 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2693 cupsdCloseClient(con
);
2701 else if (*bufptr
!= '\r')
2705 if (!con
->got_fields
)
2709 if (con
->header_used
> 0)
2711 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2713 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2714 httpError(con
->http
), strerror(httpError(con
->http
)));
2715 cupsdCloseClient(con
);
2719 if (httpIsChunked(con
->http
))
2720 httpFlushWrite(con
->http
);
2722 con
->bytes
+= con
->header_used
;
2724 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2727 bytes
= con
->header_used
;
2729 con
->header_used
= 0;
2734 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2735 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2737 if (!con
->sent_header
&& con
->pipe_pid
)
2738 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2741 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2743 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2745 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2747 if (httpWrite2(con
->http
, "", 0) < 0)
2749 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2750 httpError(con
->http
), strerror(httpError(con
->http
)));
2751 cupsdCloseClient(con
);
2756 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2757 httpFlushWrite(con
->http
);
2758 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2761 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2763 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2767 cupsdRemoveSelect(con
->file
);
2770 cupsdEndProcess(con
->pipe_pid
, 0);
2779 unlink(con
->filename
);
2780 cupsdClearString(&con
->filename
);
2785 ippDelete(con
->request
);
2786 con
->request
= NULL
;
2791 ippDelete(con
->response
);
2792 con
->response
= NULL
;
2795 cupsdClearString(&con
->command
);
2796 cupsdClearString(&con
->options
);
2797 cupsdClearString(&con
->query_string
);
2799 if (!httpGetKeepAlive(con
->http
))
2801 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2802 "Closing because Keep-Alive is disabled.");
2803 cupsdCloseClient(con
);
2808 cupsArrayRemove(ActiveClients
, con
);
2809 cupsdSetBusyState();
2816 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2819 static int /* O - 1 if modified since */
2821 cupsd_client_t
*con
, /* I - Client connection */
2822 struct stat
*filestats
) /* I - File information */
2824 const char *ptr
; /* Pointer into field */
2825 time_t date
; /* Time/date value */
2826 off_t size
; /* Size/length value */
2831 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2836 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
);
2838 while (*ptr
!= '\0')
2840 while (isspace(*ptr
) || *ptr
== ';')
2843 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2846 size
= strtoll(ptr
, NULL
, 10);
2848 while (isdigit(*ptr
))
2851 else if (isalpha(*ptr
))
2853 date
= httpGetDateTime(ptr
);
2854 while (*ptr
!= '\0' && *ptr
!= ';')
2861 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2862 (date
< filestats
->st_mtime
&& date
!= 0) ||
2863 (size
== 0 && date
== 0));
2868 * 'compare_clients()' - Compare two client connections.
2871 static int /* O - Result of comparison */
2872 compare_clients(cupsd_client_t
*a
, /* I - First client */
2873 cupsd_client_t
*b
, /* I - Second client */
2874 void *data
) /* I - User data (not used) */
2889 * 'cupsd_start_tls()' - Start encryption on a connection.
2892 static int /* O - 0 on success, -1 on error */
2893 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2894 http_encryption_t e
) /* I - Encryption mode */
2896 if (httpEncryption(con
->http
, e
))
2898 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2899 cupsLastErrorString());
2903 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Connection now encrypted.");
2906 #endif /* HAVE_SSL */
2910 * 'get_file()' - Get a filename and state info.
2913 static char * /* O - Real filename */
2914 get_file(cupsd_client_t
*con
, /* I - Client connection */
2915 struct stat
*filestats
, /* O - File information */
2916 char *filename
, /* IO - Filename buffer */
2917 size_t len
) /* I - Buffer length */
2919 int status
; /* Status of filesystem calls */
2920 char *ptr
; /* Pointer info filename */
2921 size_t plen
; /* Remaining length after pointer */
2922 char language
[7], /* Language subdirectory, if any */
2923 dest
[1024]; /* Destination name */
2924 int perm_check
= 1; /* Do permissions check? */
2928 * Figure out the real filename...
2933 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2935 strlcpy(dest
, con
->uri
+ 5, sizeof(dest
));
2936 ptr
= dest
+ strlen(dest
) - 4;
2938 if (ptr
<= dest
|| strcmp(ptr
, ".ppd"))
2940 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2945 if (!cupsdFindPrinter(dest
))
2947 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2951 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2955 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2957 strlcpy(dest
, con
->uri
+ 7, sizeof(dest
));
2958 ptr
= dest
+ strlen(dest
) - 4;
2960 if (ptr
<= dest
|| strcmp(ptr
, ".png"))
2962 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2967 if (!cupsdFindDest(dest
))
2969 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2973 snprintf(filename
, len
, "%s/%s.png", CacheDir
, dest
);
2974 if (access(filename
, F_OK
) < 0)
2975 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2979 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2980 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2981 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2983 strlcpy(filename
, ConfigurationFile
, len
);
2987 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2989 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2990 strlcpy(filename
, AccessLog
, len
);
2991 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2992 strlcpy(filename
, ErrorLog
, len
);
2993 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2994 strlcpy(filename
, PageLog
, len
);
3000 else if (con
->language
)
3002 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3003 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3006 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3008 if ((ptr
= strchr(filename
, '?')) != NULL
)
3012 * Grab the status for this language; if there isn't a language-specific file
3013 * then fallback to the default one...
3016 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
3017 strncmp(con
->uri
, "/icons/", 7) &&
3018 strncmp(con
->uri
, "/ppd/", 5) &&
3019 strncmp(con
->uri
, "/rss/", 5) &&
3020 strncmp(con
->uri
, "/admin/conf/", 12) &&
3021 strncmp(con
->uri
, "/admin/log/", 11))
3024 * Drop the country code...
3028 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3030 if ((ptr
= strchr(filename
, '?')) != NULL
)
3033 if ((status
= lstat(filename
, filestats
)) != 0)
3036 * Drop the language prefix and try the root directory...
3040 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3042 if ((ptr
= strchr(filename
, '?')) != NULL
)
3045 status
= lstat(filename
, filestats
);
3050 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3053 if (!status
&& S_ISLNK(filestats
->st_mode
))
3055 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3060 * Similarly, if the file/directory does not have world read permissions, do
3061 * not allow access...
3064 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3066 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3071 * If we've found a directory, get the index.html file instead...
3074 if (!status
&& S_ISDIR(filestats
->st_mode
))
3077 * Make sure the URI ends with a slash...
3080 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3081 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3084 * Find the directory index file, trying every language...
3089 if (status
&& language
[0])
3092 * Try a different language subset...
3096 language
[0] = '\0'; /* Strip country code */
3098 language
[0] = '\0'; /* Strip language */
3102 * Look for the index file...
3105 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3107 if ((ptr
= strchr(filename
, '?')) != NULL
)
3110 ptr
= filename
+ strlen(filename
);
3111 plen
= len
- (size_t)(ptr
- filename
);
3113 strlcpy(ptr
, "index.html", plen
);
3114 status
= lstat(filename
, filestats
);
3119 strlcpy(ptr
, "index.class", plen
);
3120 status
= lstat(filename
, filestats
);
3122 #endif /* HAVE_JAVA */
3127 strlcpy(ptr
, "index.pl", plen
);
3128 status
= lstat(filename
, filestats
);
3130 #endif /* HAVE_PERL */
3135 strlcpy(ptr
, "index.php", plen
);
3136 status
= lstat(filename
, filestats
);
3138 #endif /* HAVE_PHP */
3143 strlcpy(ptr
, "index.pyc", plen
);
3144 status
= lstat(filename
, filestats
);
3149 strlcpy(ptr
, "index.py", plen
);
3150 status
= lstat(filename
, filestats
);
3152 #endif /* HAVE_PYTHON */
3155 while (status
&& language
[0]);
3158 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3161 if (!status
&& S_ISLNK(filestats
->st_mode
))
3163 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3168 * Similarly, if the file/directory does not have world read permissions, do
3169 * not allow access...
3172 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3174 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3179 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3189 * 'install_cupsd_conf()' - Install a configuration file.
3192 static http_status_t
/* O - Status */
3193 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3195 char filename
[1024]; /* Configuration filename */
3196 cups_file_t
*in
, /* Input file */
3197 *out
; /* Output file */
3198 char buffer
[16384]; /* Copy buffer */
3199 ssize_t bytes
; /* Number of bytes */
3203 * Open the request file...
3206 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3208 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3209 con
->filename
, strerror(errno
));
3214 * Open the new config file...
3217 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3223 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3227 * Copy from the request to the new config file...
3230 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3231 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3233 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3234 "Unable to copy to config file \"%s\": %s",
3235 ConfigurationFile
, strerror(errno
));
3240 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3241 cupsdUnlinkOrRemoveFile(filename
);
3247 * Close the files...
3252 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3256 * Remove the request file...
3259 cupsdUnlinkOrRemoveFile(con
->filename
);
3260 cupsdClearString(&con
->filename
);
3263 * Set the NeedReload flag...
3266 NeedReload
= RELOAD_CUPSD
;
3267 ReloadTime
= time(NULL
);
3270 * Return that the file was created successfully...
3273 return (HTTP_STATUS_CREATED
);
3276 * Common exit for errors...
3281 cupsdUnlinkOrRemoveFile(con
->filename
);
3282 cupsdClearString(&con
->filename
);
3284 return (HTTP_STATUS_SERVER_ERROR
);
3289 * 'is_cgi()' - Is the resource a CGI script/program?
3292 static int /* O - 1 = CGI, 0 = file */
3293 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3294 const char *filename
, /* I - Real filename */
3295 struct stat
*filestats
, /* I - File information */
3296 mime_type_t
*type
) /* I - MIME type */
3298 const char *options
; /* Options on URL */
3302 * Get the options, if any...
3305 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3308 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3312 * Check for known types...
3315 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3317 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");
3321 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3322 (filestats
->st_mode
& 0111))
3325 * "application/x-httpd-cgi" is a CGI script.
3328 cupsdSetString(&con
->command
, filename
);
3331 cupsdSetStringf(&con
->options
, " %s", options
);
3333 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3337 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3340 * "application/x-httpd-java" is a Java servlet.
3343 cupsdSetString(&con
->command
, CUPS_JAVA
);
3346 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3348 cupsdSetStringf(&con
->options
, " %s", filename
);
3350 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3353 #endif /* HAVE_JAVA */
3355 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3358 * "application/x-httpd-perl" is a Perl page.
3361 cupsdSetString(&con
->command
, CUPS_PERL
);
3364 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3366 cupsdSetStringf(&con
->options
, " %s", filename
);
3368 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3371 #endif /* HAVE_PERL */
3373 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3376 * "application/x-httpd-php" is a PHP page.
3379 cupsdSetString(&con
->command
, CUPS_PHP
);
3382 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3384 cupsdSetStringf(&con
->options
, " %s", filename
);
3386 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3389 #endif /* HAVE_PHP */
3391 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3394 * "application/x-httpd-python" is a Python page.
3397 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3400 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3402 cupsdSetStringf(&con
->options
, " %s", filename
);
3404 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3407 #endif /* HAVE_PYTHON */
3409 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
->super
, type
->type
);
3415 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3418 static int /* O - 0 if relative, 1 if absolute */
3419 is_path_absolute(const char *path
) /* I - Input path */
3422 * Check for a leading slash...
3429 * Check for "<" or quotes in the path and reject since this is probably
3430 * someone trying to inject HTML...
3433 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3437 * Check for "/.." in the path...
3440 while ((path
= strstr(path
, "/..")) != NULL
)
3442 if (!path
[3] || path
[3] == '/')
3449 * If we haven't found any relative paths, return 1 indicating an
3458 * 'pipe_command()' - Pipe the output of a command to the remote client.
3461 static int /* O - Process ID */
3462 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3463 int infile
, /* I - Standard input for command */
3464 int *outfile
, /* O - Standard output for command */
3465 char *command
, /* I - Command to run */
3466 char *options
, /* I - Options for command */
3467 int root
) /* I - Run as root? */
3469 int i
; /* Looping var */
3470 int pid
; /* Process ID */
3471 char *commptr
, /* Command string pointer */
3472 commch
; /* Command string character */
3473 char *uriptr
; /* URI string pointer */
3474 int fds
[2]; /* Pipe FDs */
3475 int argc
; /* Number of arguments */
3476 int envc
; /* Number of environment variables */
3477 char argbuf
[10240], /* Argument buffer */
3478 *argv
[100], /* Argument strings */
3479 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3480 char auth_type
[256], /* AUTH_TYPE environment variable */
3481 content_length
[1024], /* CONTENT_LENGTH environment variable */
3482 content_type
[1024], /* CONTENT_TYPE environment variable */
3483 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3484 http_referer
[1024], /* HTTP_REFERER environment variable */
3485 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3486 lang
[1024], /* LANG environment variable */
3487 path_info
[1024], /* PATH_INFO environment variable */
3488 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3489 remote_host
[1024], /* REMOTE_HOST environment variable */
3490 remote_user
[1024], /* REMOTE_USER environment variable */
3491 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3492 script_name
[1024], /* SCRIPT_NAME environment variable */
3493 server_name
[1024], /* SERVER_NAME environment variable */
3494 server_port
[1024]; /* SERVER_PORT environment variable */
3495 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3499 * Parse a copy of the options string, which is of the form:
3501 * argument+argument+argument
3502 * ?argument+argument+argument
3503 * param=value¶m=value
3504 * ?param=value¶m=value
3505 * /name?argument+argument+argument
3506 * /name?param=value¶m=value
3508 * If the string contains an "=" character after the initial name,
3509 * then we treat it as a HTTP GET form request and make a copy of
3510 * the remaining string for the environment variable.
3512 * The string is always parsed out as command-line arguments, to
3513 * be consistent with Apache...
3516 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, outfile
, command
, options
? options
: "(null)", root
);
3521 strlcpy(argbuf
, options
, sizeof(argbuf
));
3525 if (argbuf
[0] == '/')
3528 * Found some trailing path information, set PATH_INFO...
3531 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3532 commptr
= argbuf
+ strlen(argbuf
);
3536 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3542 path_info
[0] = '\0';
3544 if (*commptr
== ' ')
3548 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3551 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3558 argv
[argc
++] = commptr
;
3560 for (; *commptr
&& argc
< 99; commptr
++)
3563 * Break arguments whenever we see a + or space...
3566 if (*commptr
== ' ' || *commptr
== '+')
3568 while (*commptr
== ' ' || *commptr
== '+')
3572 * If we don't have a blank string, save it as another argument...
3577 argv
[argc
] = commptr
;
3583 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3584 isxdigit(commptr
[2] & 255))
3587 * Convert the %xx notation to the individual character.
3590 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3591 *commptr
= (char)((commptr
[1] - '0') << 4);
3593 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3595 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3596 *commptr
|= commptr
[2] - '0';
3598 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3600 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3603 * Check for a %00 and break if that is the case...
3615 * Setup the environment variables as needed...
3618 if (con
->username
[0])
3620 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3621 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3623 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3627 auth_type
[0] = '\0';
3630 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3631 IPP_TAG_LANGUAGE
)) != NULL
)
3633 switch (strlen(attr
->values
[0].string
.text
))
3637 * This is an unknown or badly formatted language code; use
3638 * the POSIX locale...
3641 strlcpy(lang
, "LANG=C", sizeof(lang
));
3646 * Just the language code (ll)...
3649 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3650 attr
->values
[0].string
.text
);
3655 * Language and country code (ll-cc)...
3658 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3659 attr
->values
[0].string
.text
[0],
3660 attr
->values
[0].string
.text
[1],
3661 toupper(attr
->values
[0].string
.text
[3] & 255),
3662 toupper(attr
->values
[0].string
.text
[4] & 255));
3666 else if (con
->language
)
3667 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3669 strlcpy(lang
, "LANG=C", sizeof(lang
));
3671 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3672 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3673 sizeof(remote_addr
) - 12);
3675 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3676 httpGetHostname(con
->http
, NULL
, 0));
3678 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3679 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3682 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3683 DocumentRoot
, script_name
+ 12);
3685 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3687 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3689 char *nameptr
; /* Pointer to ":port" */
3691 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3692 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3693 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3694 *nameptr
= '\0'; /* Strip trailing ":port" */
3697 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3700 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3703 envp
[envc
++] = auth_type
;
3705 envp
[envc
++] = lang
;
3706 envp
[envc
++] = "REDIRECT_STATUS=1";
3707 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3708 envp
[envc
++] = server_name
;
3709 envp
[envc
++] = server_port
;
3710 envp
[envc
++] = remote_addr
;
3711 envp
[envc
++] = remote_host
;
3712 envp
[envc
++] = script_name
;
3713 envp
[envc
++] = script_filename
;
3716 envp
[envc
++] = path_info
;
3718 if (con
->username
[0])
3720 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3722 envp
[envc
++] = remote_user
;
3725 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3726 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3727 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3728 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3730 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3732 if (httpGetCookie(con
->http
))
3734 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3735 httpGetCookie(con
->http
));
3736 envp
[envc
++] = http_cookie
;
3739 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3741 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3742 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3743 envp
[envc
++] = http_user_agent
;
3746 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3748 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3749 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3750 envp
[envc
++] = http_referer
;
3753 if (con
->operation
== HTTP_STATE_GET
)
3755 envp
[envc
++] = "REQUEST_METHOD=GET";
3757 if (con
->query_string
)
3760 * Add GET form variables after ?...
3763 envp
[envc
++] = con
->query_string
;
3766 envp
[envc
++] = "QUERY_STRING=";
3770 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3771 CUPS_LLCAST con
->bytes
);
3772 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3773 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3775 envp
[envc
++] = "REQUEST_METHOD=POST";
3776 envp
[envc
++] = content_length
;
3777 envp
[envc
++] = content_type
;
3781 * Tell the CGI if we are using encryption...
3784 if (httpIsEncrypted(con
->http
))
3785 envp
[envc
++] = "HTTPS=ON";
3788 * Terminate the environment array...
3793 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3795 for (i
= 0; i
< argc
; i
++)
3796 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3797 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3798 for (i
= 0; i
< envc
; i
++)
3799 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3800 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3804 * Create a pipe for the output...
3807 if (cupsdOpenPipe(fds
))
3809 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3810 argv
[0], strerror(errno
));
3815 * Then execute the command...
3818 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3819 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3822 * Error - can't fork!
3825 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3828 cupsdClosePipe(fds
);
3834 * Fork successful - return the PID...
3837 if (con
->username
[0])
3838 cupsdAddCert(pid
, con
->username
, con
->type
);
3840 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3851 * 'valid_host()' - Is the Host: field valid?
3854 static int /* O - 1 if valid, 0 if not */
3855 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3857 cupsd_alias_t
*a
; /* Current alias */
3858 cupsd_netif_t
*netif
; /* Current network interface */
3859 const char *end
; /* End character */
3860 char *ptr
; /* Pointer into host value */
3864 * Copy the Host: header for later use...
3867 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3868 sizeof(con
->clientname
));
3869 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3872 con
->clientport
= atoi(ptr
);
3875 con
->clientport
= con
->serverport
;
3881 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3884 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3885 * addresses when accessing CUPS via the loopback interface...
3888 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3889 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3891 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3892 #endif /* __linux */
3893 !strcmp(con
->clientname
, "127.0.0.1") ||
3894 !strcmp(con
->clientname
, "[::1]"));
3897 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3899 * Check if the hostname is something.local (Bonjour); if so, allow it.
3902 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3906 * "." on end, work back to second-to-last "."...
3909 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3912 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3913 !_cups_strcasecmp(end
, ".local.")))
3915 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3918 * Check if the hostname is an IP address...
3921 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3924 * Possible IPv4/IPv6 address...
3927 http_addrlist_t
*addrlist
; /* List of addresses */
3930 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3933 * Good IPv4/IPv6 address...
3936 httpAddrFreeList(addrlist
);
3942 * Check for (alias) name matches...
3945 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3947 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3950 * "ServerAlias *" allows all host values through...
3953 if (!strcmp(a
->name
, "*"))
3956 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3959 * Prefix matches; check the character at the end - it must be "." or nul.
3962 end
= con
->clientname
+ a
->namelen
;
3964 if (!*end
|| (*end
== '.' && !end
[1]))
3969 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3970 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3972 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3975 * "ServerAlias *" allows all host values through...
3978 if (!strcmp(a
->name
, "*"))
3981 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3984 * Prefix matches; check the character at the end - it must be "." or nul.
3987 end
= con
->clientname
+ a
->namelen
;
3989 if (!*end
|| (*end
== '.' && !end
[1]))
3993 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3996 * Check for interface hostname matches...
3999 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4001 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4003 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4006 * Prefix matches; check the character at the end - it must be "." or nul.
4009 end
= con
->clientname
+ netif
->hostlen
;
4011 if (!*end
|| (*end
== '.' && !end
[1]))
4021 * 'write_file()' - Send a file via HTTP.
4024 static int /* O - 0 on failure, 1 on success */
4025 write_file(cupsd_client_t
*con
, /* I - Client connection */
4026 http_status_t code
, /* I - HTTP status */
4027 char *filename
, /* I - Filename */
4028 char *type
, /* I - File type */
4029 struct stat
*filestats
) /* O - File information */
4031 con
->file
= open(filename
, O_RDONLY
);
4033 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4038 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4041 con
->sent_header
= 1;
4043 httpClearFields(con
->http
);
4045 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
4047 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
4048 httpGetDateString(filestats
->st_mtime
));
4050 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4053 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4055 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4062 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4066 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4068 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
4070 con
->file_ready
= 1;
4072 cupsdRemoveSelect(con
->file
);
4073 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4075 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");