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 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
, int 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
,
82 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
83 lis
, lis
->fd
, cupsArrayCount(Clients
));
86 * Make sure we don't have a full set of clients already...
89 if (cupsArrayCount(Clients
) == MaxClients
)
93 * Get a pointer to the next available client...
97 Clients
= cupsArrayNew(NULL
, NULL
);
101 cupsdLogMessage(CUPSD_LOG_ERROR
,
102 "Unable to allocate memory for clients array!");
103 cupsdPauseListening();
108 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
112 cupsdLogMessage(CUPSD_LOG_ERROR
,
113 "Unable to allocate memory for active clients array!");
114 cupsdPauseListening();
118 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
120 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
121 cupsdPauseListening();
126 * Accept the client and get the remote address...
129 con
->number
= ++ LastClientNumber
;
132 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
134 if (errno
== ENFILE
|| errno
== EMFILE
)
135 cupsdPauseListening();
137 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
145 * Save the connected address and port number...
148 con
->clientaddr
= lis
->address
;
150 #if 0 /* ifdef AF_INET6 */
151 /* FIXME: I don't believe this is recommended any longer, and we specifically
152 * disable IPv4-over-IPv6 when we listen...
155 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
156 * can more easily use...
159 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
160 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
161 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
162 ntohl(httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
163 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
164 #endif /* AF_INET6 */
167 * Check the number of clients on the same address...
170 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
172 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
173 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
176 if (count
>= MaxClientsPerHost
)
180 if (count
>= MaxClientsPerHost
)
182 if ((time(NULL
) - last_dos
) >= 60)
184 last_dos
= time(NULL
);
185 cupsdLogMessage(CUPSD_LOG_WARN
,
186 "Possible DoS attack - more than %d clients connecting "
189 httpGetHostname(con
->http
, name
, sizeof(name
)));
192 httpClose(con
->http
);
198 * Get the hostname or format the IP address as needed...
202 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
204 hostname
= httpGetHostname(con
->http
, NULL
, 0);
206 if (hostname
== NULL
&& HostNameLookups
== 2)
209 * Can't have an unresolved IP address with double-lookups enabled...
212 httpClose(con
->http
);
214 cupsdLogClient(con
, CUPSD_LOG_WARN
,
215 "Name lookup failed - connection from %s closed!",
216 httpGetHostname(con
->http
, NULL
, 0));
222 if (HostNameLookups
== 2)
225 * Do double lookups as needed...
228 http_addrlist_t
*addrlist
, /* List of addresses */
229 *addr
; /* Current address */
231 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
234 * See if the hostname maps to the same IP address...
237 for (addr
= addrlist
; addr
; addr
= addr
->next
)
238 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
244 httpAddrFreeList(addrlist
);
249 * Can't have a hostname that doesn't resolve to the same IP address
250 * with double-lookups enabled...
253 httpClose(con
->http
);
255 cupsdLogClient(con
, CUPSD_LOG_WARN
,
256 "IP lookup failed - connection from %s closed!",
257 httpGetHostname(con
->http
, NULL
, 0));
265 * See if the connection is denied by TCP wrappers...
268 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
272 if (!hosts_access(&wrap_req
))
274 httpClose(con
->http
);
276 cupsdLogClient(con
, CUPSD_LOG_WARN
,
277 "Connection from %s refused by /etc/hosts.allow and "
278 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
282 #endif /* HAVE_TCPD_H */
285 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
288 socklen_t peersize
; /* Size of peer credentials */
289 pid_t peerpid
; /* Peer process ID */
290 char peername
[256]; /* Name of process */
292 peersize
= sizeof(peerpid
);
293 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
296 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
297 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
298 "Accepted from %s (Domain ???[%d])",
299 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
301 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
302 "Accepted from %s (Domain %s[%d])",
303 httpGetHostname(con
->http
, NULL
, 0), name
, (int)peerpid
);
306 # endif /* __APPLE__ */
308 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
309 httpGetHostname(con
->http
, NULL
, 0));
312 #endif /* AF_LOCAL */
313 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
314 httpGetHostname(con
->http
, NULL
, 0),
315 httpAddrPort(httpGetAddress(con
->http
)),
316 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
319 * Get the local address the client connected to...
322 addrlen
= sizeof(temp
);
323 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
325 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
328 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
329 con
->serverport
= LocalPort
;
332 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
334 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
335 con
->serverport
= LocalPort
;
337 #endif /* AF_LOCAL */
340 if (httpAddrLocalhost(&temp
))
341 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
342 else if (HostNameLookups
)
343 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
345 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
347 con
->serverport
= httpAddrPort(&(lis
->address
));
351 * Add the connection to the array of active clients...
354 cupsArrayAdd(Clients
, con
);
357 * Add the socket to the server select.
360 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
363 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
366 * Temporarily suspend accept()'s until we lose a client...
369 if (cupsArrayCount(Clients
) == MaxClients
)
370 cupsdPauseListening();
374 * See if we are connecting on a secure port...
377 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
380 * https connection; go secure...
383 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
384 cupsdCloseClient(con
);
388 #endif /* HAVE_SSL */
393 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
397 cupsdCloseAllClients(void)
399 cupsd_client_t
*con
; /* Current client */
402 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
403 cupsArrayCount(Clients
));
405 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
407 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
408 if (cupsdCloseClient(con
))
409 cupsdCloseClient(con
);
414 * 'cupsdCloseClient()' - Close a remote client.
417 int /* O - 1 if partial close, 0 if fully closed */
418 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
420 int partial
; /* Do partial close for SSL? */
422 #elif defined(HAVE_GNUTLS)
423 # elif defined(HAVE_CDSASSL)
424 #endif /* HAVE_LIBSSL */
427 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
430 * Flush pending writes before closing...
433 httpFlushWrite(con
->http
);
437 if (con
->pipe_pid
!= 0)
440 * Stop any CGI process...
443 cupsdEndProcess(con
->pipe_pid
, 1);
449 cupsdRemoveSelect(con
->file
);
456 * Close the socket and clear the file from the input set for select()...
459 if (httpGetFd(con
->http
) >= 0)
461 cupsArrayRemove(ActiveClients
, con
);
466 * Shutdown encryption as needed...
469 if (httpIsEncrypted(con
->http
))
471 #endif /* HAVE_SSL */
476 * Only do a partial close so that the encrypted client gets everything.
479 httpShutdown(con
->http
);
480 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
483 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
488 * Shut the socket down fully...
491 cupsdRemoveSelect(httpGetFd(con
->http
));
492 httpClose(con
->http
);
503 cupsdRemoveSelect(httpGetFd(con
->http
));
505 httpClose(con
->http
);
507 cupsdClearString(&con
->filename
);
508 cupsdClearString(&con
->command
);
509 cupsdClearString(&con
->options
);
510 cupsdClearString(&con
->query_string
);
514 ippDelete(con
->request
);
520 ippDelete(con
->response
);
521 con
->response
= NULL
;
526 cupsLangFree(con
->language
);
527 con
->language
= NULL
;
530 #ifdef HAVE_AUTHORIZATION_H
533 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
536 #endif /* HAVE_AUTHORIZATION_H */
539 * Re-enable new client connections if we are going back under the
543 if (cupsArrayCount(Clients
) == MaxClients
)
544 cupsdResumeListening();
547 * Compact the list of clients as necessary...
550 cupsArrayRemove(Clients
, con
);
560 * 'cupsdReadClient()' - Read data from a client.
564 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
566 char line
[32768], /* Line from client... */
567 locale
[64], /* Locale */
568 *ptr
; /* Pointer into strings */
569 http_status_t status
; /* Transfer status */
570 ipp_state_t ipp_state
; /* State of IPP transfer */
571 int bytes
; /* Number of bytes to POST */
572 char *filename
; /* Name of file for GET/HEAD */
573 char buf
[1024]; /* Buffer for real filename */
574 struct stat filestats
; /* File information */
575 mime_type_t
*type
; /* MIME type of file */
576 cupsd_printer_t
*p
; /* Printer */
577 static unsigned request_id
= 0; /* Request ID for temp files */
580 status
= HTTP_STATUS_CONTINUE
;
582 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
587 "data_encoding=HTTP_ENCODING_%s, "
588 "data_remaining=" CUPS_LLFMT
", "
591 httpError(con
->http
), (int)httpGetReady(con
->http
),
592 httpStateString(httpGetState(con
->http
)),
593 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
594 CUPS_LLCAST
httpGetRemaining(con
->http
),
596 con
->request
? ippStateString(ippGetState(con
->request
)) : "",
599 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
600 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
601 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
604 * If we get called in the wrong state, then something went wrong with the
605 * connection and we need to shut it down...
608 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.",
609 httpStateString(httpGetState(con
->http
)));
610 cupsdCloseClient(con
);
619 * Automatically check for a SSL/TLS handshake...
624 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
625 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
628 * Encrypt this connection...
631 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
632 "Saw first byte %02X, auto-negotiating "
633 "SSL/TLS session.", buf
[0] & 255);
635 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
636 cupsdCloseClient(con
);
641 #endif /* HAVE_SSL */
643 switch (httpGetState(con
->http
))
645 case HTTP_STATE_WAITING
:
647 * See if we've received a request line...
650 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
651 if (con
->operation
== HTTP_STATE_ERROR
||
652 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
653 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
655 if (httpError(con
->http
))
656 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
657 "HTTP_STATE_WAITING Closing for error %d (%s)",
658 httpError(con
->http
), strerror(httpError(con
->http
)));
660 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
661 "HTTP_STATE_WAITING Closing on error: %s",
662 cupsLastErrorString());
664 cupsdCloseClient(con
);
669 * Ignore blank request lines...
672 if (con
->operation
== HTTP_STATE_WAITING
)
676 * Clear other state variables...
683 con
->username
[0] = '\0';
684 con
->password
[0] = '\0';
686 cupsdClearString(&con
->command
);
687 cupsdClearString(&con
->options
);
688 cupsdClearString(&con
->query_string
);
692 ippDelete(con
->request
);
698 ippDelete(con
->response
);
699 con
->response
= NULL
;
704 cupsLangFree(con
->language
);
705 con
->language
= NULL
;
711 #endif /* HAVE_GSSAPI */
714 * Handle full URLs in the request line...
717 if (strcmp(con
->uri
, "*"))
719 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
720 userpass
[HTTP_MAX_URI
], /* Username:password */
721 hostname
[HTTP_MAX_URI
], /* Hostname */
722 resource
[HTTP_MAX_URI
]; /* Resource path */
723 int port
; /* Port number */
726 * Separate the URI into its components...
729 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
730 scheme
, sizeof(scheme
),
731 userpass
, sizeof(userpass
),
732 hostname
, sizeof(hostname
), &port
,
733 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
735 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
737 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
738 cupsdCloseClient(con
);
743 * Only allow URIs with the servername, localhost, or an IP
747 if (strcmp(scheme
, "file") &&
748 _cups_strcasecmp(hostname
, ServerName
) &&
749 _cups_strcasecmp(hostname
, "localhost") &&
750 !cupsArrayFind(ServerAlias
, hostname
) &&
751 !isdigit(hostname
[0]) && hostname
[0] != '[')
754 * Nope, we don't do proxies...
757 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
759 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
760 cupsdCloseClient(con
);
765 * Copy the resource portion back into the URI; both resource and
766 * con->uri are HTTP_MAX_URI bytes in size...
769 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
773 * Process the request...
776 gettimeofday(&(con
->start
), NULL
);
778 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
779 httpStateString(con
->operation
) + 11, con
->uri
,
780 httpGetVersion(con
->http
) / 100,
781 httpGetVersion(con
->http
) % 100);
783 if (!cupsArrayFind(ActiveClients
, con
))
785 cupsArrayAdd(ActiveClients
, con
);
789 case HTTP_STATE_OPTIONS
:
790 case HTTP_STATE_DELETE
:
791 case HTTP_STATE_GET
:
792 case HTTP_STATE_HEAD
:
793 case HTTP_STATE_POST
:
794 case HTTP_STATE_PUT
:
795 case HTTP_STATE_TRACE
:
797 * Parse incoming parameters until the status changes...
800 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
801 if (!httpGetReady(con
->http
))
804 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
806 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
807 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
808 "Closing for error %d (%s) while reading headers.",
809 httpError(con
->http
), strerror(httpError(con
->http
)));
811 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
812 "Closing on EOF while reading headers.");
814 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
815 cupsdCloseClient(con
);
821 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
824 * Connection closed...
827 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
828 cupsdCloseClient(con
);
831 break; /* Anti-compiler-warning-code */
835 * Handle new transfers...
838 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d", status
);
840 if (status
== HTTP_STATUS_OK
)
842 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
845 * Figure out the locale from the Accept-Language and Content-Type
849 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
853 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
857 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
858 "charset=")) != NULL
)
861 * Combine language and charset, and trim any extra params in the
865 snprintf(locale
, sizeof(locale
), "%s.%s",
866 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
868 if ((ptr
= strchr(locale
, ',')) != NULL
)
872 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
873 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
875 con
->language
= cupsLangGet(locale
);
878 con
->language
= cupsLangGet(DefaultLocale
);
882 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
883 "Keep-Alive", 10) && KeepAlive
)
884 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
885 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
887 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
889 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
890 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
893 * HTTP/1.1 and higher require the "Host:" field...
896 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
898 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
899 cupsdCloseClient(con
);
903 else if (!valid_host(con
))
906 * Access to localhost must use "localhost" or the corresponding IPv4
907 * or IPv6 values in the Host: field.
910 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
911 "Request from \"%s\" using invalid Host: field \"%s\".",
912 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
914 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
916 cupsdCloseClient(con
);
920 else if (con
->operation
== HTTP_STATE_OPTIONS
)
923 * Do OPTIONS command...
926 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
928 httpClearFields(con
->http
);
930 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
932 cupsdCloseClient(con
);
937 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
938 !httpIsEncrypted(con
->http
))
942 * Do encryption stuff...
945 httpClearFields(con
->http
);
947 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
949 cupsdCloseClient(con
);
953 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
955 cupsdCloseClient(con
);
959 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
961 cupsdCloseClient(con
);
964 #endif /* HAVE_SSL */
967 httpClearFields(con
->http
);
968 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
969 "GET, HEAD, OPTIONS, POST, PUT");
970 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
972 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
974 cupsdCloseClient(con
);
978 else if (!is_path_absolute(con
->uri
))
981 * Protect against malicious users!
984 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
985 "Request for non-absolute resource \"%s\".", con
->uri
);
987 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
989 cupsdCloseClient(con
);
995 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
996 "Upgrade") && !httpIsEncrypted(con
->http
))
1000 * Do encryption stuff...
1003 httpClearFields(con
->http
);
1005 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1008 cupsdCloseClient(con
);
1012 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
1014 cupsdCloseClient(con
);
1018 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1020 cupsdCloseClient(con
);
1023 #endif /* HAVE_SSL */
1026 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1028 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1029 cupsdCloseClient(con
);
1033 if (httpGetExpect(con
->http
) &&
1034 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1036 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1039 * Send 100-continue header...
1042 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1044 cupsdCloseClient(con
);
1051 * Send 417-expectation-failed header...
1054 httpClearFields(con
->http
);
1055 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1057 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1058 cupsdCloseClient(con
);
1063 switch (httpGetState(con
->http
))
1065 case HTTP_STATE_GET_SEND
:
1066 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1068 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1069 !strncmp(con
->uri
, "/printers/", 10) ||
1070 !strncmp(con
->uri
, "/classes/", 9)) &&
1071 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1074 * Send PPD file - get the real printer name since printer
1075 * names are not case sensitive but filenames can be...
1078 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1080 if (!strncmp(con
->uri
, "/ppd/", 5))
1081 p
= cupsdFindPrinter(con
->uri
+ 5);
1082 else if (!strncmp(con
->uri
, "/printers/", 10))
1083 p
= cupsdFindPrinter(con
->uri
+ 10);
1086 p
= cupsdFindClass(con
->uri
+ 9);
1090 int i
; /* Looping var */
1092 for (i
= 0; i
< p
->num_printers
; i
++)
1094 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1096 char ppdname
[1024];/* PPD filename */
1098 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1099 ServerRoot
, p
->printers
[i
]->name
);
1100 if (!access(ppdname
, 0))
1108 if (i
>= p
->num_printers
)
1115 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1119 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1121 cupsdCloseClient(con
);
1128 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1129 !strncmp(con
->uri
, "/printers/", 10) ||
1130 !strncmp(con
->uri
, "/classes/", 9)) &&
1131 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1134 * Send icon file - get the real queue name since queue names are
1135 * not case sensitive but filenames can be...
1138 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1140 if (!strncmp(con
->uri
, "/icons/", 7))
1141 p
= cupsdFindPrinter(con
->uri
+ 7);
1142 else if (!strncmp(con
->uri
, "/printers/", 10))
1143 p
= cupsdFindPrinter(con
->uri
+ 10);
1146 p
= cupsdFindClass(con
->uri
+ 9);
1150 int i
; /* Looping var */
1152 for (i
= 0; i
< p
->num_printers
; i
++)
1154 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1156 char ppdname
[1024];/* PPD filename */
1158 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1159 ServerRoot
, p
->printers
[i
]->name
);
1160 if (!access(ppdname
, 0))
1168 if (i
>= p
->num_printers
)
1174 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1177 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1179 cupsdCloseClient(con
);
1186 else if (!WebInterface
)
1189 * Web interface is disabled. Show an appropriate message...
1192 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1194 cupsdCloseClient(con
);
1201 if ((!strncmp(con
->uri
, "/admin", 6) &&
1202 strncmp(con
->uri
, "/admin/conf/", 12) &&
1203 strncmp(con
->uri
, "/admin/log/", 11)) ||
1204 !strncmp(con
->uri
, "/printers", 9) ||
1205 !strncmp(con
->uri
, "/classes", 8) ||
1206 !strncmp(con
->uri
, "/help", 5) ||
1207 !strncmp(con
->uri
, "/jobs", 5))
1210 * Send CGI output...
1213 if (!strncmp(con
->uri
, "/admin", 6))
1215 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1218 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1220 else if (!strncmp(con
->uri
, "/printers", 9))
1222 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1225 if (con
->uri
[9] && con
->uri
[10])
1226 cupsdSetString(&con
->options
, con
->uri
+ 9);
1228 cupsdSetString(&con
->options
, NULL
);
1230 else if (!strncmp(con
->uri
, "/classes", 8))
1232 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1235 if (con
->uri
[8] && con
->uri
[9])
1236 cupsdSetString(&con
->options
, con
->uri
+ 8);
1238 cupsdSetString(&con
->options
, NULL
);
1240 else if (!strncmp(con
->uri
, "/jobs", 5))
1242 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1245 if (con
->uri
[5] && con
->uri
[6])
1246 cupsdSetString(&con
->options
, con
->uri
+ 5);
1248 cupsdSetString(&con
->options
, NULL
);
1252 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1255 if (con
->uri
[5] && con
->uri
[6])
1256 cupsdSetString(&con
->options
, con
->uri
+ 5);
1258 cupsdSetString(&con
->options
, NULL
);
1261 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1263 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1265 cupsdCloseClient(con
);
1270 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1272 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1273 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1275 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1276 (strchr(con
->uri
+ 12, '/') ||
1277 strlen(con
->uri
) == 12)) ||
1278 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1279 (strchr(con
->uri
+ 11, '/') ||
1280 strlen(con
->uri
) == 11)))
1283 * GET can only be done to configuration files directly under
1287 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1288 "Request for subdirectory \"%s\"!", con
->uri
);
1290 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1292 cupsdCloseClient(con
);
1304 if ((filename
= get_file(con
, &filestats
, buf
,
1305 sizeof(buf
))) == NULL
)
1307 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1309 cupsdCloseClient(con
);
1316 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1318 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1320 if (is_cgi(con
, filename
, &filestats
, type
))
1323 * Note: con->command and con->options were set by
1327 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1329 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1331 cupsdCloseClient(con
);
1336 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1338 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1339 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1343 if (!check_if_modified(con
, &filestats
))
1345 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1347 cupsdCloseClient(con
);
1354 strlcpy(line
, "text/plain", sizeof(line
));
1356 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1358 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1360 cupsdCloseClient(con
);
1367 case HTTP_STATE_POST_RECV
:
1369 * See if the POST request includes a Content-Length field, and if
1370 * so check the length against any limits that are set...
1373 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1374 MaxRequestSize
> 0 &&
1375 httpGetLength2(con
->http
) > MaxRequestSize
)
1378 * Request too large...
1381 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1383 cupsdCloseClient(con
);
1389 else if (httpGetLength2(con
->http
) < 0)
1392 * Negative content lengths are invalid!
1395 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1397 cupsdCloseClient(con
);
1405 * See what kind of POST request this is; for IPP requests the
1406 * content-type field will be "application/ipp"...
1409 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1411 con
->request
= ippNew();
1412 else if (!WebInterface
)
1415 * Web interface is disabled. Show an appropriate message...
1418 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1420 cupsdCloseClient(con
);
1426 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1427 strncmp(con
->uri
, "/admin/conf/", 12) &&
1428 strncmp(con
->uri
, "/admin/log/", 11)) ||
1429 !strncmp(con
->uri
, "/printers", 9) ||
1430 !strncmp(con
->uri
, "/classes", 8) ||
1431 !strncmp(con
->uri
, "/help", 5) ||
1432 !strncmp(con
->uri
, "/jobs", 5))
1438 if (!strncmp(con
->uri
, "/admin", 6))
1440 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1443 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1445 else if (!strncmp(con
->uri
, "/printers", 9))
1447 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1450 if (con
->uri
[9] && con
->uri
[10])
1451 cupsdSetString(&con
->options
, con
->uri
+ 9);
1453 cupsdSetString(&con
->options
, NULL
);
1455 else if (!strncmp(con
->uri
, "/classes", 8))
1457 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1460 if (con
->uri
[8] && con
->uri
[9])
1461 cupsdSetString(&con
->options
, con
->uri
+ 8);
1463 cupsdSetString(&con
->options
, NULL
);
1465 else if (!strncmp(con
->uri
, "/jobs", 5))
1467 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1470 if (con
->uri
[5] && con
->uri
[6])
1471 cupsdSetString(&con
->options
, con
->uri
+ 5);
1473 cupsdSetString(&con
->options
, NULL
);
1477 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1480 if (con
->uri
[5] && con
->uri
[6])
1481 cupsdSetString(&con
->options
, con
->uri
+ 5);
1483 cupsdSetString(&con
->options
, NULL
);
1486 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1487 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1495 if ((filename
= get_file(con
, &filestats
, buf
,
1496 sizeof(buf
))) == NULL
)
1498 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1500 cupsdCloseClient(con
);
1507 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1509 if (!is_cgi(con
, filename
, &filestats
, type
))
1512 * Only POST to CGI's...
1515 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1517 cupsdCloseClient(con
);
1524 case HTTP_STATE_PUT_RECV
:
1526 * Validate the resource name...
1529 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1532 * PUT can only be done to the cupsd.conf file...
1535 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1536 "Disallowed PUT request for \"%s\".", con
->uri
);
1538 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1540 cupsdCloseClient(con
);
1548 * See if the PUT request includes a Content-Length field, and if
1549 * so check the length against any limits that are set...
1552 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1553 MaxRequestSize
> 0 &&
1554 httpGetLength2(con
->http
) > MaxRequestSize
)
1557 * Request too large...
1560 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1562 cupsdCloseClient(con
);
1568 else if (httpGetLength2(con
->http
) < 0)
1571 * Negative content lengths are invalid!
1574 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1576 cupsdCloseClient(con
);
1584 * Open a temporary file to hold the request...
1587 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1589 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1593 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1594 "Unable to create request file \"%s\": %s",
1595 con
->filename
, strerror(errno
));
1597 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1599 cupsdCloseClient(con
);
1604 fchmod(con
->file
, 0640);
1605 fchown(con
->file
, RunUser
, Group
);
1606 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1609 case HTTP_STATE_DELETE
:
1610 case HTTP_STATE_TRACE
:
1611 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1612 cupsdCloseClient(con
);
1615 case HTTP_STATE_HEAD
:
1616 if (!strncmp(con
->uri
, "/printers/", 10) &&
1617 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1620 * Send PPD file - get the real printer name since printer
1621 * names are not case sensitive but filenames can be...
1624 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1626 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1627 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1630 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1632 cupsdCloseClient(con
);
1636 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1640 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1641 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1644 * Send PNG file - get the real printer name since printer
1645 * names are not case sensitive but filenames can be...
1648 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1650 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1651 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1654 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1656 cupsdCloseClient(con
);
1660 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1664 else if (!WebInterface
)
1666 httpClearFields(con
->http
);
1668 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1670 cupsdCloseClient(con
);
1674 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1678 if ((!strncmp(con
->uri
, "/admin", 6) &&
1679 strncmp(con
->uri
, "/admin/conf/", 12) &&
1680 strncmp(con
->uri
, "/admin/log/", 11)) ||
1681 !strncmp(con
->uri
, "/printers", 9) ||
1682 !strncmp(con
->uri
, "/classes", 8) ||
1683 !strncmp(con
->uri
, "/help", 5) ||
1684 !strncmp(con
->uri
, "/jobs", 5))
1690 httpClearFields(con
->http
);
1692 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1694 cupsdCloseClient(con
);
1698 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1700 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1701 (strchr(con
->uri
+ 12, '/') ||
1702 strlen(con
->uri
) == 12)) ||
1703 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1704 (strchr(con
->uri
+ 11, '/') ||
1705 strlen(con
->uri
) == 11)))
1708 * HEAD can only be done to configuration files under
1712 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1713 "Request for subdirectory \"%s\".", con
->uri
);
1715 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1717 cupsdCloseClient(con
);
1721 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1724 else if ((filename
= get_file(con
, &filestats
, buf
,
1725 sizeof(buf
))) == NULL
)
1727 httpClearFields(con
->http
);
1729 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1732 cupsdCloseClient(con
);
1736 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1738 else if (!check_if_modified(con
, &filestats
))
1740 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1742 cupsdCloseClient(con
);
1746 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1754 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1756 strlcpy(line
, "text/plain", sizeof(line
));
1758 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1760 httpClearFields(con
->http
);
1762 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1763 httpGetDateString(filestats
.st_mtime
));
1764 httpSetLength(con
->http
, filestats
.st_size
);
1766 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1768 cupsdCloseClient(con
);
1772 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1777 break; /* Anti-compiler-warning-code */
1783 * Handle any incoming data...
1786 switch (httpGetState(con
->http
))
1788 case HTTP_STATE_PUT_RECV
:
1791 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1793 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1794 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1795 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1796 httpError(con
->http
), strerror(httpError(con
->http
)));
1798 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1799 "HTTP_STATE_PUT_RECV Closing on EOF.");
1801 cupsdCloseClient(con
);
1806 con
->bytes
+= bytes
;
1808 if (write(con
->file
, line
, bytes
) < bytes
)
1810 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1811 "Unable to write %d bytes to \"%s\": %s", bytes
,
1812 con
->filename
, strerror(errno
));
1816 unlink(con
->filename
);
1817 cupsdClearString(&con
->filename
);
1819 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1821 cupsdCloseClient(con
);
1827 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1829 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1832 * End of file, see how big it is...
1835 fstat(con
->file
, &filestats
);
1840 if (filestats
.st_size
> MaxRequestSize
&&
1844 * Request is too big; remove it and send an error...
1847 unlink(con
->filename
);
1848 cupsdClearString(&con
->filename
);
1850 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1852 cupsdCloseClient(con
);
1858 * Install the configuration file...
1861 status
= install_cupsd_conf(con
);
1864 * Return the status to the client...
1867 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1869 cupsdCloseClient(con
);
1875 case HTTP_STATE_POST_RECV
:
1878 if (con
->request
&& con
->file
< 0)
1881 * Grab any request data from the connection...
1884 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1886 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1887 cupsLastErrorString());
1889 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1890 cupsdCloseClient(con
);
1893 else if (ipp_state
!= IPP_STATE_DATA
)
1895 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1897 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1898 cupsdCloseClient(con
);
1902 if (httpGetReady(con
->http
))
1908 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1909 con
->request
->request
.op
.version
[0],
1910 con
->request
->request
.op
.version
[1],
1911 ippOpString(con
->request
->request
.op
.operation_id
),
1912 con
->request
->request
.op
.request_id
);
1913 con
->bytes
+= ippLength(con
->request
);
1917 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1920 * Create a file as needed for the request data...
1923 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1925 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1929 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1930 "Unable to create request file \"%s\": %s",
1931 con
->filename
, strerror(errno
));
1933 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1935 cupsdCloseClient(con
);
1940 fchmod(con
->file
, 0640);
1941 fchown(con
->file
, RunUser
, Group
);
1942 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1945 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1947 if (!httpWait(con
->http
, 0))
1949 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1951 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1952 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1953 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1954 httpError(con
->http
), strerror(httpError(con
->http
)));
1956 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1957 "HTTP_STATE_POST_SEND Closing on EOF.");
1959 cupsdCloseClient(con
);
1964 con
->bytes
+= bytes
;
1966 if (write(con
->file
, line
, bytes
) < bytes
)
1968 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1969 "Unable to write %d bytes to \"%s\": %s",
1970 bytes
, con
->filename
, strerror(errno
));
1974 unlink(con
->filename
);
1975 cupsdClearString(&con
->filename
);
1977 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1980 cupsdCloseClient(con
);
1985 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1987 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1989 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1990 "Closing on unexpected state %s.",
1991 httpStateString(httpGetState(con
->http
)));
1992 cupsdCloseClient(con
);
1997 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1999 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2003 fstat(con
->file
, &filestats
);
2008 if (filestats
.st_size
> MaxRequestSize
&&
2012 * Request is too big; remove it and send an error...
2015 unlink(con
->filename
);
2016 cupsdClearString(&con
->filename
);
2021 * Delete any IPP request data...
2024 ippDelete(con
->request
);
2025 con
->request
= NULL
;
2028 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2030 cupsdCloseClient(con
);
2034 else if (filestats
.st_size
== 0)
2037 * Don't allow empty file...
2040 unlink(con
->filename
);
2041 cupsdClearString(&con
->filename
);
2046 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2048 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2050 cupsdCloseClient(con
);
2055 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2061 cupsdProcessIPPRequest(con
);
2065 unlink(con
->filename
);
2066 cupsdClearString(&con
->filename
);
2075 break; /* Anti-compiler-warning-code */
2078 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2080 if (!httpGetKeepAlive(con
->http
))
2082 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2083 "Closing because Keep-Alive is disabled.");
2084 cupsdCloseClient(con
);
2088 cupsArrayRemove(ActiveClients
, con
);
2089 cupsdSetBusyState();
2096 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2099 int /* O - 1 on success, 0 on failure */
2101 cupsd_client_t
*con
, /* I - Client connection */
2102 char *command
, /* I - Command to run */
2103 char *options
, /* I - Command-line options */
2104 int root
) /* I - Run as root? */
2106 int fd
; /* Standard input file descriptor */
2111 fd
= open(con
->filename
, O_RDONLY
);
2115 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2116 "Unable to open \"%s\" for reading: %s",
2117 con
->filename
? con
->filename
: "/dev/null",
2122 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2127 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2128 con
->pipe_status
= HTTP_STATUS_OK
;
2130 httpClearFields(con
->http
);
2135 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2136 command
, con
->pipe_pid
, con
->file
);
2138 if (con
->pipe_pid
== 0)
2141 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2143 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2145 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2147 con
->sent_header
= 0;
2148 con
->file_ready
= 0;
2149 con
->got_fields
= 0;
2150 con
->header_used
= 0;
2157 * 'cupsdSendError()' - Send an error message via HTTP.
2160 int /* O - 1 if successful, 0 otherwise */
2161 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2162 http_status_t code
, /* I - Error code */
2163 int auth_type
)/* I - Authentication type */
2165 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2170 * Force client to upgrade for authentication if that is how the
2171 * server is configured...
2174 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2175 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2176 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2177 !httpIsEncrypted(con
->http
))
2179 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2181 #endif /* HAVE_SSL */
2184 * Put the request in the access_log file...
2187 cupsdLogRequest(con
, code
);
2190 * To work around bugs in some proxies, don't use Keep-Alive for some
2193 * Kerberos authentication doesn't work without Keep-Alive, so
2194 * never disable it in that case.
2197 httpClearFields(con
->http
);
2199 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2200 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2202 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2203 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2204 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2206 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2209 * Send a human-readable error message.
2212 char message
[4096], /* Message for user */
2213 urltext
[1024], /* URL redirection text */
2214 redirect
[1024]; /* Redirection link */
2215 const char *text
; /* Status-specific text */
2220 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2221 text
= _cupsLangString(con
->language
,
2222 _("Enter your username and password or the "
2223 "root username and password to access this "
2224 "page. If you are using Kerberos authentication, "
2225 "make sure you have a valid Kerberos ticket."));
2226 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2230 snprintf(urltext
, sizeof(urltext
),
2231 _cupsLangString(con
->language
,
2232 _("You must access this page using the URL "
2233 "<A HREF=\"https://%s:%d%s\">"
2234 "https://%s:%d%s</A>.")),
2235 con
->servername
, con
->serverport
, con
->uri
,
2236 con
->servername
, con
->serverport
, con
->uri
);
2238 snprintf(redirect
, sizeof(redirect
),
2239 "<META HTTP-EQUIV=\"Refresh\" "
2240 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2241 con
->servername
, con
->serverport
, con
->uri
);
2243 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2244 text
= _cupsLangString(con
->language
,
2245 _("The web interface is currently disabled. Run "
2246 "\"cupsctl WebInterface=yes\" to enable it."));
2250 snprintf(message
, sizeof(message
),
2251 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2252 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2255 "\t<META HTTP-EQUIV=\"Content-Type\" "
2256 "CONTENT=\"text/html; charset=utf-8\">\n"
2257 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2258 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2259 "HREF=\"/cups.css\">\n"
2267 _httpStatus(con
->language
, code
), redirect
,
2268 _httpStatus(con
->language
, code
), text
);
2271 * Send an error message back to the client. If the error code is a
2272 * 400 or 500 series, make sure the message contains some text, too!
2275 size_t length
= strlen(message
); /* Length of message */
2277 httpSetLength(con
->http
, length
);
2279 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2282 if (httpWrite2(con
->http
, message
, length
) < 0)
2285 if (httpFlushWrite(con
->http
) < 0)
2290 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2292 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2301 * 'cupsdSendHeader()' - Send an HTTP request.
2304 int /* O - 1 on success, 0 on failure */
2306 cupsd_client_t
*con
, /* I - Client to send to */
2307 http_status_t code
, /* I - HTTP status code */
2308 char *type
, /* I - MIME type of document */
2309 int auth_type
) /* I - Type of authentication */
2311 char auth_str
[1024]; /* Authorization string */
2315 * Send the HTTP status header...
2318 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2321 * Treat our special "web interface is disabled" status as "200 OK" for web
2325 code
= HTTP_STATUS_OK
;
2329 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2331 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2332 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2334 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2336 if (auth_type
== CUPSD_AUTH_NONE
)
2338 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2339 auth_type
= cupsdDefaultAuthType();
2341 auth_type
= con
->best
->type
;
2346 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2347 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2348 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2349 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2350 httpGetHostname(con
->http
, NULL
, 0));
2352 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2355 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2356 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2358 # endif /* AF_LOCAL */
2359 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2361 #endif /* HAVE_GSSAPI */
2363 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2364 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2367 * Add a "trc" (try root certification) parameter for local non-Kerberos
2368 * requests when the request requires system group membership - then the
2369 * client knows the root certificate can/should be used.
2371 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2372 * parameter as needed...
2375 char *name
, /* Current user name */
2376 *auth_key
; /* Auth key buffer */
2377 size_t auth_size
; /* Size of remaining buffer */
2379 auth_key
= auth_str
+ strlen(auth_str
);
2380 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2382 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2384 name
= (char *)cupsArrayNext(con
->best
->names
))
2386 #ifdef HAVE_AUTHORIZATION_H
2387 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2389 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2390 /* end parenthesis is stripped in conf.c */
2394 #endif /* HAVE_AUTHORIZATION_H */
2395 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2397 #ifdef HAVE_AUTHORIZATION_H
2398 if (SystemGroupAuthKey
)
2399 snprintf(auth_key
, auth_size
,
2401 SystemGroupAuthKey
);
2404 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2405 #endif /* HAVE_AUTHORIZATION_H */
2413 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2415 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2419 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2420 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2424 if (!strcmp(type
, "text/html"))
2425 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2427 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2430 return (!httpWriteResponse(con
->http
, code
));
2435 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2439 cupsdUpdateCGI(void)
2441 char *ptr
, /* Pointer to end of line in buffer */
2442 message
[1024]; /* Pointer to message text */
2443 int loglevel
; /* Log level for message */
2446 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2447 message
, sizeof(message
))) != NULL
)
2449 if (loglevel
== CUPSD_LOG_INFO
)
2450 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2452 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2456 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2459 * Fatal error on pipe - should never happen!
2462 cupsdLogMessage(CUPSD_LOG_CRIT
,
2463 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2470 * 'cupsdWriteClient()' - Write data to a client as needed.
2474 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2476 int bytes
, /* Number of bytes written */
2477 field_col
; /* Current column */
2478 char *bufptr
, /* Pointer into buffer */
2479 *bufend
; /* Pointer to end of buffer */
2480 ipp_state_t ipp_state
; /* IPP state value */
2483 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2484 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2489 "data_encoding=HTTP_ENCODING_%s, "
2490 "data_remaining=" CUPS_LLFMT
", "
2494 httpError(con
->http
), (int)httpGetReady(con
->http
),
2495 httpStateString(httpGetState(con
->http
)),
2496 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2497 CUPS_LLCAST
httpGetLength2(con
->http
),
2499 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2500 con
->pipe_pid
, con
->file
);
2502 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2503 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2506 * If we get called in the wrong state, then something went wrong with the
2507 * connection and we need to shut it down...
2510 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2511 httpStateString(httpGetState(con
->http
)));
2512 cupsdCloseClient(con
);
2519 * Make sure we select on the CGI output...
2522 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2524 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2526 if (!con
->file_ready
)
2529 * Try again later when there is CGI output available...
2532 cupsdRemoveSelect(httpGetFd(con
->http
));
2536 con
->file_ready
= 0;
2539 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2541 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2546 * Write a single attribute or the IPP message header...
2549 ipp_state
= ippWrite(con
->http
, con
->response
);
2552 * If the write buffer has been flushed, stop buffering up attributes...
2555 if (httpGetPending(con
->http
) <= wused
)
2558 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2560 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2561 "Writing IPP response, ipp_state=%s, old "
2562 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2563 ippStateString(ipp_state
),
2564 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2566 if (httpGetPending(con
->http
) > 0)
2567 httpFlushWrite(con
->http
);
2569 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2570 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2572 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2573 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2574 (int)bytes
, httpGetState(con
->http
),
2575 CUPS_LLCAST
httpGetLength2(con
->http
));
2577 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2578 sizeof(con
->header
) - con
->header_used
)) > 0)
2580 con
->header_used
+= bytes
;
2582 if (con
->pipe_pid
&& !con
->got_fields
)
2585 * Inspect the data for Content-Type and other fields.
2588 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2590 !con
->got_fields
&& bufptr
< bufend
;
2593 if (*bufptr
== '\n')
2596 * Send line to client...
2599 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2603 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2605 if (!con
->sent_header
)
2608 * Handle redirection and CGI status codes...
2611 http_field_t field
; /* HTTP field */
2612 char *value
= strchr(con
->header
, ':');
2613 /* Value of field */
2618 while (isspace(*value
& 255))
2622 field
= httpFieldValue(con
->header
);
2624 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2626 httpSetField(con
->http
, field
, value
);
2628 if (field
== HTTP_FIELD_LOCATION
)
2630 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2631 con
->sent_header
= 2;
2634 con
->sent_header
= 1;
2636 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2638 con
->pipe_status
= (http_status_t
)atoi(value
);
2639 con
->sent_header
= 2;
2641 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2643 char *sep
= strchr(value
, ';');
2644 /* Separator between name=value and the rest */
2649 httpSetCookie(con
->http
, value
);
2650 con
->sent_header
= 1;
2658 con
->header_used
-= bufptr
- con
->header
;
2660 if (con
->header_used
> 0)
2661 memmove(con
->header
, bufptr
, con
->header_used
);
2663 bufptr
= con
->header
- 1;
2666 * See if the line was empty...
2671 con
->got_fields
= 1;
2673 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2674 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2675 httpSetLength(con
->http
, 0);
2677 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2679 cupsdCloseClient(con
);
2686 else if (*bufptr
!= '\r')
2690 if (!con
->got_fields
)
2694 if (con
->header_used
> 0)
2696 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2698 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2699 httpError(con
->http
), strerror(httpError(con
->http
)));
2700 cupsdCloseClient(con
);
2704 if (httpIsChunked(con
->http
))
2705 httpFlushWrite(con
->http
);
2707 con
->bytes
+= con
->header_used
;
2709 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2712 bytes
= con
->header_used
;
2714 con
->header_used
= 0;
2719 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2720 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2722 if (!con
->sent_header
&& con
->pipe_pid
)
2723 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2726 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2728 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
== 1))
2730 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2732 if (httpWrite2(con
->http
, "", 0) < 0)
2734 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2735 httpError(con
->http
), strerror(httpError(con
->http
)));
2736 cupsdCloseClient(con
);
2741 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2742 httpFlushWrite(con
->http
);
2743 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2746 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2748 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2752 cupsdRemoveSelect(con
->file
);
2755 cupsdEndProcess(con
->pipe_pid
, 0);
2764 unlink(con
->filename
);
2765 cupsdClearString(&con
->filename
);
2770 ippDelete(con
->request
);
2771 con
->request
= NULL
;
2776 ippDelete(con
->response
);
2777 con
->response
= NULL
;
2780 cupsdClearString(&con
->command
);
2781 cupsdClearString(&con
->options
);
2782 cupsdClearString(&con
->query_string
);
2784 if (!httpGetKeepAlive(con
->http
))
2786 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2787 "Closing because Keep-Alive is disabled.");
2788 cupsdCloseClient(con
);
2793 cupsArrayRemove(ActiveClients
, con
);
2794 cupsdSetBusyState();
2801 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2804 static int /* O - 1 if modified since */
2806 cupsd_client_t
*con
, /* I - Client connection */
2807 struct stat
*filestats
) /* I - File information */
2809 const char *ptr
; /* Pointer into field */
2810 time_t date
; /* Time/date value */
2811 off_t size
; /* Size/length value */
2816 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2821 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2822 "check_if_modified "
2823 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2824 filestats
, CUPS_LLCAST filestats
->st_size
,
2825 (int)filestats
->st_mtime
, ptr
);
2827 while (*ptr
!= '\0')
2829 while (isspace(*ptr
) || *ptr
== ';')
2832 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2835 size
= strtoll(ptr
, NULL
, 10);
2837 while (isdigit(*ptr
))
2840 else if (isalpha(*ptr
))
2842 date
= httpGetDateTime(ptr
);
2843 while (*ptr
!= '\0' && *ptr
!= ';')
2850 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2851 (date
< filestats
->st_mtime
&& date
!= 0) ||
2852 (size
== 0 && date
== 0));
2857 * 'compare_clients()' - Compare two client connections.
2860 static int /* O - Result of comparison */
2861 compare_clients(cupsd_client_t
*a
, /* I - First client */
2862 cupsd_client_t
*b
, /* I - Second client */
2863 void *data
) /* I - User data (not used) */
2878 * 'cupsd_start_tls()' - Start encryption on a connection.
2881 static int /* O - 0 on success, -1 on error */
2882 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2883 http_encryption_t e
) /* I - Encryption mode */
2885 /* TODO: Lookup/load cert + key and set */
2886 if (httpEncryption(con
->http
, e
))
2888 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2889 cupsLastErrorString());
2893 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Connection now encrypted.");
2896 #endif /* HAVE_SSL */
2900 * 'get_file()' - Get a filename and state info.
2903 static char * /* O - Real filename */
2904 get_file(cupsd_client_t
*con
, /* I - Client connection */
2905 struct stat
*filestats
, /* O - File information */
2906 char *filename
, /* IO - Filename buffer */
2907 int len
) /* I - Buffer length */
2909 int status
; /* Status of filesystem calls */
2910 char *ptr
; /* Pointer info filename */
2911 int plen
; /* Remaining length after pointer */
2912 char language
[7]; /* Language subdirectory, if any */
2916 * Figure out the real filename...
2921 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2922 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2923 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2925 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
2926 if (access(filename
, F_OK
) < 0)
2927 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2929 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2930 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2931 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2932 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2933 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2935 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2936 strlcpy(filename
, AccessLog
, len
);
2937 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2938 strlcpy(filename
, ErrorLog
, len
);
2939 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2940 strlcpy(filename
, PageLog
, len
);
2944 else if (con
->language
)
2946 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2947 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2950 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2952 if ((ptr
= strchr(filename
, '?')) != NULL
)
2956 * Grab the status for this language; if there isn't a language-specific file
2957 * then fallback to the default one...
2960 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
2961 strncmp(con
->uri
, "/icons/", 7) &&
2962 strncmp(con
->uri
, "/ppd/", 5) &&
2963 strncmp(con
->uri
, "/rss/", 5) &&
2964 strncmp(con
->uri
, "/admin/conf/", 12) &&
2965 strncmp(con
->uri
, "/admin/log/", 11))
2968 * Drop the country code...
2972 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2974 if ((ptr
= strchr(filename
, '?')) != NULL
)
2977 if ((status
= stat(filename
, filestats
)) != 0)
2980 * Drop the language prefix and try the root directory...
2984 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2986 if ((ptr
= strchr(filename
, '?')) != NULL
)
2989 status
= stat(filename
, filestats
);
2994 * If we're found a directory, get the index.html file instead...
2997 if (!status
&& S_ISDIR(filestats
->st_mode
))
3000 * Make sure the URI ends with a slash...
3003 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3004 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3007 * Find the directory index file, trying every language...
3012 if (status
&& language
[0])
3015 * Try a different language subset...
3019 language
[0] = '\0'; /* Strip country code */
3021 language
[0] = '\0'; /* Strip language */
3025 * Look for the index file...
3028 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3030 if ((ptr
= strchr(filename
, '?')) != NULL
)
3033 ptr
= filename
+ strlen(filename
);
3034 plen
= len
- (ptr
- filename
);
3036 strlcpy(ptr
, "index.html", plen
);
3037 status
= stat(filename
, filestats
);
3042 strlcpy(ptr
, "index.class", plen
);
3043 status
= stat(filename
, filestats
);
3045 #endif /* HAVE_JAVA */
3050 strlcpy(ptr
, "index.pl", plen
);
3051 status
= stat(filename
, filestats
);
3053 #endif /* HAVE_PERL */
3058 strlcpy(ptr
, "index.php", plen
);
3059 status
= stat(filename
, filestats
);
3061 #endif /* HAVE_PHP */
3066 strlcpy(ptr
, "index.pyc", plen
);
3067 status
= stat(filename
, filestats
);
3072 strlcpy(ptr
, "index.py", plen
);
3073 status
= stat(filename
, filestats
);
3075 #endif /* HAVE_PYTHON */
3078 while (status
&& language
[0]);
3081 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3082 "get_file filestats=%p, filename=%p, len=%d, "
3083 "returning \"%s\".", filestats
, filename
, len
,
3084 status
? "(null)" : filename
);
3094 * 'install_cupsd_conf()' - Install a configuration file.
3097 static http_status_t
/* O - Status */
3098 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3100 char filename
[1024]; /* Configuration filename */
3101 cups_file_t
*in
, /* Input file */
3102 *out
; /* Output file */
3103 char buffer
[16384]; /* Copy buffer */
3104 ssize_t bytes
; /* Number of bytes */
3108 * Open the request file...
3111 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3113 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3114 con
->filename
, strerror(errno
));
3115 return (HTTP_STATUS_SERVER_ERROR
);
3119 * Open the new config file...
3122 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3125 return (HTTP_STATUS_SERVER_ERROR
);
3128 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3132 * Copy from the request to the new config file...
3135 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3136 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3138 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3139 "Unable to copy to config file \"%s\": %s",
3140 ConfigurationFile
, strerror(errno
));
3145 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3146 cupsdUnlinkOrRemoveFile(filename
);
3148 return (HTTP_STATUS_SERVER_ERROR
);
3152 * Close the files...
3157 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3158 return (HTTP_STATUS_SERVER_ERROR
);
3161 * Remove the request file...
3164 cupsdUnlinkOrRemoveFile(con
->filename
);
3165 cupsdClearString(&con
->filename
);
3168 * Set the NeedReload flag...
3171 NeedReload
= RELOAD_CUPSD
;
3172 ReloadTime
= time(NULL
);
3175 * Return that the file was created successfully...
3178 return (HTTP_STATUS_CREATED
);
3183 * 'is_cgi()' - Is the resource a CGI script/program?
3186 static int /* O - 1 = CGI, 0 = file */
3187 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3188 const char *filename
, /* I - Real filename */
3189 struct stat
*filestats
, /* I - File information */
3190 mime_type_t
*type
) /* I - MIME type */
3192 const char *options
; /* Options on URL */
3196 * Get the options, if any...
3199 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3202 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3206 * Check for known types...
3209 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3211 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3212 "is_cgi filename=\"%s\", filestats=%p, "
3213 "type=%s/%s, returning 0", filename
,
3214 filestats
, type
? type
->super
: "unknown",
3215 type
? type
->type
: "unknown");
3219 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3220 (filestats
->st_mode
& 0111))
3223 * "application/x-httpd-cgi" is a CGI script.
3226 cupsdSetString(&con
->command
, filename
);
3229 cupsdSetStringf(&con
->options
, " %s", options
);
3231 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3232 "is_cgi filename=\"%s\", filestats=%p, "
3233 "type=%s/%s, returning 1", filename
,
3234 filestats
, type
->super
, type
->type
);
3238 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3241 * "application/x-httpd-java" is a Java servlet.
3244 cupsdSetString(&con
->command
, CUPS_JAVA
);
3247 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3249 cupsdSetStringf(&con
->options
, " %s", filename
);
3251 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3252 "is_cgi filename=\"%s\", filestats=%p, "
3253 "type=%s/%s, returning 1", filename
,
3254 filestats
, type
->super
, type
->type
);
3257 #endif /* HAVE_JAVA */
3259 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3262 * "application/x-httpd-perl" is a Perl page.
3265 cupsdSetString(&con
->command
, CUPS_PERL
);
3268 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3270 cupsdSetStringf(&con
->options
, " %s", filename
);
3272 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3273 "is_cgi filename=\"%s\", filestats=%p, "
3274 "type=%s/%s, returning 1", filename
,
3275 filestats
, type
->super
, type
->type
);
3278 #endif /* HAVE_PERL */
3280 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3283 * "application/x-httpd-php" is a PHP page.
3286 cupsdSetString(&con
->command
, CUPS_PHP
);
3289 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3291 cupsdSetStringf(&con
->options
, " %s", filename
);
3293 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3294 "is_cgi filename=\"%s\", filestats=%p, "
3295 "type=%s/%s, returning 1", filename
,
3296 filestats
, type
->super
, type
->type
);
3299 #endif /* HAVE_PHP */
3301 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3304 * "application/x-httpd-python" is a Python page.
3307 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3310 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3312 cupsdSetStringf(&con
->options
, " %s", filename
);
3314 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3315 "is_cgi filename=\"%s\", filestats=%p, "
3316 "type=%s/%s, returning 1", filename
,
3317 filestats
, type
->super
, type
->type
);
3320 #endif /* HAVE_PYTHON */
3322 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3323 "is_cgi filename=\"%s\", filestats=%p, "
3324 "type=%s/%s, returning 0", filename
,
3325 filestats
, type
->super
, type
->type
);
3331 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3334 static int /* O - 0 if relative, 1 if absolute */
3335 is_path_absolute(const char *path
) /* I - Input path */
3338 * Check for a leading slash...
3345 * Check for "/.." in the path...
3348 while ((path
= strstr(path
, "/..")) != NULL
)
3350 if (!path
[3] || path
[3] == '/')
3357 * If we haven't found any relative paths, return 1 indicating an
3366 * 'pipe_command()' - Pipe the output of a command to the remote client.
3369 static int /* O - Process ID */
3370 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3371 int infile
, /* I - Standard input for command */
3372 int *outfile
, /* O - Standard output for command */
3373 char *command
, /* I - Command to run */
3374 char *options
, /* I - Options for command */
3375 int root
) /* I - Run as root? */
3377 int i
; /* Looping var */
3378 int pid
; /* Process ID */
3379 char *commptr
, /* Command string pointer */
3380 commch
; /* Command string character */
3381 char *uriptr
; /* URI string pointer */
3382 int fds
[2]; /* Pipe FDs */
3383 int argc
; /* Number of arguments */
3384 int envc
; /* Number of environment variables */
3385 char argbuf
[10240], /* Argument buffer */
3386 *argv
[100], /* Argument strings */
3387 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3388 char auth_type
[256], /* AUTH_TYPE environment variable */
3389 content_length
[1024], /* CONTENT_LENGTH environment variable */
3390 content_type
[1024], /* CONTENT_TYPE environment variable */
3391 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3392 http_referer
[1024], /* HTTP_REFERER environment variable */
3393 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3394 lang
[1024], /* LANG environment variable */
3395 path_info
[1024], /* PATH_INFO environment variable */
3396 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3397 remote_host
[1024], /* REMOTE_HOST environment variable */
3398 remote_user
[1024], /* REMOTE_USER environment variable */
3399 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3400 script_name
[1024], /* SCRIPT_NAME environment variable */
3401 server_name
[1024], /* SERVER_NAME environment variable */
3402 server_port
[1024]; /* SERVER_PORT environment variable */
3403 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3407 * Parse a copy of the options string, which is of the form:
3409 * argument+argument+argument
3410 * ?argument+argument+argument
3411 * param=value¶m=value
3412 * ?param=value¶m=value
3413 * /name?argument+argument+argument
3414 * /name?param=value¶m=value
3416 * If the string contains an "=" character after the initial name,
3417 * then we treat it as a HTTP GET form request and make a copy of
3418 * the remaining string for the environment variable.
3420 * The string is always parsed out as command-line arguments, to
3421 * be consistent with Apache...
3424 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3425 "pipe_command infile=%d, outfile=%p, "
3426 "command=\"%s\", options=\"%s\", root=%d",
3427 infile
, outfile
, command
,
3428 options
? options
: "(null)", root
);
3435 if (*commptr
== ' ')
3437 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3442 if (argbuf
[0] == '/')
3445 * Found some trailing path information, set PATH_INFO...
3448 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3449 commptr
= argbuf
+ strlen(argbuf
);
3453 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3459 path_info
[0] = '\0';
3461 if (*commptr
== ' ')
3465 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3468 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3475 argv
[argc
++] = commptr
;
3477 for (; *commptr
&& argc
< 99; commptr
++)
3480 * Break arguments whenever we see a + or space...
3483 if (*commptr
== ' ' || *commptr
== '+')
3485 while (*commptr
== ' ' || *commptr
== '+')
3489 * If we don't have a blank string, save it as another argument...
3494 argv
[argc
] = commptr
;
3500 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3501 isxdigit(commptr
[2] & 255))
3504 * Convert the %xx notation to the individual character.
3507 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3508 *commptr
= (commptr
[1] - '0') << 4;
3510 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3512 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3513 *commptr
|= commptr
[2] - '0';
3515 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3517 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3520 * Check for a %00 and break if that is the case...
3532 * Setup the environment variables as needed...
3535 if (con
->username
[0])
3537 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3538 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3540 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3544 auth_type
[0] = '\0';
3547 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3548 IPP_TAG_LANGUAGE
)) != NULL
)
3550 switch (strlen(attr
->values
[0].string
.text
))
3554 * This is an unknown or badly formatted language code; use
3555 * the POSIX locale...
3558 strlcpy(lang
, "LANG=C", sizeof(lang
));
3563 * Just the language code (ll)...
3566 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3567 attr
->values
[0].string
.text
);
3572 * Language and country code (ll-cc)...
3575 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3576 attr
->values
[0].string
.text
[0],
3577 attr
->values
[0].string
.text
[1],
3578 toupper(attr
->values
[0].string
.text
[3] & 255),
3579 toupper(attr
->values
[0].string
.text
[4] & 255));
3583 else if (con
->language
)
3584 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3586 strlcpy(lang
, "LANG=C", sizeof(lang
));
3588 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3589 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3590 sizeof(remote_addr
) - 12);
3592 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3593 httpGetHostname(con
->http
, NULL
, 0));
3595 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3596 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3599 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3600 DocumentRoot
, script_name
+ 12);
3602 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3604 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3606 char *nameptr
; /* Pointer to ":port" */
3608 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3609 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3610 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3611 *nameptr
= '\0'; /* Strip trailing ":port" */
3614 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3617 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3620 envp
[envc
++] = auth_type
;
3622 envp
[envc
++] = lang
;
3623 envp
[envc
++] = "REDIRECT_STATUS=1";
3624 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3625 envp
[envc
++] = server_name
;
3626 envp
[envc
++] = server_port
;
3627 envp
[envc
++] = remote_addr
;
3628 envp
[envc
++] = remote_host
;
3629 envp
[envc
++] = script_name
;
3630 envp
[envc
++] = script_filename
;
3633 envp
[envc
++] = path_info
;
3635 if (con
->username
[0])
3637 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3639 envp
[envc
++] = remote_user
;
3642 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3643 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3644 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3645 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3647 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3649 if (httpGetCookie(con
->http
))
3651 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3652 httpGetCookie(con
->http
));
3653 envp
[envc
++] = http_cookie
;
3656 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3658 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3659 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3660 envp
[envc
++] = http_user_agent
;
3663 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3665 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3666 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3667 envp
[envc
++] = http_referer
;
3670 if (con
->operation
== HTTP_STATE_GET
)
3672 envp
[envc
++] = "REQUEST_METHOD=GET";
3674 if (con
->query_string
)
3677 * Add GET form variables after ?...
3680 envp
[envc
++] = con
->query_string
;
3683 envp
[envc
++] = "QUERY_STRING=";
3687 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3688 CUPS_LLCAST con
->bytes
);
3689 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3690 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3692 envp
[envc
++] = "REQUEST_METHOD=POST";
3693 envp
[envc
++] = content_length
;
3694 envp
[envc
++] = content_type
;
3698 * Tell the CGI if we are using encryption...
3701 if (httpIsEncrypted(con
->http
))
3702 envp
[envc
++] = "HTTPS=ON";
3705 * Terminate the environment array...
3710 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3712 for (i
= 0; i
< argc
; i
++)
3713 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3714 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3715 for (i
= 0; i
< envc
; i
++)
3716 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3717 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3721 * Create a pipe for the output...
3724 if (cupsdOpenPipe(fds
))
3726 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3727 argv
[0], strerror(errno
));
3732 * Then execute the command...
3735 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3736 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3739 * Error - can't fork!
3742 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3745 cupsdClosePipe(fds
);
3751 * Fork successful - return the PID...
3754 if (con
->username
[0])
3755 cupsdAddCert(pid
, con
->username
, con
->type
);
3757 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3768 * 'valid_host()' - Is the Host: field valid?
3771 static int /* O - 1 if valid, 0 if not */
3772 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3774 cupsd_alias_t
*a
; /* Current alias */
3775 cupsd_netif_t
*netif
; /* Current network interface */
3776 const char *end
; /* End character */
3777 char *ptr
; /* Pointer into host value */
3781 * Copy the Host: header for later use...
3784 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3785 sizeof(con
->clientname
));
3786 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3789 con
->clientport
= atoi(ptr
);
3792 con
->clientport
= con
->serverport
;
3798 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3801 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3802 * addresses when accessing CUPS via the loopback interface...
3805 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3806 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3808 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3809 #endif /* __linux */
3810 !strcmp(con
->clientname
, "127.0.0.1") ||
3811 !strcmp(con
->clientname
, "[::1]"));
3814 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3816 * Check if the hostname is something.local (Bonjour); if so, allow it.
3819 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3823 * "." on end, work back to second-to-last "."...
3826 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3829 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3830 !_cups_strcasecmp(end
, ".local.")))
3832 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3835 * Check if the hostname is an IP address...
3838 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3841 * Possible IPv4/IPv6 address...
3844 http_addrlist_t
*addrlist
; /* List of addresses */
3847 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3850 * Good IPv4/IPv6 address...
3853 httpAddrFreeList(addrlist
);
3859 * Check for (alias) name matches...
3862 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3864 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3867 * "ServerAlias *" allows all host values through...
3870 if (!strcmp(a
->name
, "*"))
3873 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3876 * Prefix matches; check the character at the end - it must be "." or nul.
3879 end
= con
->clientname
+ a
->namelen
;
3881 if (!*end
|| (*end
== '.' && !end
[1]))
3886 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3887 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3889 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3892 * "ServerAlias *" allows all host values through...
3895 if (!strcmp(a
->name
, "*"))
3898 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3901 * Prefix matches; check the character at the end - it must be "." or nul.
3904 end
= con
->clientname
+ a
->namelen
;
3906 if (!*end
|| (*end
== '.' && !end
[1]))
3910 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3913 * Check for interface hostname matches...
3916 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3918 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3920 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3923 * Prefix matches; check the character at the end - it must be "." or nul.
3926 end
= con
->clientname
+ netif
->hostlen
;
3928 if (!*end
|| (*end
== '.' && !end
[1]))
3938 * 'write_file()' - Send a file via HTTP.
3941 static int /* O - 0 on failure, 1 on success */
3942 write_file(cupsd_client_t
*con
, /* I - Client connection */
3943 http_status_t code
, /* I - HTTP status */
3944 char *filename
, /* I - Filename */
3945 char *type
, /* I - File type */
3946 struct stat
*filestats
) /* O - File information */
3948 con
->file
= open(filename
, O_RDONLY
);
3950 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3951 "write_file code=%d, filename=\"%s\" (%d), "
3952 "type=\"%s\", filestats=%p",
3953 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3958 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3961 con
->sent_header
= 1;
3963 httpClearFields(con
->http
);
3965 httpSetLength(con
->http
, filestats
->st_size
);
3967 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3968 httpGetDateString(filestats
->st_mtime
));
3970 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3973 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3975 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3982 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3986 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3988 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
3991 con
->file_ready
= 1;
3993 cupsdRemoveSelect(con
->file
);
3994 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3996 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");