4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2013 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 const char * const ipp_states
[] =
40 { /* IPP state strings */
52 static int check_if_modified(cupsd_client_t
*con
,
53 struct stat
*filestats
);
54 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
56 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
57 char *filename
, int len
);
58 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
59 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
60 struct stat
*filestats
, mime_type_t
*type
);
61 static int is_path_absolute(const char *path
);
62 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
63 char *command
, char *options
, int root
);
64 static int valid_host(cupsd_client_t
*con
);
65 static int write_file(cupsd_client_t
*con
, http_status_t code
,
66 char *filename
, char *type
,
67 struct stat
*filestats
);
68 static void write_pipe(cupsd_client_t
*con
);
72 * 'cupsdAcceptClient()' - Accept a new client.
76 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
78 const char *hostname
; /* Hostname of client */
79 char name
[256]; /* Hostname of client */
80 int count
; /* Count of connections on a host */
81 cupsd_client_t
*con
, /* New client pointer */
82 *tempcon
; /* Temporary client pointer */
83 socklen_t addrlen
; /* Length of address */
84 http_addr_t temp
; /* Temporary address variable */
85 static time_t last_dos
= 0; /* Time of last DoS attack */
87 struct request_info wrap_req
; /* TCP wrappers request information */
88 #endif /* HAVE_TCPD_H */
91 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
92 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
93 lis
, lis
->fd
, cupsArrayCount(Clients
));
96 * Make sure we don't have a full set of clients already...
99 if (cupsArrayCount(Clients
) == MaxClients
)
103 * Get a pointer to the next available client...
107 Clients
= cupsArrayNew(NULL
, NULL
);
111 cupsdLogMessage(CUPSD_LOG_ERROR
,
112 "Unable to allocate memory for clients array!");
113 cupsdPauseListening();
118 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
122 cupsdLogMessage(CUPSD_LOG_ERROR
,
123 "Unable to allocate memory for active clients array!");
124 cupsdPauseListening();
128 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
130 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
131 cupsdPauseListening();
136 * Accept the client and get the remote address...
139 con
->number
= ++ LastClientNumber
;
142 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
144 if (errno
== ENFILE
|| errno
== EMFILE
)
145 cupsdPauseListening();
147 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
155 * Save the connected address and port number...
158 con
->clientaddr
= lis
->address
;
160 #if 0 /* ifdef AF_INET6 */
161 /* FIXME: I don't believe this is recommended any longer, and we specifically
162 * disable IPv4-over-IPv6 when we listen...
165 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
166 * can more easily use...
169 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
170 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
171 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
172 ntohl(httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
173 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
174 #endif /* AF_INET6 */
177 * Check the number of clients on the same address...
180 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
182 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
183 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
186 if (count
>= MaxClientsPerHost
)
190 if (count
>= MaxClientsPerHost
)
192 if ((time(NULL
) - last_dos
) >= 60)
194 last_dos
= time(NULL
);
195 cupsdLogMessage(CUPSD_LOG_WARN
,
196 "Possible DoS attack - more than %d clients connecting "
199 httpGetHostname(con
->http
, name
, sizeof(name
)));
202 httpClose(con
->http
);
208 * Get the hostname or format the IP address as needed...
212 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
214 hostname
= httpGetHostname(con
->http
, NULL
, 0);
216 if (hostname
== NULL
&& HostNameLookups
== 2)
219 * Can't have an unresolved IP address with double-lookups enabled...
222 httpClose(con
->http
);
224 cupsdLogClient(con
, CUPSD_LOG_WARN
,
225 "Name lookup failed - connection from %s closed!",
226 httpGetHostname(con
->http
, NULL
, 0));
232 if (HostNameLookups
== 2)
235 * Do double lookups as needed...
238 http_addrlist_t
*addrlist
, /* List of addresses */
239 *addr
; /* Current address */
241 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
244 * See if the hostname maps to the same IP address...
247 for (addr
= addrlist
; addr
; addr
= addr
->next
)
248 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
254 httpAddrFreeList(addrlist
);
259 * Can't have a hostname that doesn't resolve to the same IP address
260 * with double-lookups enabled...
263 httpClose(con
->http
);
265 cupsdLogClient(con
, CUPSD_LOG_WARN
,
266 "IP lookup failed - connection from %s closed!",
267 httpGetHostname(con
->http
, NULL
, 0));
275 * See if the connection is denied by TCP wrappers...
278 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
282 if (!hosts_access(&wrap_req
))
284 httpClose(con
->http
);
286 cupsdLogClient(con
, CUPSD_LOG_WARN
,
287 "Connection from %s refused by /etc/hosts.allow and "
288 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
292 #endif /* HAVE_TCPD_H */
295 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
298 socklen_t peersize
; /* Size of peer credentials */
299 pid_t peerpid
; /* Peer process ID */
300 char peername
[256]; /* Name of process */
302 peersize
= sizeof(peerpid
);
303 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
306 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
307 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
308 "Accepted from %s (Domain ???[%d])",
309 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
311 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
312 "Accepted from %s (Domain %s[%d])",
313 httpGetHostname(con
->http
, NULL
, 0), name
, (int)peerpid
);
316 # endif /* __APPLE__ */
318 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
319 httpGetHostname(con
->http
, NULL
, 0));
322 #endif /* AF_LOCAL */
323 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
324 httpGetHostname(con
->http
, NULL
, 0),
325 httpAddrPort(httpGetAddress(con
->http
)),
326 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
329 * Get the local address the client connected to...
332 addrlen
= sizeof(temp
);
333 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
335 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
338 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
339 con
->serverport
= LocalPort
;
342 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
344 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
345 con
->serverport
= LocalPort
;
347 #endif /* AF_LOCAL */
350 if (httpAddrLocalhost(&temp
))
351 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
352 else if (HostNameLookups
)
353 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
355 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
357 con
->serverport
= httpAddrPort(&(lis
->address
));
361 * Add the connection to the array of active clients...
364 cupsArrayAdd(Clients
, con
);
367 * Add the socket to the server select.
370 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
373 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
376 * Temporarily suspend accept()'s until we lose a client...
379 if (cupsArrayCount(Clients
) == MaxClients
)
380 cupsdPauseListening();
384 * See if we are connecting on a secure port...
387 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
390 * https connection; go secure...
393 if (!cupsdStartTLS(con
))
394 cupsdCloseClient(con
);
398 #endif /* HAVE_SSL */
403 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
407 cupsdCloseAllClients(void)
409 cupsd_client_t
*con
; /* Current client */
412 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
413 cupsArrayCount(Clients
));
415 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
417 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
418 if (cupsdCloseClient(con
))
419 cupsdCloseClient(con
);
424 * 'cupsdCloseClient()' - Close a remote client.
427 int /* O - 1 if partial close, 0 if fully closed */
428 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
430 int partial
; /* Do partial close for SSL? */
432 #elif defined(HAVE_GNUTLS)
433 # elif defined(HAVE_CDSASSL)
434 #endif /* HAVE_LIBSSL */
437 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
440 * Flush pending writes before closing...
443 httpFlushWrite(con
->http
);
447 if (con
->pipe_pid
!= 0)
450 * Stop any CGI process...
453 cupsdEndProcess(con
->pipe_pid
, 1);
459 cupsdRemoveSelect(con
->file
);
466 * Close the socket and clear the file from the input set for select()...
469 if (httpGetFd(con
->http
) >= 0)
471 cupsArrayRemove(ActiveClients
, con
);
476 * Shutdown encryption as needed...
479 if (httpIsEncrypted(con
->http
))
481 #endif /* HAVE_SSL */
486 * Only do a partial close so that the encrypted client gets everything.
489 httpShutdown(con
->http
);
490 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
493 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
498 * Shut the socket down fully...
501 cupsdRemoveSelect(httpGetFd(con
->http
));
502 httpClose(con
->http
);
513 cupsdRemoveSelect(httpGetFd(con
->http
));
515 httpClose(con
->http
);
517 cupsdClearString(&con
->filename
);
518 cupsdClearString(&con
->command
);
519 cupsdClearString(&con
->options
);
520 cupsdClearString(&con
->query_string
);
524 ippDelete(con
->request
);
530 ippDelete(con
->response
);
531 con
->response
= NULL
;
536 cupsLangFree(con
->language
);
537 con
->language
= NULL
;
540 #ifdef HAVE_AUTHORIZATION_H
543 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
546 #endif /* HAVE_AUTHORIZATION_H */
549 * Re-enable new client connections if we are going back under the
553 if (cupsArrayCount(Clients
) == MaxClients
)
554 cupsdResumeListening();
557 * Compact the list of clients as necessary...
560 cupsArrayRemove(Clients
, con
);
571 * 'cupsdFlushHeader()' - Flush the header fields to the client.
574 int /* I - Bytes written or -1 on error */
575 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
577 int bytes
= httpFlushWrite(con
->http
);
579 // TODO: Need to use httpSendResponse
580 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
588 * 'cupsdReadClient()' - Read data from a client.
592 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
594 char line
[32768], /* Line from client... */
595 operation
[64], /* Operation code from socket */
596 locale
[64], /* Locale */
597 *ptr
; /* Pointer into strings */
598 http_status_t status
; /* Transfer status */
599 ipp_state_t ipp_state
; /* State of IPP transfer */
600 int bytes
; /* Number of bytes to POST */
601 char *filename
; /* Name of file for GET/HEAD */
602 char buf
[1024]; /* Buffer for real filename */
603 struct stat filestats
; /* File information */
604 mime_type_t
*type
; /* MIME type of file */
605 cupsd_printer_t
*p
; /* Printer */
606 static unsigned request_id
= 0; /* Request ID for temp files */
609 status
= HTTP_STATUS_CONTINUE
;
611 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
616 "data_encoding=HTTP_ENCODING_%s, "
617 "data_remaining=" CUPS_LLFMT
", "
620 httpError(con
->http
), (int)httpGetReady(con
->http
),
621 httpStateString(httpGetState(con
->http
)),
622 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
623 CUPS_LLCAST
httpGetRemaining(con
->http
),
625 con
->request
? ipp_states
[con
->request
->state
] : "",
632 * Automatically check for a SSL/TLS handshake...
637 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
638 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
641 * Encrypt this connection...
644 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
645 "Saw first byte %02X, auto-negotiating "
646 "SSL/TLS session.", buf
[0] & 255);
648 if (!cupsdStartTLS(con
))
649 cupsdCloseClient(con
);
654 #endif /* HAVE_SSL */
656 switch (httpGetState(con
->http
))
658 case HTTP_STATE_WAITING
:
660 * See if we've received a request line...
663 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
664 if (con
->operation
== HTTP_STATE_ERROR
||
665 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
666 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
668 if (httpError(con
->http
))
669 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
670 "HTTP_STATE_WAITING Closing for error %d (%s)",
671 httpError(con
->http
), strerror(httpError(con
->http
)));
673 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
674 "HTTP_STATE_WAITING Closing on error: %s",
675 cupsLastErrorString());
677 cupsdCloseClient(con
);
682 * Ignore blank request lines...
685 if (con
->operation
== HTTP_STATE_WAITING
)
689 * Clear other state variables...
696 con
->username
[0] = '\0';
697 con
->password
[0] = '\0';
699 cupsdClearString(&con
->command
);
700 cupsdClearString(&con
->options
);
701 cupsdClearString(&con
->query_string
);
705 ippDelete(con
->request
);
711 ippDelete(con
->response
);
712 con
->response
= NULL
;
717 cupsLangFree(con
->language
);
718 con
->language
= NULL
;
724 #endif /* HAVE_GSSAPI */
727 * Handle full URLs in the request line...
730 if (strcmp(con
->uri
, "*"))
732 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
733 userpass
[HTTP_MAX_URI
], /* Username:password */
734 hostname
[HTTP_MAX_URI
], /* Hostname */
735 resource
[HTTP_MAX_URI
]; /* Resource path */
736 int port
; /* Port number */
739 * Separate the URI into its components...
742 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
743 scheme
, sizeof(scheme
),
744 userpass
, sizeof(userpass
),
745 hostname
, sizeof(hostname
), &port
,
746 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
748 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
750 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
751 cupsdCloseClient(con
);
756 * Only allow URIs with the servername, localhost, or an IP
760 if (strcmp(scheme
, "file") &&
761 _cups_strcasecmp(hostname
, ServerName
) &&
762 _cups_strcasecmp(hostname
, "localhost") &&
763 !cupsArrayFind(ServerAlias
, hostname
) &&
764 !isdigit(hostname
[0]) && hostname
[0] != '[')
767 * Nope, we don't do proxies...
770 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
772 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
773 cupsdCloseClient(con
);
778 * Copy the resource portion back into the URI; both resource and
779 * con->uri are HTTP_MAX_URI bytes in size...
782 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
786 * Process the request...
789 gettimeofday(&(con
->start
), NULL
);
791 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
793 httpGetVersion(con
->http
) / 100,
794 httpGetVersion(con
->http
) % 100);
796 if (!cupsArrayFind(ActiveClients
, con
))
798 cupsArrayAdd(ActiveClients
, con
);
802 case HTTP_STATE_OPTIONS
:
803 case HTTP_STATE_DELETE
:
804 case HTTP_STATE_GET
:
805 case HTTP_STATE_HEAD
:
806 case HTTP_STATE_POST
:
807 case HTTP_STATE_PUT
:
808 case HTTP_STATE_TRACE
:
810 * Parse incoming parameters until the status changes...
813 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
814 if (!httpGetReady(con
->http
))
817 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
819 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
820 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
821 "Closing for error %d (%s) while reading headers.",
822 httpError(con
->http
), strerror(httpError(con
->http
)));
824 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
825 "Closing on EOF while reading headers.");
827 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
828 cupsdCloseClient(con
);
834 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
837 * Connection closed...
840 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
841 cupsdCloseClient(con
);
844 break; /* Anti-compiler-warning-code */
848 * Handle new transfers...
851 if (status
== HTTP_STATUS_OK
)
853 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
856 * Figure out the locale from the Accept-Language and Content-Type
860 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
864 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
868 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
869 "charset=")) != NULL
)
872 * Combine language and charset, and trim any extra params in the
876 snprintf(locale
, sizeof(locale
), "%s.%s",
877 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
879 if ((ptr
= strchr(locale
, ',')) != NULL
)
883 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
884 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
886 con
->language
= cupsLangGet(locale
);
889 con
->language
= cupsLangGet(DefaultLocale
);
893 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
894 "Keep-Alive", 10) && KeepAlive
)
895 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
896 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
898 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
900 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
901 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
904 * HTTP/1.1 and higher require the "Host:" field...
907 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
909 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
910 cupsdCloseClient(con
);
914 else if (!valid_host(con
))
917 * Access to localhost must use "localhost" or the corresponding IPv4
918 * or IPv6 values in the Host: field.
921 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
922 "Request from \"%s\" using invalid Host: field \"%s\".",
923 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
925 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
927 cupsdCloseClient(con
);
931 else if (con
->operation
== HTTP_STATE_OPTIONS
)
934 * Do OPTIONS command...
937 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
939 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
941 cupsdCloseClient(con
);
946 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
947 !httpIsEncrypted(con
->http
))
951 * Do encryption stuff...
955 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
957 cupsdCloseClient(con
);
961 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
962 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
963 httpPrintf(con
->http
, "Content-Length: 0\r\n");
964 httpPrintf(con
->http
, "\r\n");
966 if (cupsdFlushHeader(con
) < 0)
968 cupsdCloseClient(con
);
973 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
975 cupsdCloseClient(con
);
980 if (!cupsdStartTLS(con
))
982 cupsdCloseClient(con
);
986 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
988 cupsdCloseClient(con
);
991 #endif /* HAVE_SSL */
995 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
997 cupsdCloseClient(con
);
1001 httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1002 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1003 httpPrintf(con
->http
, "\r\n");
1005 if (cupsdFlushHeader(con
) < 0)
1007 cupsdCloseClient(con
);
1011 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
1012 "GET, HEAD, OPTIONS, POST, PUT");
1013 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1015 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1017 cupsdCloseClient(con
);
1022 else if (!is_path_absolute(con
->uri
))
1025 * Protect against malicious users!
1028 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1029 "Request for non-absolute resource \"%s\".", con
->uri
);
1031 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1033 cupsdCloseClient(con
);
1039 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
1040 "Upgrade") && !httpIsEncrypted(con
->http
))
1044 * Do encryption stuff...
1048 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1051 cupsdCloseClient(con
);
1055 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1056 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1057 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1058 httpPrintf(con
->http
, "\r\n");
1060 if (cupsdFlushHeader(con
) < 0)
1062 cupsdCloseClient(con
);
1066 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1069 cupsdCloseClient(con
);
1074 if (!cupsdStartTLS(con
))
1076 cupsdCloseClient(con
);
1080 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1082 cupsdCloseClient(con
);
1085 #endif /* HAVE_SSL */
1088 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1090 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1091 cupsdCloseClient(con
);
1095 if (httpGetExpect(con
->http
) &&
1096 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1098 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1101 * Send 100-continue header...
1104 if (!cupsdSendHeader(con
, HTTP_STATUS_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1106 cupsdCloseClient(con
);
1113 * Send 417-expectation-failed header...
1116 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1118 if (!cupsdSendHeader(con
, HTTP_STATUS_EXPECTATION_FAILED
, NULL
,
1121 cupsdCloseClient(con
);
1127 switch (httpGetState(con
->http
))
1129 case HTTP_STATE_GET_SEND
:
1130 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1131 !strncmp(con
->uri
, "/printers/", 10) ||
1132 !strncmp(con
->uri
, "/classes/", 9)) &&
1133 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1136 * Send PPD file - get the real printer name since printer
1137 * names are not case sensitive but filenames can be...
1140 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1142 if (!strncmp(con
->uri
, "/ppd/", 5))
1143 p
= cupsdFindPrinter(con
->uri
+ 5);
1144 else if (!strncmp(con
->uri
, "/printers/", 10))
1145 p
= cupsdFindPrinter(con
->uri
+ 10);
1148 p
= cupsdFindClass(con
->uri
+ 9);
1152 int i
; /* Looping var */
1154 for (i
= 0; i
< p
->num_printers
; i
++)
1156 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1158 char ppdname
[1024];/* PPD filename */
1160 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1161 ServerRoot
, p
->printers
[i
]->name
);
1162 if (!access(ppdname
, 0))
1170 if (i
>= p
->num_printers
)
1177 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1181 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1183 cupsdCloseClient(con
);
1190 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1191 !strncmp(con
->uri
, "/printers/", 10) ||
1192 !strncmp(con
->uri
, "/classes/", 9)) &&
1193 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1196 * Send icon file - get the real queue name since queue names are
1197 * not case sensitive but filenames can be...
1200 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1202 if (!strncmp(con
->uri
, "/icons/", 7))
1203 p
= cupsdFindPrinter(con
->uri
+ 7);
1204 else if (!strncmp(con
->uri
, "/printers/", 10))
1205 p
= cupsdFindPrinter(con
->uri
+ 10);
1208 p
= cupsdFindClass(con
->uri
+ 9);
1212 int i
; /* Looping var */
1214 for (i
= 0; i
< p
->num_printers
; i
++)
1216 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1218 char ppdname
[1024];/* PPD filename */
1220 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1221 ServerRoot
, p
->printers
[i
]->name
);
1222 if (!access(ppdname
, 0))
1230 if (i
>= p
->num_printers
)
1236 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1239 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1241 cupsdCloseClient(con
);
1248 else if (!WebInterface
)
1251 * Web interface is disabled. Show an appropriate message...
1254 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1256 cupsdCloseClient(con
);
1263 if ((!strncmp(con
->uri
, "/admin", 6) &&
1264 strncmp(con
->uri
, "/admin/conf/", 12) &&
1265 strncmp(con
->uri
, "/admin/log/", 11)) ||
1266 !strncmp(con
->uri
, "/printers", 9) ||
1267 !strncmp(con
->uri
, "/classes", 8) ||
1268 !strncmp(con
->uri
, "/help", 5) ||
1269 !strncmp(con
->uri
, "/jobs", 5))
1272 * Send CGI output...
1275 if (!strncmp(con
->uri
, "/admin", 6))
1277 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1280 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1282 else if (!strncmp(con
->uri
, "/printers", 9))
1284 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1287 if (con
->uri
[9] && con
->uri
[10])
1288 cupsdSetString(&con
->options
, con
->uri
+ 9);
1290 cupsdSetString(&con
->options
, NULL
);
1292 else if (!strncmp(con
->uri
, "/classes", 8))
1294 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1297 if (con
->uri
[8] && con
->uri
[9])
1298 cupsdSetString(&con
->options
, con
->uri
+ 8);
1300 cupsdSetString(&con
->options
, NULL
);
1302 else if (!strncmp(con
->uri
, "/jobs", 5))
1304 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1307 if (con
->uri
[5] && con
->uri
[6])
1308 cupsdSetString(&con
->options
, con
->uri
+ 5);
1310 cupsdSetString(&con
->options
, NULL
);
1314 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1317 if (con
->uri
[5] && con
->uri
[6])
1318 cupsdSetString(&con
->options
, con
->uri
+ 5);
1320 cupsdSetString(&con
->options
, NULL
);
1323 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1325 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1327 cupsdCloseClient(con
);
1332 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1334 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1335 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1337 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1338 (strchr(con
->uri
+ 12, '/') ||
1339 strlen(con
->uri
) == 12)) ||
1340 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1341 (strchr(con
->uri
+ 11, '/') ||
1342 strlen(con
->uri
) == 11)))
1345 * GET can only be done to configuration files directly under
1349 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1350 "Request for subdirectory \"%s\"!", con
->uri
);
1352 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1354 cupsdCloseClient(con
);
1366 if ((filename
= get_file(con
, &filestats
, buf
,
1367 sizeof(buf
))) == NULL
)
1369 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1371 cupsdCloseClient(con
);
1378 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1380 if (is_cgi(con
, filename
, &filestats
, type
))
1383 * Note: con->command and con->options were set by
1387 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1389 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1391 cupsdCloseClient(con
);
1396 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1398 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1399 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1403 if (!check_if_modified(con
, &filestats
))
1405 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1407 cupsdCloseClient(con
);
1414 strlcpy(line
, "text/plain", sizeof(line
));
1416 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1418 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1420 cupsdCloseClient(con
);
1427 case HTTP_STATE_POST_RECV
:
1429 * See if the POST request includes a Content-Length field, and if
1430 * so check the length against any limits that are set...
1433 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1434 MaxRequestSize
> 0 &&
1435 httpGetLength2(con
->http
) > MaxRequestSize
)
1438 * Request too large...
1441 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1443 cupsdCloseClient(con
);
1449 else if (httpGetLength2(con
->http
) < 0)
1452 * Negative content lengths are invalid!
1455 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1457 cupsdCloseClient(con
);
1465 * See what kind of POST request this is; for IPP requests the
1466 * content-type field will be "application/ipp"...
1469 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1471 con
->request
= ippNew();
1472 else if (!WebInterface
)
1475 * Web interface is disabled. Show an appropriate message...
1478 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1480 cupsdCloseClient(con
);
1486 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1487 strncmp(con
->uri
, "/admin/conf/", 12) &&
1488 strncmp(con
->uri
, "/admin/log/", 11)) ||
1489 !strncmp(con
->uri
, "/printers", 9) ||
1490 !strncmp(con
->uri
, "/classes", 8) ||
1491 !strncmp(con
->uri
, "/help", 5) ||
1492 !strncmp(con
->uri
, "/jobs", 5))
1498 if (!strncmp(con
->uri
, "/admin", 6))
1500 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1503 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1505 else if (!strncmp(con
->uri
, "/printers", 9))
1507 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1510 if (con
->uri
[9] && con
->uri
[10])
1511 cupsdSetString(&con
->options
, con
->uri
+ 9);
1513 cupsdSetString(&con
->options
, NULL
);
1515 else if (!strncmp(con
->uri
, "/classes", 8))
1517 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1520 if (con
->uri
[8] && con
->uri
[9])
1521 cupsdSetString(&con
->options
, con
->uri
+ 8);
1523 cupsdSetString(&con
->options
, NULL
);
1525 else if (!strncmp(con
->uri
, "/jobs", 5))
1527 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1530 if (con
->uri
[5] && con
->uri
[6])
1531 cupsdSetString(&con
->options
, con
->uri
+ 5);
1533 cupsdSetString(&con
->options
, NULL
);
1537 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1540 if (con
->uri
[5] && con
->uri
[6])
1541 cupsdSetString(&con
->options
, con
->uri
+ 5);
1543 cupsdSetString(&con
->options
, NULL
);
1546 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1547 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1555 if ((filename
= get_file(con
, &filestats
, buf
,
1556 sizeof(buf
))) == NULL
)
1558 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1560 cupsdCloseClient(con
);
1567 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1569 if (!is_cgi(con
, filename
, &filestats
, type
))
1572 * Only POST to CGI's...
1575 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1577 cupsdCloseClient(con
);
1584 case HTTP_STATE_PUT_RECV
:
1586 * Validate the resource name...
1589 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1592 * PUT can only be done to the cupsd.conf file...
1595 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1596 "Disallowed PUT request for \"%s\".", con
->uri
);
1598 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1600 cupsdCloseClient(con
);
1608 * See if the PUT request includes a Content-Length field, and if
1609 * so check the length against any limits that are set...
1612 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1613 MaxRequestSize
> 0 &&
1614 httpGetLength2(con
->http
) > MaxRequestSize
)
1617 * Request too large...
1620 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1622 cupsdCloseClient(con
);
1628 else if (httpGetLength2(con
->http
) < 0)
1631 * Negative content lengths are invalid!
1634 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1636 cupsdCloseClient(con
);
1644 * Open a temporary file to hold the request...
1647 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1649 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1653 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1654 "Unable to create request file \"%s\": %s",
1655 con
->filename
, strerror(errno
));
1657 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1659 cupsdCloseClient(con
);
1664 fchmod(con
->file
, 0640);
1665 fchown(con
->file
, RunUser
, Group
);
1666 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1669 case HTTP_STATE_DELETE
:
1670 case HTTP_STATE_TRACE
:
1671 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1672 cupsdCloseClient(con
);
1675 case HTTP_STATE_HEAD
:
1676 if (!strncmp(con
->uri
, "/printers/", 10) &&
1677 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1680 * Send PPD file - get the real printer name since printer
1681 * names are not case sensitive but filenames can be...
1684 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1686 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1687 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1690 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1692 cupsdCloseClient(con
);
1696 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1700 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1701 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1704 * Send PNG file - get the real printer name since printer
1705 * names are not case sensitive but filenames can be...
1708 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1710 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1711 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1714 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1716 cupsdCloseClient(con
);
1720 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1724 else if (!WebInterface
)
1726 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1728 cupsdCloseClient(con
);
1732 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1736 if ((!strncmp(con
->uri
, "/admin", 6) &&
1737 strncmp(con
->uri
, "/admin/conf/", 12) &&
1738 strncmp(con
->uri
, "/admin/log/", 11)) ||
1739 !strncmp(con
->uri
, "/printers", 9) ||
1740 !strncmp(con
->uri
, "/classes", 8) ||
1741 !strncmp(con
->uri
, "/help", 5) ||
1742 !strncmp(con
->uri
, "/jobs", 5))
1748 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1750 cupsdCloseClient(con
);
1754 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1756 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1757 (strchr(con
->uri
+ 12, '/') ||
1758 strlen(con
->uri
) == 12)) ||
1759 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1760 (strchr(con
->uri
+ 11, '/') ||
1761 strlen(con
->uri
) == 11)))
1764 * HEAD can only be done to configuration files under
1768 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1769 "Request for subdirectory \"%s\".", con
->uri
);
1771 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1773 cupsdCloseClient(con
);
1777 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1780 else if ((filename
= get_file(con
, &filestats
, buf
,
1781 sizeof(buf
))) == NULL
)
1783 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1786 cupsdCloseClient(con
);
1790 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1792 else if (!check_if_modified(con
, &filestats
))
1794 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1796 cupsdCloseClient(con
);
1800 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1808 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1810 strlcpy(line
, "text/plain", sizeof(line
));
1812 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1814 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1815 httpGetDateString(filestats
.st_mtime
));
1816 httpSetLength(con
->http
, filestats
.st_size
);
1818 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1820 cupsdCloseClient(con
);
1824 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1829 break; /* Anti-compiler-warning-code */
1835 * Handle any incoming data...
1838 switch (httpGetState(con
->http
))
1840 case HTTP_STATE_PUT_RECV
:
1843 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1845 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1846 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1847 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1848 httpError(con
->http
), strerror(httpError(con
->http
)));
1850 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1851 "HTTP_STATE_PUT_RECV Closing on EOF.");
1853 cupsdCloseClient(con
);
1858 con
->bytes
+= bytes
;
1860 if (write(con
->file
, line
, bytes
) < bytes
)
1862 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1863 "Unable to write %d bytes to \"%s\": %s", bytes
,
1864 con
->filename
, strerror(errno
));
1868 unlink(con
->filename
);
1869 cupsdClearString(&con
->filename
);
1871 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1873 cupsdCloseClient(con
);
1879 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1881 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1884 * End of file, see how big it is...
1887 fstat(con
->file
, &filestats
);
1892 if (filestats
.st_size
> MaxRequestSize
&&
1896 * Request is too big; remove it and send an error...
1899 unlink(con
->filename
);
1900 cupsdClearString(&con
->filename
);
1902 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1904 cupsdCloseClient(con
);
1910 * Install the configuration file...
1913 status
= install_cupsd_conf(con
);
1916 * Return the status to the client...
1919 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1921 cupsdCloseClient(con
);
1927 case HTTP_STATE_POST_RECV
:
1930 if (con
->request
&& con
->file
< 0)
1933 * Grab any request data from the connection...
1936 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1938 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1939 cupsLastErrorString());
1941 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1942 cupsdCloseClient(con
);
1945 else if (ipp_state
!= IPP_STATE_DATA
)
1947 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1949 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1950 cupsdCloseClient(con
);
1954 if (httpGetReady(con
->http
))
1960 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1961 con
->request
->request
.op
.version
[0],
1962 con
->request
->request
.op
.version
[1],
1963 ippOpString(con
->request
->request
.op
.operation_id
),
1964 con
->request
->request
.op
.request_id
);
1965 con
->bytes
+= ippLength(con
->request
);
1969 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1972 * Create a file as needed for the request data...
1975 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1977 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1981 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1982 "Unable to create request file \"%s\": %s",
1983 con
->filename
, strerror(errno
));
1985 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1987 cupsdCloseClient(con
);
1992 fchmod(con
->file
, 0640);
1993 fchown(con
->file
, RunUser
, Group
);
1994 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1997 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1999 if (!httpWait(con
->http
, 0))
2001 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
2003 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
2004 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2005 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
2006 httpError(con
->http
), strerror(httpError(con
->http
)));
2008 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2009 "HTTP_STATE_POST_SEND Closing on EOF.");
2011 cupsdCloseClient(con
);
2016 con
->bytes
+= bytes
;
2018 if (write(con
->file
, line
, bytes
) < bytes
)
2020 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2021 "Unable to write %d bytes to \"%s\": %s",
2022 bytes
, con
->filename
, strerror(errno
));
2026 unlink(con
->filename
);
2027 cupsdClearString(&con
->filename
);
2029 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
2032 cupsdCloseClient(con
);
2037 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
2039 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2041 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2042 "Closing on unexpected state %s.",
2043 httpStateString(httpGetState(con
->http
)));
2044 cupsdCloseClient(con
);
2049 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
2051 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2055 fstat(con
->file
, &filestats
);
2060 if (filestats
.st_size
> MaxRequestSize
&&
2064 * Request is too big; remove it and send an error...
2067 unlink(con
->filename
);
2068 cupsdClearString(&con
->filename
);
2073 * Delete any IPP request data...
2076 ippDelete(con
->request
);
2077 con
->request
= NULL
;
2080 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2082 cupsdCloseClient(con
);
2086 else if (filestats
.st_size
== 0)
2089 * Don't allow empty file...
2092 unlink(con
->filename
);
2093 cupsdClearString(&con
->filename
);
2098 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2100 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2102 cupsdCloseClient(con
);
2107 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2113 cupsdProcessIPPRequest(con
);
2117 unlink(con
->filename
);
2118 cupsdClearString(&con
->filename
);
2127 break; /* Anti-compiler-warning-code */
2130 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2132 if (!httpGetKeepAlive(con
->http
))
2134 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2135 "Closing because Keep-Alive is disabled.");
2136 cupsdCloseClient(con
);
2140 cupsArrayRemove(ActiveClients
, con
);
2141 cupsdSetBusyState();
2148 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2151 int /* O - 1 on success, 0 on failure */
2153 cupsd_client_t
*con
, /* I - Client connection */
2154 char *command
, /* I - Command to run */
2155 char *options
, /* I - Command-line options */
2156 int root
) /* I - Run as root? */
2158 int fd
; /* Standard input file descriptor */
2163 fd
= open(con
->filename
, O_RDONLY
);
2167 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2168 "Unable to open \"%s\" for reading: %s",
2169 con
->filename
? con
->filename
: "/dev/null",
2174 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2179 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2180 con
->pipe_status
= HTTP_STATUS_OK
;
2185 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2186 command
, con
->pipe_pid
, con
->file
);
2188 if (con
->pipe_pid
== 0)
2191 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2193 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2195 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2197 con
->sent_header
= 0;
2198 con
->file_ready
= 0;
2199 con
->got_fields
= 0;
2200 con
->header_used
= 0;
2207 * 'cupsdSendError()' - Send an error message via HTTP.
2210 int /* O - 1 if successful, 0 otherwise */
2211 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2212 http_status_t code
, /* I - Error code */
2213 int auth_type
)/* I - Authentication type */
2215 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2220 * Force client to upgrade for authentication if that is how the
2221 * server is configured...
2224 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2225 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2226 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2227 !httpIsEncrypted(con
->http
))
2229 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2231 #endif /* HAVE_SSL */
2234 * Put the request in the access_log file...
2237 cupsdLogRequest(con
, code
);
2240 * To work around bugs in some proxies, don't use Keep-Alive for some
2243 * Kerberos authentication doesn't work without Keep-Alive, so
2244 * never disable it in that case.
2247 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2248 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2250 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2251 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2252 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2254 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2257 * Send a human-readable error message.
2260 char message
[4096], /* Message for user */
2261 urltext
[1024], /* URL redirection text */
2262 redirect
[1024]; /* Redirection link */
2263 const char *text
; /* Status-specific text */
2268 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2269 text
= _cupsLangString(con
->language
,
2270 _("Enter your username and password or the "
2271 "root username and password to access this "
2272 "page. If you are using Kerberos authentication, "
2273 "make sure you have a valid Kerberos ticket."));
2274 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2278 snprintf(urltext
, sizeof(urltext
),
2279 _cupsLangString(con
->language
,
2280 _("You must access this page using the URL "
2281 "<A HREF=\"https://%s:%d%s\">"
2282 "https://%s:%d%s</A>.")),
2283 con
->servername
, con
->serverport
, con
->uri
,
2284 con
->servername
, con
->serverport
, con
->uri
);
2286 snprintf(redirect
, sizeof(redirect
),
2287 "<META HTTP-EQUIV=\"Refresh\" "
2288 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2289 con
->servername
, con
->serverport
, con
->uri
);
2291 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2292 text
= _cupsLangString(con
->language
,
2293 _("The web interface is currently disabled. Run "
2294 "\"cupsctl WebInterface=yes\" to enable it."));
2298 snprintf(message
, sizeof(message
),
2299 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2300 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2303 "\t<META HTTP-EQUIV=\"Content-Type\" "
2304 "CONTENT=\"text/html; charset=utf-8\">\n"
2305 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2306 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2307 "HREF=\"/cups.css\">\n"
2315 _httpStatus(con
->language
, code
), redirect
,
2316 _httpStatus(con
->language
, code
), text
);
2319 * Send an error message back to the client. If the error code is a
2320 * 400 or 500 series, make sure the message contains some text, too!
2323 httpSetLength(con
->http
, strlen(message
));
2325 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2328 if (httpPrintf(con
->http
, "%s", message
) < 0)
2333 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2335 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2344 * 'cupsdSendHeader()' - Send an HTTP request.
2347 int /* O - 1 on success, 0 on failure */
2349 cupsd_client_t
*con
, /* I - Client to send to */
2350 http_status_t code
, /* I - HTTP status code */
2351 char *type
, /* I - MIME type of document */
2352 int auth_type
) /* I - Type of authentication */
2354 char auth_str
[1024]; /* Authorization string */
2358 * Send the HTTP status header...
2361 if (code
== HTTP_STATUS_CONTINUE
)
2364 * 100-continue doesn't send any headers...
2367 return (!httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
));
2369 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2372 * Treat our special "web interface is disabled" status as "200 OK" for web
2376 code
= HTTP_STATUS_OK
;
2380 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2382 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2383 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2385 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2387 if (auth_type
== CUPSD_AUTH_NONE
)
2389 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2390 auth_type
= cupsdDefaultAuthType();
2392 auth_type
= con
->best
->type
;
2397 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2398 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2399 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2400 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2401 httpGetHostname(con
->http
, NULL
, 0));
2403 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2406 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2407 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2409 # endif /* AF_LOCAL */
2410 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2412 #endif /* HAVE_GSSAPI */
2414 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2415 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2418 * Add a "trc" (try root certification) parameter for local non-Kerberos
2419 * requests when the request requires system group membership - then the
2420 * client knows the root certificate can/should be used.
2422 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2423 * parameter as needed...
2426 char *name
, /* Current user name */
2427 *auth_key
; /* Auth key buffer */
2428 size_t auth_size
; /* Size of remaining buffer */
2430 auth_key
= auth_str
+ strlen(auth_str
);
2431 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2433 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2435 name
= (char *)cupsArrayNext(con
->best
->names
))
2437 #ifdef HAVE_AUTHORIZATION_H
2438 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2440 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2441 /* end parenthesis is stripped in conf.c */
2445 #endif /* HAVE_AUTHORIZATION_H */
2446 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2448 #ifdef HAVE_AUTHORIZATION_H
2449 if (SystemGroupAuthKey
)
2450 snprintf(auth_key
, auth_size
,
2452 SystemGroupAuthKey
);
2455 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2456 #endif /* HAVE_AUTHORIZATION_H */
2464 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2466 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2470 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2471 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2475 if (!strcmp(type
, "text/html"))
2476 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2478 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2481 return (!httpWriteResponse(con
->http
, code
));
2486 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2490 cupsdUpdateCGI(void)
2492 char *ptr
, /* Pointer to end of line in buffer */
2493 message
[1024]; /* Pointer to message text */
2494 int loglevel
; /* Log level for message */
2497 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2498 message
, sizeof(message
))) != NULL
)
2500 if (loglevel
== CUPSD_LOG_INFO
)
2501 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2503 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2507 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2510 * Fatal error on pipe - should never happen!
2513 cupsdLogMessage(CUPSD_LOG_CRIT
,
2514 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2521 * 'cupsdWriteClient()' - Write data to a client as needed.
2525 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2527 int bytes
, /* Number of bytes written */
2528 field_col
; /* Current column */
2529 char *bufptr
, /* Pointer into buffer */
2530 *bufend
; /* Pointer to end of buffer */
2531 ipp_state_t ipp_state
; /* IPP state value */
2534 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2535 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2540 "data_encoding=HTTP_ENCODING_%s, "
2541 "data_remaining=" CUPS_LLFMT
", "
2545 httpError(con
->http
), (int)httpGetReady(con
->http
),
2546 httpStateString(httpGetState(con
->http
)),
2547 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2548 CUPS_LLCAST
httpGetLength2(con
->http
),
2550 con
->response
? ipp_states
[con
->response
->state
] : "",
2551 con
->pipe_pid
, con
->file
);
2553 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2554 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2557 * If we get called in the wrong state, then something went wrong with the
2558 * connection and we need to shut it down...
2561 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP state %s.",
2562 httpStateString(httpGetState(con
->http
)));
2563 cupsdCloseClient(con
);
2570 * Make sure we select on the CGI output...
2573 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2575 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2577 if (!con
->file_ready
)
2580 * Try again later when there is CGI output available...
2583 cupsdRemoveSelect(httpGetFd(con
->http
));
2587 con
->file_ready
= 0;
2590 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2592 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2597 * Write a single attribute or the IPP message header...
2600 ipp_state
= ippWrite(con
->http
, con
->response
);
2603 * If the write buffer has been flushed, stop buffering up attributes...
2606 if (httpGetPending(con
->http
) <= wused
)
2609 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2611 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2612 "Writing IPP response, ipp_state=%s, old "
2613 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2614 ippStateString(ipp_state
),
2615 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2617 if (httpGetPending(con
->http
) > 0)
2618 httpFlushWrite(con
->http
);
2620 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2621 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2623 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2624 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2625 (int)bytes
, httpGetState(con
->http
),
2626 CUPS_LLCAST
httpGetLength2(con
->http
));
2628 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2629 sizeof(con
->header
) - con
->header_used
)) > 0)
2631 con
->header_used
+= bytes
;
2633 if (con
->pipe_pid
&& !con
->got_fields
)
2636 * Inspect the data for Content-Type and other fields.
2639 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2641 !con
->got_fields
&& bufptr
< bufend
;
2644 if (*bufptr
== '\n')
2647 * Send line to client...
2650 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2654 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2656 if (!con
->sent_header
)
2659 * Handle redirection and CGI status codes...
2662 http_field_t field
; /* HTTP field */
2663 char *value
= strchr(con
->header
, ':');
2664 /* Value of field */
2669 while (isspace(*value
& 255))
2673 field
= httpFieldValue(con
->header
);
2675 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2677 httpSetField(con
->http
, field
, value
);
2679 if (field
== HTTP_FIELD_LOCATION
)
2681 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2682 con
->sent_header
= 2;
2685 con
->sent_header
= 1;
2687 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2689 con
->pipe_status
= (http_status_t
)atoi(value
);
2690 con
->sent_header
= 2;
2692 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2694 char *sep
= strchr(value
, ';');
2695 /* Separator between name=value and the rest */
2700 httpSetCookie(con
->http
, value
);
2701 con
->sent_header
= 1;
2709 con
->header_used
-= bufptr
- con
->header
;
2711 if (con
->header_used
> 0)
2712 memmove(con
->header
, bufptr
, con
->header_used
);
2714 bufptr
= con
->header
- 1;
2717 * See if the line was empty...
2722 con
->got_fields
= 1;
2724 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2725 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2726 httpSetLength(con
->http
, 0);
2728 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2730 cupsdCloseClient(con
);
2737 else if (*bufptr
!= '\r')
2741 if (!con
->got_fields
)
2745 if (con
->header_used
> 0)
2747 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2749 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2750 httpError(con
->http
), strerror(httpError(con
->http
)));
2751 cupsdCloseClient(con
);
2755 if (httpIsChunked(con
->http
))
2756 httpFlushWrite(con
->http
);
2758 con
->bytes
+= con
->header_used
;
2760 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2763 bytes
= con
->header_used
;
2765 con
->header_used
= 0;
2770 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2771 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2773 if (!con
->sent_header
&& con
->pipe_pid
)
2774 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2777 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2779 httpFlushWrite(con
->http
);
2781 if (httpIsChunked(con
->http
) && con
->sent_header
== 1)
2783 if (httpWrite2(con
->http
, "", 0) < 0)
2785 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2786 httpError(con
->http
), strerror(httpError(con
->http
)));
2787 cupsdCloseClient(con
);
2793 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2795 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2799 cupsdRemoveSelect(con
->file
);
2802 cupsdEndProcess(con
->pipe_pid
, 0);
2811 unlink(con
->filename
);
2812 cupsdClearString(&con
->filename
);
2817 ippDelete(con
->request
);
2818 con
->request
= NULL
;
2823 ippDelete(con
->response
);
2824 con
->response
= NULL
;
2827 cupsdClearString(&con
->command
);
2828 cupsdClearString(&con
->options
);
2829 cupsdClearString(&con
->query_string
);
2831 if (!httpGetKeepAlive(con
->http
))
2833 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2834 "Closing because Keep-Alive is disabled.");
2835 cupsdCloseClient(con
);
2840 cupsArrayRemove(ActiveClients
, con
);
2841 cupsdSetBusyState();
2848 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2851 static int /* O - 1 if modified since */
2853 cupsd_client_t
*con
, /* I - Client connection */
2854 struct stat
*filestats
) /* I - File information */
2856 const char *ptr
; /* Pointer into field */
2857 time_t date
; /* Time/date value */
2858 off_t size
; /* Size/length value */
2863 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2868 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2869 "check_if_modified "
2870 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2871 filestats
, CUPS_LLCAST filestats
->st_size
,
2872 (int)filestats
->st_mtime
, ptr
);
2874 while (*ptr
!= '\0')
2876 while (isspace(*ptr
) || *ptr
== ';')
2879 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2882 size
= strtoll(ptr
, NULL
, 10);
2884 while (isdigit(*ptr
))
2887 else if (isalpha(*ptr
))
2889 date
= httpGetDateTime(ptr
);
2890 while (*ptr
!= '\0' && *ptr
!= ';')
2897 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2898 (date
< filestats
->st_mtime
&& date
!= 0) ||
2899 (size
== 0 && date
== 0));
2904 * 'compare_clients()' - Compare two client connections.
2907 static int /* O - Result of comparison */
2908 compare_clients(cupsd_client_t
*a
, /* I - First client */
2909 cupsd_client_t
*b
, /* I - Second client */
2910 void *data
) /* I - User data (not used) */
2924 * 'get_file()' - Get a filename and state info.
2927 static char * /* O - Real filename */
2928 get_file(cupsd_client_t
*con
, /* I - Client connection */
2929 struct stat
*filestats
, /* O - File information */
2930 char *filename
, /* IO - Filename buffer */
2931 int len
) /* I - Buffer length */
2933 int status
; /* Status of filesystem calls */
2934 char *ptr
; /* Pointer info filename */
2935 int plen
; /* Remaining length after pointer */
2936 char language
[7]; /* Language subdirectory, if any */
2940 * Figure out the real filename...
2945 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2946 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2947 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2949 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
2950 if (access(filename
, F_OK
) < 0)
2951 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2953 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2954 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2955 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2956 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2957 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2959 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2960 strlcpy(filename
, AccessLog
, len
);
2961 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2962 strlcpy(filename
, ErrorLog
, len
);
2963 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2964 strlcpy(filename
, PageLog
, len
);
2968 else if (con
->language
)
2970 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2971 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2974 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2976 if ((ptr
= strchr(filename
, '?')) != NULL
)
2980 * Grab the status for this language; if there isn't a language-specific file
2981 * then fallback to the default one...
2984 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
2985 strncmp(con
->uri
, "/icons/", 7) &&
2986 strncmp(con
->uri
, "/ppd/", 5) &&
2987 strncmp(con
->uri
, "/rss/", 5) &&
2988 strncmp(con
->uri
, "/admin/conf/", 12) &&
2989 strncmp(con
->uri
, "/admin/log/", 11))
2992 * Drop the country code...
2996 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2998 if ((ptr
= strchr(filename
, '?')) != NULL
)
3001 if ((status
= stat(filename
, filestats
)) != 0)
3004 * Drop the language prefix and try the root directory...
3008 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3010 if ((ptr
= strchr(filename
, '?')) != NULL
)
3013 status
= stat(filename
, filestats
);
3018 * If we're found a directory, get the index.html file instead...
3021 if (!status
&& S_ISDIR(filestats
->st_mode
))
3024 * Make sure the URI ends with a slash...
3027 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3028 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3031 * Find the directory index file, trying every language...
3036 if (status
&& language
[0])
3039 * Try a different language subset...
3043 language
[0] = '\0'; /* Strip country code */
3045 language
[0] = '\0'; /* Strip language */
3049 * Look for the index file...
3052 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3054 if ((ptr
= strchr(filename
, '?')) != NULL
)
3057 ptr
= filename
+ strlen(filename
);
3058 plen
= len
- (ptr
- filename
);
3060 strlcpy(ptr
, "index.html", plen
);
3061 status
= stat(filename
, filestats
);
3066 strlcpy(ptr
, "index.class", plen
);
3067 status
= stat(filename
, filestats
);
3069 #endif /* HAVE_JAVA */
3074 strlcpy(ptr
, "index.pl", plen
);
3075 status
= stat(filename
, filestats
);
3077 #endif /* HAVE_PERL */
3082 strlcpy(ptr
, "index.php", plen
);
3083 status
= stat(filename
, filestats
);
3085 #endif /* HAVE_PHP */
3090 strlcpy(ptr
, "index.pyc", plen
);
3091 status
= stat(filename
, filestats
);
3096 strlcpy(ptr
, "index.py", plen
);
3097 status
= stat(filename
, filestats
);
3099 #endif /* HAVE_PYTHON */
3102 while (status
&& language
[0]);
3105 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3106 "get_file filestats=%p, filename=%p, len=%d, "
3107 "returning \"%s\".", filestats
, filename
, len
,
3108 status
? "(null)" : filename
);
3118 * 'install_cupsd_conf()' - Install a configuration file.
3121 static http_status_t
/* O - Status */
3122 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3124 char filename
[1024]; /* Configuration filename */
3125 cups_file_t
*in
, /* Input file */
3126 *out
; /* Output file */
3127 char buffer
[16384]; /* Copy buffer */
3128 ssize_t bytes
; /* Number of bytes */
3132 * Open the request file...
3135 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3137 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3138 con
->filename
, strerror(errno
));
3139 return (HTTP_STATUS_SERVER_ERROR
);
3143 * Open the new config file...
3146 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3149 return (HTTP_STATUS_SERVER_ERROR
);
3152 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3156 * Copy from the request to the new config file...
3159 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3160 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3162 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3163 "Unable to copy to config file \"%s\": %s",
3164 ConfigurationFile
, strerror(errno
));
3169 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3170 cupsdUnlinkOrRemoveFile(filename
);
3172 return (HTTP_STATUS_SERVER_ERROR
);
3176 * Close the files...
3181 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3182 return (HTTP_STATUS_SERVER_ERROR
);
3185 * Remove the request file...
3188 cupsdUnlinkOrRemoveFile(con
->filename
);
3189 cupsdClearString(&con
->filename
);
3192 * Set the NeedReload flag...
3195 NeedReload
= RELOAD_CUPSD
;
3196 ReloadTime
= time(NULL
);
3199 * Return that the file was created successfully...
3202 return (HTTP_STATUS_CREATED
);
3207 * 'is_cgi()' - Is the resource a CGI script/program?
3210 static int /* O - 1 = CGI, 0 = file */
3211 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3212 const char *filename
, /* I - Real filename */
3213 struct stat
*filestats
, /* I - File information */
3214 mime_type_t
*type
) /* I - MIME type */
3216 const char *options
; /* Options on URL */
3220 * Get the options, if any...
3223 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3226 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3230 * Check for known types...
3233 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3235 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3236 "is_cgi filename=\"%s\", filestats=%p, "
3237 "type=%s/%s, returning 0", filename
,
3238 filestats
, type
? type
->super
: "unknown",
3239 type
? type
->type
: "unknown");
3243 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3244 (filestats
->st_mode
& 0111))
3247 * "application/x-httpd-cgi" is a CGI script.
3250 cupsdSetString(&con
->command
, filename
);
3253 cupsdSetStringf(&con
->options
, " %s", options
);
3255 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3256 "is_cgi filename=\"%s\", filestats=%p, "
3257 "type=%s/%s, returning 1", filename
,
3258 filestats
, type
->super
, type
->type
);
3262 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3265 * "application/x-httpd-java" is a Java servlet.
3268 cupsdSetString(&con
->command
, CUPS_JAVA
);
3271 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3273 cupsdSetStringf(&con
->options
, " %s", filename
);
3275 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3276 "is_cgi filename=\"%s\", filestats=%p, "
3277 "type=%s/%s, returning 1", filename
,
3278 filestats
, type
->super
, type
->type
);
3281 #endif /* HAVE_JAVA */
3283 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3286 * "application/x-httpd-perl" is a Perl page.
3289 cupsdSetString(&con
->command
, CUPS_PERL
);
3292 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3294 cupsdSetStringf(&con
->options
, " %s", filename
);
3296 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3297 "is_cgi filename=\"%s\", filestats=%p, "
3298 "type=%s/%s, returning 1", filename
,
3299 filestats
, type
->super
, type
->type
);
3302 #endif /* HAVE_PERL */
3304 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3307 * "application/x-httpd-php" is a PHP page.
3310 cupsdSetString(&con
->command
, CUPS_PHP
);
3313 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3315 cupsdSetStringf(&con
->options
, " %s", filename
);
3317 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3318 "is_cgi filename=\"%s\", filestats=%p, "
3319 "type=%s/%s, returning 1", filename
,
3320 filestats
, type
->super
, type
->type
);
3323 #endif /* HAVE_PHP */
3325 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3328 * "application/x-httpd-python" is a Python page.
3331 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3334 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3336 cupsdSetStringf(&con
->options
, " %s", filename
);
3338 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3339 "is_cgi filename=\"%s\", filestats=%p, "
3340 "type=%s/%s, returning 1", filename
,
3341 filestats
, type
->super
, type
->type
);
3344 #endif /* HAVE_PYTHON */
3346 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3347 "is_cgi filename=\"%s\", filestats=%p, "
3348 "type=%s/%s, returning 0", filename
,
3349 filestats
, type
->super
, type
->type
);
3355 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3358 static int /* O - 0 if relative, 1 if absolute */
3359 is_path_absolute(const char *path
) /* I - Input path */
3362 * Check for a leading slash...
3369 * Check for "/.." in the path...
3372 while ((path
= strstr(path
, "/..")) != NULL
)
3374 if (!path
[3] || path
[3] == '/')
3381 * If we haven't found any relative paths, return 1 indicating an
3390 * 'pipe_command()' - Pipe the output of a command to the remote client.
3393 static int /* O - Process ID */
3394 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3395 int infile
, /* I - Standard input for command */
3396 int *outfile
, /* O - Standard output for command */
3397 char *command
, /* I - Command to run */
3398 char *options
, /* I - Options for command */
3399 int root
) /* I - Run as root? */
3401 int i
; /* Looping var */
3402 int pid
; /* Process ID */
3403 char *commptr
, /* Command string pointer */
3404 commch
; /* Command string character */
3405 char *uriptr
; /* URI string pointer */
3406 int fds
[2]; /* Pipe FDs */
3407 int argc
; /* Number of arguments */
3408 int envc
; /* Number of environment variables */
3409 char argbuf
[10240], /* Argument buffer */
3410 *argv
[100], /* Argument strings */
3411 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3412 char auth_type
[256], /* AUTH_TYPE environment variable */
3413 content_length
[1024], /* CONTENT_LENGTH environment variable */
3414 content_type
[1024], /* CONTENT_TYPE environment variable */
3415 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3416 http_referer
[1024], /* HTTP_REFERER environment variable */
3417 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3418 lang
[1024], /* LANG environment variable */
3419 path_info
[1024], /* PATH_INFO environment variable */
3420 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3421 remote_host
[1024], /* REMOTE_HOST environment variable */
3422 remote_user
[1024], /* REMOTE_USER environment variable */
3423 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3424 script_name
[1024], /* SCRIPT_NAME environment variable */
3425 server_name
[1024], /* SERVER_NAME environment variable */
3426 server_port
[1024]; /* SERVER_PORT environment variable */
3427 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3431 * Parse a copy of the options string, which is of the form:
3433 * argument+argument+argument
3434 * ?argument+argument+argument
3435 * param=value¶m=value
3436 * ?param=value¶m=value
3437 * /name?argument+argument+argument
3438 * /name?param=value¶m=value
3440 * If the string contains an "=" character after the initial name,
3441 * then we treat it as a HTTP GET form request and make a copy of
3442 * the remaining string for the environment variable.
3444 * The string is always parsed out as command-line arguments, to
3445 * be consistent with Apache...
3448 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3449 "pipe_command infile=%d, outfile=%p, "
3450 "command=\"%s\", options=\"%s\", root=%d",
3451 infile
, outfile
, command
,
3452 options
? options
: "(null)", root
);
3459 if (*commptr
== ' ')
3461 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3466 if (argbuf
[0] == '/')
3469 * Found some trailing path information, set PATH_INFO...
3472 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3473 commptr
= argbuf
+ strlen(argbuf
);
3477 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3483 path_info
[0] = '\0';
3485 if (*commptr
== ' ')
3489 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3492 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3499 argv
[argc
++] = commptr
;
3501 for (; *commptr
&& argc
< 99; commptr
++)
3504 * Break arguments whenever we see a + or space...
3507 if (*commptr
== ' ' || *commptr
== '+')
3509 while (*commptr
== ' ' || *commptr
== '+')
3513 * If we don't have a blank string, save it as another argument...
3518 argv
[argc
] = commptr
;
3524 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3525 isxdigit(commptr
[2] & 255))
3528 * Convert the %xx notation to the individual character.
3531 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3532 *commptr
= (commptr
[1] - '0') << 4;
3534 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3536 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3537 *commptr
|= commptr
[2] - '0';
3539 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3541 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3544 * Check for a %00 and break if that is the case...
3556 * Setup the environment variables as needed...
3559 if (con
->username
[0])
3561 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3562 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3564 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3568 auth_type
[0] = '\0';
3571 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3572 IPP_TAG_LANGUAGE
)) != NULL
)
3574 switch (strlen(attr
->values
[0].string
.text
))
3578 * This is an unknown or badly formatted language code; use
3579 * the POSIX locale...
3582 strlcpy(lang
, "LANG=C", sizeof(lang
));
3587 * Just the language code (ll)...
3590 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3591 attr
->values
[0].string
.text
);
3596 * Language and country code (ll-cc)...
3599 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3600 attr
->values
[0].string
.text
[0],
3601 attr
->values
[0].string
.text
[1],
3602 toupper(attr
->values
[0].string
.text
[3] & 255),
3603 toupper(attr
->values
[0].string
.text
[4] & 255));
3607 else if (con
->language
)
3608 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3610 strlcpy(lang
, "LANG=C", sizeof(lang
));
3612 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3613 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3614 sizeof(remote_addr
) - 12);
3616 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3617 httpGetHostname(con
->http
, NULL
, 0));
3619 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3620 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3623 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3624 DocumentRoot
, script_name
+ 12);
3626 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3628 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3630 char *nameptr
; /* Pointer to ":port" */
3632 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3633 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3634 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3635 *nameptr
= '\0'; /* Strip trailing ":port" */
3638 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3641 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3644 envp
[envc
++] = auth_type
;
3646 envp
[envc
++] = lang
;
3647 envp
[envc
++] = "REDIRECT_STATUS=1";
3648 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3649 envp
[envc
++] = server_name
;
3650 envp
[envc
++] = server_port
;
3651 envp
[envc
++] = remote_addr
;
3652 envp
[envc
++] = remote_host
;
3653 envp
[envc
++] = script_name
;
3654 envp
[envc
++] = script_filename
;
3657 envp
[envc
++] = path_info
;
3659 if (con
->username
[0])
3661 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3663 envp
[envc
++] = remote_user
;
3666 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3667 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3668 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3669 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3671 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3673 if (httpGetCookie(con
->http
))
3675 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3676 httpGetCookie(con
->http
));
3677 envp
[envc
++] = http_cookie
;
3680 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3682 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3683 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3684 envp
[envc
++] = http_user_agent
;
3687 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3689 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3690 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3691 envp
[envc
++] = http_referer
;
3694 if (con
->operation
== HTTP_STATE_GET
)
3696 envp
[envc
++] = "REQUEST_METHOD=GET";
3698 if (con
->query_string
)
3701 * Add GET form variables after ?...
3704 envp
[envc
++] = con
->query_string
;
3707 envp
[envc
++] = "QUERY_STRING=";
3711 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3712 CUPS_LLCAST con
->bytes
);
3713 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3714 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3716 envp
[envc
++] = "REQUEST_METHOD=POST";
3717 envp
[envc
++] = content_length
;
3718 envp
[envc
++] = content_type
;
3722 * Tell the CGI if we are using encryption...
3725 if (httpIsEncrypted(con
->http
))
3726 envp
[envc
++] = "HTTPS=ON";
3729 * Terminate the environment array...
3734 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3736 for (i
= 0; i
< argc
; i
++)
3737 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3738 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3739 for (i
= 0; i
< envc
; i
++)
3740 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3741 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3745 * Create a pipe for the output...
3748 if (cupsdOpenPipe(fds
))
3750 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3751 argv
[0], strerror(errno
));
3756 * Then execute the command...
3759 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3760 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3763 * Error - can't fork!
3766 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3769 cupsdClosePipe(fds
);
3775 * Fork successful - return the PID...
3778 if (con
->username
[0])
3779 cupsdAddCert(pid
, con
->username
, con
->type
);
3781 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3792 * 'valid_host()' - Is the Host: field valid?
3795 static int /* O - 1 if valid, 0 if not */
3796 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3798 cupsd_alias_t
*a
; /* Current alias */
3799 cupsd_netif_t
*netif
; /* Current network interface */
3800 const char *end
; /* End character */
3801 char *ptr
; /* Pointer into host value */
3805 * Copy the Host: header for later use...
3808 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3809 sizeof(con
->clientname
));
3810 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3813 con
->clientport
= atoi(ptr
);
3816 con
->clientport
= con
->serverport
;
3822 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3825 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3826 * addresses when accessing CUPS via the loopback interface...
3829 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3830 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3832 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3833 #endif /* __linux */
3834 !strcmp(con
->clientname
, "127.0.0.1") ||
3835 !strcmp(con
->clientname
, "[::1]"));
3838 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3840 * Check if the hostname is something.local (Bonjour); if so, allow it.
3843 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3847 * "." on end, work back to second-to-last "."...
3850 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3853 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3854 !_cups_strcasecmp(end
, ".local.")))
3856 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3859 * Check if the hostname is an IP address...
3862 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3865 * Possible IPv4/IPv6 address...
3868 http_addrlist_t
*addrlist
; /* List of addresses */
3871 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3874 * Good IPv4/IPv6 address...
3877 httpAddrFreeList(addrlist
);
3883 * Check for (alias) name matches...
3886 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3888 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3891 * "ServerAlias *" allows all host values through...
3894 if (!strcmp(a
->name
, "*"))
3897 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3900 * Prefix matches; check the character at the end - it must be "." or nul.
3903 end
= con
->clientname
+ a
->namelen
;
3905 if (!*end
|| (*end
== '.' && !end
[1]))
3910 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3911 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3913 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3916 * "ServerAlias *" allows all host values through...
3919 if (!strcmp(a
->name
, "*"))
3922 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3925 * Prefix matches; check the character at the end - it must be "." or nul.
3928 end
= con
->clientname
+ a
->namelen
;
3930 if (!*end
|| (*end
== '.' && !end
[1]))
3934 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3937 * Check for interface hostname matches...
3940 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3942 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3944 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3947 * Prefix matches; check the character at the end - it must be "." or nul.
3950 end
= con
->clientname
+ netif
->hostlen
;
3952 if (!*end
|| (*end
== '.' && !end
[1]))
3962 * 'write_file()' - Send a file via HTTP.
3965 static int /* O - 0 on failure, 1 on success */
3966 write_file(cupsd_client_t
*con
, /* I - Client connection */
3967 http_status_t code
, /* I - HTTP status */
3968 char *filename
, /* I - Filename */
3969 char *type
, /* I - File type */
3970 struct stat
*filestats
) /* O - File information */
3972 con
->file
= open(filename
, O_RDONLY
);
3974 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3975 "write_file code=%d, filename=\"%s\" (%d), "
3976 "type=\"%s\", filestats=%p",
3977 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3982 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3986 httpSetLength(con
->http
, filestats
->st_size
);
3988 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3989 httpGetDateString(filestats
->st_mtime
));
3991 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3994 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
3995 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3997 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4004 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4008 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4010 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4013 con
->file_ready
= 1;
4015 cupsdRemoveSelect(con
->file
);
4016 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4018 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");