4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2015 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * Include necessary headers...
23 #define _CUPS_NO_DEPRECATED
24 #define _HTTP_NO_PRIVATE
29 #endif /* __APPLE__ */
32 #endif /* HAVE_TCPD_H */
39 static int check_if_modified(cupsd_client_t
*con
,
40 struct stat
*filestats
);
41 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
44 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
46 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
47 char *filename
, size_t len
);
48 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
49 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
50 struct stat
*filestats
, mime_type_t
*type
);
51 static int is_path_absolute(const char *path
);
52 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
53 char *command
, char *options
, int root
);
54 static int valid_host(cupsd_client_t
*con
);
55 static int write_file(cupsd_client_t
*con
, http_status_t code
,
56 char *filename
, char *type
,
57 struct stat
*filestats
);
58 static void write_pipe(cupsd_client_t
*con
);
62 * 'cupsdAcceptClient()' - Accept a new client.
66 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
68 const char *hostname
; /* Hostname of client */
69 char name
[256]; /* Hostname of client */
70 int count
; /* Count of connections on a host */
71 cupsd_client_t
*con
, /* New client pointer */
72 *tempcon
; /* Temporary client pointer */
73 socklen_t addrlen
; /* Length of address */
74 http_addr_t temp
; /* Temporary address variable */
75 static time_t last_dos
= 0; /* Time of last DoS attack */
77 struct request_info wrap_req
; /* TCP wrappers request information */
78 #endif /* HAVE_TCPD_H */
81 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis
, lis
->fd
, cupsArrayCount(Clients
));
84 * Make sure we don't have a full set of clients already...
87 if (cupsArrayCount(Clients
) == MaxClients
)
91 * Get a pointer to the next available client...
95 Clients
= cupsArrayNew(NULL
, NULL
);
99 cupsdLogMessage(CUPSD_LOG_ERROR
,
100 "Unable to allocate memory for clients array!");
101 cupsdPauseListening();
106 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
110 cupsdLogMessage(CUPSD_LOG_ERROR
,
111 "Unable to allocate memory for active clients array!");
112 cupsdPauseListening();
116 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
118 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
119 cupsdPauseListening();
124 * Accept the client and get the remote address...
127 con
->number
= ++ LastClientNumber
;
130 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
132 if (errno
== ENFILE
|| errno
== EMFILE
)
133 cupsdPauseListening();
135 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
143 * Save the connected address and port number...
146 addrlen
= sizeof(con
->clientaddr
);
148 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&con
->clientaddr
, &addrlen
) || addrlen
== 0)
149 con
->clientaddr
= lis
->address
;
151 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Server address is \"%s\".", httpAddrString(&con
->clientaddr
, name
, sizeof(name
)));
154 * Check the number of clients on the same address...
157 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
159 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
160 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
163 if (count
>= MaxClientsPerHost
)
167 if (count
>= MaxClientsPerHost
)
169 if ((time(NULL
) - last_dos
) >= 60)
171 last_dos
= time(NULL
);
172 cupsdLogMessage(CUPSD_LOG_WARN
,
173 "Possible DoS attack - more than %d clients connecting "
176 httpGetHostname(con
->http
, name
, sizeof(name
)));
179 httpClose(con
->http
);
185 * Get the hostname or format the IP address as needed...
189 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
191 hostname
= httpGetHostname(con
->http
, NULL
, 0);
193 if (hostname
== NULL
&& HostNameLookups
== 2)
196 * Can't have an unresolved IP address with double-lookups enabled...
199 httpClose(con
->http
);
201 cupsdLogClient(con
, CUPSD_LOG_WARN
,
202 "Name lookup failed - connection from %s closed!",
203 httpGetHostname(con
->http
, NULL
, 0));
209 if (HostNameLookups
== 2)
212 * Do double lookups as needed...
215 http_addrlist_t
*addrlist
, /* List of addresses */
216 *addr
; /* Current address */
218 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
221 * See if the hostname maps to the same IP address...
224 for (addr
= addrlist
; addr
; addr
= addr
->next
)
225 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
231 httpAddrFreeList(addrlist
);
236 * Can't have a hostname that doesn't resolve to the same IP address
237 * with double-lookups enabled...
240 httpClose(con
->http
);
242 cupsdLogClient(con
, CUPSD_LOG_WARN
,
243 "IP lookup failed - connection from %s closed!",
244 httpGetHostname(con
->http
, NULL
, 0));
252 * See if the connection is denied by TCP wrappers...
255 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
259 if (!hosts_access(&wrap_req
))
261 httpClose(con
->http
);
263 cupsdLogClient(con
, CUPSD_LOG_WARN
,
264 "Connection from %s refused by /etc/hosts.allow and "
265 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
269 #endif /* HAVE_TCPD_H */
272 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
275 socklen_t peersize
; /* Size of peer credentials */
276 pid_t peerpid
; /* Peer process ID */
277 char peername
[256]; /* Name of process */
279 peersize
= sizeof(peerpid
);
280 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
283 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
284 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
285 "Accepted from %s (Domain ???[%d])",
286 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
288 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
289 "Accepted from %s (Domain %s[%d])",
290 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
293 # endif /* __APPLE__ */
295 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
296 httpGetHostname(con
->http
, NULL
, 0));
299 #endif /* AF_LOCAL */
300 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
301 httpGetHostname(con
->http
, NULL
, 0),
302 httpAddrPort(httpGetAddress(con
->http
)),
303 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
306 * Get the local address the client connected to...
309 addrlen
= sizeof(temp
);
310 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
312 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
315 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
316 con
->serverport
= LocalPort
;
319 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
321 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
322 con
->serverport
= LocalPort
;
324 #endif /* AF_LOCAL */
327 if (httpAddrLocalhost(&temp
))
328 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
329 else if (HostNameLookups
)
330 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
332 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
334 con
->serverport
= httpAddrPort(&(lis
->address
));
338 * Add the connection to the array of active clients...
341 cupsArrayAdd(Clients
, con
);
344 * Add the socket to the server select.
347 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
350 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
353 * Temporarily suspend accept()'s until we lose a client...
356 if (cupsArrayCount(Clients
) == MaxClients
)
357 cupsdPauseListening();
361 * See if we are connecting on a secure port...
364 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
367 * https connection; go secure...
370 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
371 cupsdCloseClient(con
);
375 #endif /* HAVE_SSL */
380 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
384 cupsdCloseAllClients(void)
386 cupsd_client_t
*con
; /* Current client */
389 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients
));
391 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
393 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
394 if (cupsdCloseClient(con
))
395 cupsdCloseClient(con
);
400 * 'cupsdCloseClient()' - Close a remote client.
403 int /* O - 1 if partial close, 0 if fully closed */
404 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
406 int partial
; /* Do partial close for SSL? */
409 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
412 * Flush pending writes before closing...
415 httpFlushWrite(con
->http
);
419 if (con
->pipe_pid
!= 0)
422 * Stop any CGI process...
425 cupsdEndProcess(con
->pipe_pid
, 1);
431 cupsdRemoveSelect(con
->file
);
438 * Close the socket and clear the file from the input set for select()...
441 if (httpGetFd(con
->http
) >= 0)
443 cupsArrayRemove(ActiveClients
, con
);
448 * Shutdown encryption as needed...
451 if (httpIsEncrypted(con
->http
))
453 #endif /* HAVE_SSL */
458 * Only do a partial close so that the encrypted client gets everything.
461 httpShutdown(con
->http
);
462 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
465 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
470 * Shut the socket down fully...
473 cupsdRemoveSelect(httpGetFd(con
->http
));
474 httpClose(con
->http
);
485 cupsdRemoveSelect(httpGetFd(con
->http
));
487 httpClose(con
->http
);
491 unlink(con
->filename
);
492 cupsdClearString(&con
->filename
);
495 cupsdClearString(&con
->command
);
496 cupsdClearString(&con
->options
);
497 cupsdClearString(&con
->query_string
);
501 ippDelete(con
->request
);
507 ippDelete(con
->response
);
508 con
->response
= NULL
;
513 cupsLangFree(con
->language
);
514 con
->language
= NULL
;
517 #ifdef HAVE_AUTHORIZATION_H
520 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
523 #endif /* HAVE_AUTHORIZATION_H */
526 * Re-enable new client connections if we are going back under the
530 if (cupsArrayCount(Clients
) == MaxClients
)
531 cupsdResumeListening();
534 * Compact the list of clients as necessary...
537 cupsArrayRemove(Clients
, con
);
547 * 'cupsdReadClient()' - Read data from a client.
551 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
553 char line
[32768], /* Line from client... */
554 locale
[64], /* Locale */
555 *ptr
; /* Pointer into strings */
556 http_status_t status
; /* Transfer status */
557 ipp_state_t ipp_state
; /* State of IPP transfer */
558 int bytes
; /* Number of bytes to POST */
559 char *filename
; /* Name of file for GET/HEAD */
560 char buf
[1024]; /* Buffer for real filename */
561 struct stat filestats
; /* File information */
562 mime_type_t
*type
; /* MIME type of file */
563 cupsd_printer_t
*p
; /* Printer */
564 static unsigned request_id
= 0; /* Request ID for temp files */
567 status
= HTTP_STATUS_CONTINUE
;
569 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=" CUPS_LLFMT
", request=%p(%s), file=%d", httpError(con
->http
), (int)httpGetReady(con
->http
), httpStateString(httpGetState(con
->http
)), httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH", CUPS_LLCAST
httpGetRemaining(con
->http
), con
->request
, con
->request
? ippStateString(ippGetState(con
->request
)) : "", con
->file
);
571 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
572 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
573 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
576 * If we get called in the wrong state, then something went wrong with the
577 * connection and we need to shut it down...
580 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
583 * Connection closed...
586 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
587 cupsdCloseClient(con
);
591 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con
->http
)));
592 cupsdCloseClient(con
);
600 * Automatically check for a SSL/TLS handshake...
605 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
606 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
609 * Encrypt this connection...
612 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf
[0] & 255);
614 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
615 cupsdCloseClient(con
);
620 #endif /* HAVE_SSL */
622 switch (httpGetState(con
->http
))
624 case HTTP_STATE_WAITING
:
626 * See if we've received a request line...
629 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
630 if (con
->operation
== HTTP_STATE_ERROR
||
631 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
632 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
634 if (httpError(con
->http
))
635 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
636 "HTTP_STATE_WAITING Closing for error %d (%s)",
637 httpError(con
->http
), strerror(httpError(con
->http
)));
639 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
640 "HTTP_STATE_WAITING Closing on error: %s",
641 cupsLastErrorString());
643 cupsdCloseClient(con
);
648 * Ignore blank request lines...
651 if (con
->operation
== HTTP_STATE_WAITING
)
655 * Clear other state variables...
662 con
->username
[0] = '\0';
663 con
->password
[0] = '\0';
665 cupsdClearString(&con
->command
);
666 cupsdClearString(&con
->options
);
667 cupsdClearString(&con
->query_string
);
671 ippDelete(con
->request
);
677 ippDelete(con
->response
);
678 con
->response
= NULL
;
683 cupsLangFree(con
->language
);
684 con
->language
= NULL
;
690 #endif /* HAVE_GSSAPI */
693 * Handle full URLs in the request line...
696 if (strcmp(con
->uri
, "*"))
698 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
699 userpass
[HTTP_MAX_URI
], /* Username:password */
700 hostname
[HTTP_MAX_URI
], /* Hostname */
701 resource
[HTTP_MAX_URI
]; /* Resource path */
702 int port
; /* Port number */
705 * Separate the URI into its components...
708 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
709 scheme
, sizeof(scheme
),
710 userpass
, sizeof(userpass
),
711 hostname
, sizeof(hostname
), &port
,
712 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
714 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
716 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
717 cupsdCloseClient(con
);
722 * Only allow URIs with the servername, localhost, or an IP
726 if (strcmp(scheme
, "file") &&
727 _cups_strcasecmp(hostname
, ServerName
) &&
728 _cups_strcasecmp(hostname
, "localhost") &&
729 !cupsArrayFind(ServerAlias
, hostname
) &&
730 !isdigit(hostname
[0]) && hostname
[0] != '[')
733 * Nope, we don't do proxies...
736 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
738 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
739 cupsdCloseClient(con
);
744 * Copy the resource portion back into the URI; both resource and
745 * con->uri are HTTP_MAX_URI bytes in size...
748 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
752 * Process the request...
755 gettimeofday(&(con
->start
), NULL
);
757 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
758 httpStateString(con
->operation
) + 11, con
->uri
,
759 httpGetVersion(con
->http
) / 100,
760 httpGetVersion(con
->http
) % 100);
762 if (!cupsArrayFind(ActiveClients
, con
))
764 cupsArrayAdd(ActiveClients
, con
);
768 case HTTP_STATE_OPTIONS
:
769 case HTTP_STATE_DELETE
:
770 case HTTP_STATE_GET
:
771 case HTTP_STATE_HEAD
:
772 case HTTP_STATE_POST
:
773 case HTTP_STATE_PUT
:
774 case HTTP_STATE_TRACE
:
776 * Parse incoming parameters until the status changes...
779 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
780 if (!httpGetReady(con
->http
))
783 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
785 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
786 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
787 "Closing for error %d (%s) while reading headers.",
788 httpError(con
->http
), strerror(httpError(con
->http
)));
790 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
791 "Closing on EOF while reading headers.");
793 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
794 cupsdCloseClient(con
);
800 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
803 * Connection closed...
806 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
807 cupsdCloseClient(con
);
810 break; /* Anti-compiler-warning-code */
814 * Handle new transfers...
817 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d", status
);
819 if (status
== HTTP_STATUS_OK
)
821 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
824 * Figure out the locale from the Accept-Language and Content-Type
828 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
832 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
836 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
837 "charset=")) != NULL
)
840 * Combine language and charset, and trim any extra params in the
844 snprintf(locale
, sizeof(locale
), "%s.%s",
845 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
847 if ((ptr
= strchr(locale
, ',')) != NULL
)
851 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
852 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
854 con
->language
= cupsLangGet(locale
);
857 con
->language
= cupsLangGet(DefaultLocale
);
861 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
862 "Keep-Alive", 10) && KeepAlive
)
863 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
864 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
866 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
868 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
869 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
872 * HTTP/1.1 and higher require the "Host:" field...
875 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
877 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
878 cupsdCloseClient(con
);
882 else if (!valid_host(con
))
885 * Access to localhost must use "localhost" or the corresponding IPv4
886 * or IPv6 values in the Host: field.
889 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
890 "Request from \"%s\" using invalid Host: field \"%s\".",
891 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
893 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
895 cupsdCloseClient(con
);
899 else if (con
->operation
== HTTP_STATE_OPTIONS
)
902 * Do OPTIONS command...
905 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
907 httpClearFields(con
->http
);
909 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
911 cupsdCloseClient(con
);
916 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
920 * Do encryption stuff...
923 httpClearFields(con
->http
);
925 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
927 cupsdCloseClient(con
);
931 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
933 cupsdCloseClient(con
);
937 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
939 cupsdCloseClient(con
);
942 #endif /* HAVE_SSL */
945 httpClearFields(con
->http
);
946 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
947 "GET, HEAD, OPTIONS, POST, PUT");
948 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
950 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
952 cupsdCloseClient(con
);
956 else if (!is_path_absolute(con
->uri
))
959 * Protect against malicious users!
962 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
963 "Request for non-absolute resource \"%s\".", con
->uri
);
965 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
967 cupsdCloseClient(con
);
973 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
974 "Upgrade") && !httpIsEncrypted(con
->http
))
978 * Do encryption stuff...
981 httpClearFields(con
->http
);
983 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
986 cupsdCloseClient(con
);
990 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
992 cupsdCloseClient(con
);
996 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
998 cupsdCloseClient(con
);
1001 #endif /* HAVE_SSL */
1004 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1006 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1007 cupsdCloseClient(con
);
1011 if (httpGetExpect(con
->http
) &&
1012 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1014 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1017 * Send 100-continue header...
1020 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1022 cupsdCloseClient(con
);
1029 * Send 417-expectation-failed header...
1032 httpClearFields(con
->http
);
1033 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1035 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1036 cupsdCloseClient(con
);
1041 switch (httpGetState(con
->http
))
1043 case HTTP_STATE_GET_SEND
:
1044 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1046 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1047 !strncmp(con
->uri
, "/printers/", 10) ||
1048 !strncmp(con
->uri
, "/classes/", 9)) &&
1049 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1052 * Send PPD file - get the real printer name since printer
1053 * names are not case sensitive but filenames can be...
1056 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1058 if (!strncmp(con
->uri
, "/ppd/", 5))
1059 p
= cupsdFindPrinter(con
->uri
+ 5);
1060 else if (!strncmp(con
->uri
, "/printers/", 10))
1061 p
= cupsdFindPrinter(con
->uri
+ 10);
1064 p
= cupsdFindClass(con
->uri
+ 9);
1068 int i
; /* Looping var */
1070 for (i
= 0; i
< p
->num_printers
; i
++)
1072 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1074 char ppdname
[1024];/* PPD filename */
1076 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1077 ServerRoot
, p
->printers
[i
]->name
);
1078 if (!access(ppdname
, 0))
1086 if (i
>= p
->num_printers
)
1093 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1097 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1099 cupsdCloseClient(con
);
1106 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1107 !strncmp(con
->uri
, "/printers/", 10) ||
1108 !strncmp(con
->uri
, "/classes/", 9)) &&
1109 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1112 * Send icon file - get the real queue name since queue names are
1113 * not case sensitive but filenames can be...
1116 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1118 if (!strncmp(con
->uri
, "/icons/", 7))
1119 p
= cupsdFindPrinter(con
->uri
+ 7);
1120 else if (!strncmp(con
->uri
, "/printers/", 10))
1121 p
= cupsdFindPrinter(con
->uri
+ 10);
1124 p
= cupsdFindClass(con
->uri
+ 9);
1128 int i
; /* Looping var */
1130 for (i
= 0; i
< p
->num_printers
; i
++)
1132 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1134 char ppdname
[1024];/* PPD filename */
1136 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1137 ServerRoot
, p
->printers
[i
]->name
);
1138 if (!access(ppdname
, 0))
1146 if (i
>= p
->num_printers
)
1152 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1155 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1157 cupsdCloseClient(con
);
1165 if ((!strncmp(con
->uri
, "/admin", 6) && strcmp(con
->uri
, "/admin/conf/cupsd.conf") && strncmp(con
->uri
, "/admin/log/", 11)) ||
1166 !strncmp(con
->uri
, "/printers", 9) ||
1167 !strncmp(con
->uri
, "/classes", 8) ||
1168 !strncmp(con
->uri
, "/help", 5) ||
1169 !strncmp(con
->uri
, "/jobs", 5))
1174 * Web interface is disabled. Show an appropriate message...
1177 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1179 cupsdCloseClient(con
);
1187 * Send CGI output...
1190 if (!strncmp(con
->uri
, "/admin", 6))
1192 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1195 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1197 else if (!strncmp(con
->uri
, "/printers", 9))
1199 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1202 if (con
->uri
[9] && con
->uri
[10])
1203 cupsdSetString(&con
->options
, con
->uri
+ 9);
1205 cupsdSetString(&con
->options
, NULL
);
1207 else if (!strncmp(con
->uri
, "/classes", 8))
1209 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1212 if (con
->uri
[8] && con
->uri
[9])
1213 cupsdSetString(&con
->options
, con
->uri
+ 8);
1215 cupsdSetString(&con
->options
, NULL
);
1217 else if (!strncmp(con
->uri
, "/jobs", 5))
1219 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1222 if (con
->uri
[5] && con
->uri
[6])
1223 cupsdSetString(&con
->options
, con
->uri
+ 5);
1225 cupsdSetString(&con
->options
, NULL
);
1229 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1232 if (con
->uri
[5] && con
->uri
[6])
1233 cupsdSetString(&con
->options
, con
->uri
+ 5);
1235 cupsdSetString(&con
->options
, NULL
);
1238 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1240 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1242 cupsdCloseClient(con
);
1247 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1249 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1250 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1252 else if (!strncmp(con
->uri
, "/admin/log/", 11) && (strchr(con
->uri
+ 11, '/') || strlen(con
->uri
) == 11))
1255 * GET can only be done to configuration files directly under
1259 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Request for subdirectory \"%s\".", con
->uri
);
1261 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1263 cupsdCloseClient(con
);
1275 if ((filename
= get_file(con
, &filestats
, buf
,
1276 sizeof(buf
))) == NULL
)
1278 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1280 cupsdCloseClient(con
);
1287 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1289 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1291 if (is_cgi(con
, filename
, &filestats
, type
))
1294 * Note: con->command and con->options were set by
1298 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1300 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1302 cupsdCloseClient(con
);
1307 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1309 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1310 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1314 if (!check_if_modified(con
, &filestats
))
1316 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1318 cupsdCloseClient(con
);
1325 strlcpy(line
, "text/plain", sizeof(line
));
1327 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1329 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1331 cupsdCloseClient(con
);
1338 case HTTP_STATE_POST_RECV
:
1340 * See if the POST request includes a Content-Length field, and if
1341 * so check the length against any limits that are set...
1344 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1345 MaxRequestSize
> 0 &&
1346 httpGetLength2(con
->http
) > MaxRequestSize
)
1349 * Request too large...
1352 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1354 cupsdCloseClient(con
);
1360 else if (httpGetLength2(con
->http
) < 0)
1363 * Negative content lengths are invalid!
1366 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1368 cupsdCloseClient(con
);
1376 * See what kind of POST request this is; for IPP requests the
1377 * content-type field will be "application/ipp"...
1380 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1382 con
->request
= ippNew();
1383 else if (!WebInterface
)
1386 * Web interface is disabled. Show an appropriate message...
1389 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1391 cupsdCloseClient(con
);
1397 else if ((!strncmp(con
->uri
, "/admin", 6) && strncmp(con
->uri
, "/admin/log/", 11)) ||
1398 !strncmp(con
->uri
, "/printers", 9) ||
1399 !strncmp(con
->uri
, "/classes", 8) ||
1400 !strncmp(con
->uri
, "/help", 5) ||
1401 !strncmp(con
->uri
, "/jobs", 5))
1407 if (!strncmp(con
->uri
, "/admin", 6))
1409 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1412 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1414 else if (!strncmp(con
->uri
, "/printers", 9))
1416 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1419 if (con
->uri
[9] && con
->uri
[10])
1420 cupsdSetString(&con
->options
, con
->uri
+ 9);
1422 cupsdSetString(&con
->options
, NULL
);
1424 else if (!strncmp(con
->uri
, "/classes", 8))
1426 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1429 if (con
->uri
[8] && con
->uri
[9])
1430 cupsdSetString(&con
->options
, con
->uri
+ 8);
1432 cupsdSetString(&con
->options
, NULL
);
1434 else if (!strncmp(con
->uri
, "/jobs", 5))
1436 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1439 if (con
->uri
[5] && con
->uri
[6])
1440 cupsdSetString(&con
->options
, con
->uri
+ 5);
1442 cupsdSetString(&con
->options
, NULL
);
1446 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1449 if (con
->uri
[5] && con
->uri
[6])
1450 cupsdSetString(&con
->options
, con
->uri
+ 5);
1452 cupsdSetString(&con
->options
, NULL
);
1455 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1456 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1464 if ((filename
= get_file(con
, &filestats
, buf
,
1465 sizeof(buf
))) == NULL
)
1467 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1469 cupsdCloseClient(con
);
1476 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1478 if (!is_cgi(con
, filename
, &filestats
, type
))
1481 * Only POST to CGI's...
1484 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1486 cupsdCloseClient(con
);
1493 case HTTP_STATE_PUT_RECV
:
1495 * Validate the resource name...
1498 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1501 * PUT can only be done to the cupsd.conf file...
1504 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1505 "Disallowed PUT request for \"%s\".", con
->uri
);
1507 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1509 cupsdCloseClient(con
);
1517 * See if the PUT request includes a Content-Length field, and if
1518 * so check the length against any limits that are set...
1521 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1522 MaxRequestSize
> 0 &&
1523 httpGetLength2(con
->http
) > MaxRequestSize
)
1526 * Request too large...
1529 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1531 cupsdCloseClient(con
);
1537 else if (httpGetLength2(con
->http
) < 0)
1540 * Negative content lengths are invalid!
1543 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1545 cupsdCloseClient(con
);
1553 * Open a temporary file to hold the request...
1556 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1558 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1562 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1563 "Unable to create request file \"%s\": %s",
1564 con
->filename
, strerror(errno
));
1566 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1568 cupsdCloseClient(con
);
1573 fchmod(con
->file
, 0640);
1574 fchown(con
->file
, RunUser
, Group
);
1575 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1578 case HTTP_STATE_DELETE
:
1579 case HTTP_STATE_TRACE
:
1580 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1581 cupsdCloseClient(con
);
1584 case HTTP_STATE_HEAD
:
1585 if (!strncmp(con
->uri
, "/printers/", 10) &&
1586 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1589 * Send PPD file - get the real printer name since printer
1590 * names are not case sensitive but filenames can be...
1593 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1595 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1596 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1599 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1601 cupsdCloseClient(con
);
1605 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1609 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1610 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1613 * Send PNG file - get the real printer name since printer
1614 * names are not case sensitive but filenames can be...
1617 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1619 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1620 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1623 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1625 cupsdCloseClient(con
);
1629 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1633 else if (!WebInterface
)
1635 httpClearFields(con
->http
);
1637 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1639 cupsdCloseClient(con
);
1643 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1647 if ((!strncmp(con
->uri
, "/admin", 6) && strcmp(con
->uri
, "/admin/conf/cupsd.conf") && strncmp(con
->uri
, "/admin/log/", 11)) ||
1648 !strncmp(con
->uri
, "/printers", 9) ||
1649 !strncmp(con
->uri
, "/classes", 8) ||
1650 !strncmp(con
->uri
, "/help", 5) ||
1651 !strncmp(con
->uri
, "/jobs", 5))
1657 httpClearFields(con
->http
);
1659 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1665 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1667 else if (!strncmp(con
->uri
, "/admin/log/", 11) && (strchr(con
->uri
+ 11, '/') || strlen(con
->uri
) == 11))
1670 * HEAD can only be done to configuration files under
1674 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1675 "Request for subdirectory \"%s\".", con
->uri
);
1677 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1679 cupsdCloseClient(con
);
1683 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1686 else if ((filename
= get_file(con
, &filestats
, buf
,
1687 sizeof(buf
))) == NULL
)
1689 httpClearFields(con
->http
);
1691 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1694 cupsdCloseClient(con
);
1698 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1700 else if (!check_if_modified(con
, &filestats
))
1702 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1704 cupsdCloseClient(con
);
1708 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1716 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1718 strlcpy(line
, "text/plain", sizeof(line
));
1720 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1722 httpClearFields(con
->http
);
1724 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1725 httpGetDateString(filestats
.st_mtime
));
1726 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1728 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1730 cupsdCloseClient(con
);
1734 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1739 break; /* Anti-compiler-warning-code */
1745 * Handle any incoming data...
1748 switch (httpGetState(con
->http
))
1750 case HTTP_STATE_PUT_RECV
:
1753 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1755 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1756 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1757 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1758 httpError(con
->http
), strerror(httpError(con
->http
)));
1760 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1761 "HTTP_STATE_PUT_RECV Closing on EOF.");
1763 cupsdCloseClient(con
);
1768 con
->bytes
+= bytes
;
1770 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1774 unlink(con
->filename
);
1775 cupsdClearString(&con
->filename
);
1777 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1779 cupsdCloseClient(con
);
1784 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1786 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1787 "Unable to write %d bytes to \"%s\": %s", bytes
,
1788 con
->filename
, strerror(errno
));
1792 unlink(con
->filename
);
1793 cupsdClearString(&con
->filename
);
1795 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1797 cupsdCloseClient(con
);
1802 else if (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
)
1804 cupsdCloseClient(con
);
1808 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1810 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1813 * End of file, see how big it is...
1816 fstat(con
->file
, &filestats
);
1821 if (filestats
.st_size
> MaxRequestSize
&&
1825 * Request is too big; remove it and send an error...
1828 unlink(con
->filename
);
1829 cupsdClearString(&con
->filename
);
1831 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1833 cupsdCloseClient(con
);
1839 * Install the configuration file...
1842 status
= install_cupsd_conf(con
);
1845 * Return the status to the client...
1848 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1850 cupsdCloseClient(con
);
1856 case HTTP_STATE_POST_RECV
:
1859 if (con
->request
&& con
->file
< 0)
1862 * Grab any request data from the connection...
1865 if (!httpWait(con
->http
, 0))
1868 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1870 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1871 cupsLastErrorString());
1873 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1874 cupsdCloseClient(con
);
1877 else if (ipp_state
!= IPP_STATE_DATA
)
1879 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1881 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1882 cupsdCloseClient(con
);
1886 if (httpGetReady(con
->http
))
1892 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1893 con
->request
->request
.op
.version
[0],
1894 con
->request
->request
.op
.version
[1],
1895 ippOpString(con
->request
->request
.op
.operation_id
),
1896 con
->request
->request
.op
.request_id
);
1897 con
->bytes
+= (off_t
)ippLength(con
->request
);
1901 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1904 * Create a file as needed for the request data...
1907 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1909 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1913 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1914 "Unable to create request file \"%s\": %s",
1915 con
->filename
, strerror(errno
));
1917 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1919 cupsdCloseClient(con
);
1924 fchmod(con
->file
, 0640);
1925 fchown(con
->file
, RunUser
, Group
);
1926 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1929 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1931 if (!httpWait(con
->http
, 0))
1933 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1935 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1936 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1937 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1938 httpError(con
->http
), strerror(httpError(con
->http
)));
1940 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1941 "HTTP_STATE_POST_SEND Closing on EOF.");
1943 cupsdCloseClient(con
);
1948 con
->bytes
+= bytes
;
1950 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1954 unlink(con
->filename
);
1955 cupsdClearString(&con
->filename
);
1957 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1959 cupsdCloseClient(con
);
1964 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1966 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1967 "Unable to write %d bytes to \"%s\": %s",
1968 bytes
, con
->filename
, strerror(errno
));
1972 unlink(con
->filename
);
1973 cupsdClearString(&con
->filename
);
1975 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1978 cupsdCloseClient(con
);
1983 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1985 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1987 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1988 "Closing on unexpected state %s.",
1989 httpStateString(httpGetState(con
->http
)));
1990 cupsdCloseClient(con
);
1995 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1997 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2001 fstat(con
->file
, &filestats
);
2006 if (filestats
.st_size
> MaxRequestSize
&&
2010 * Request is too big; remove it and send an error...
2013 unlink(con
->filename
);
2014 cupsdClearString(&con
->filename
);
2019 * Delete any IPP request data...
2022 ippDelete(con
->request
);
2023 con
->request
= NULL
;
2026 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2028 cupsdCloseClient(con
);
2032 else if (filestats
.st_size
== 0)
2035 * Don't allow empty file...
2038 unlink(con
->filename
);
2039 cupsdClearString(&con
->filename
);
2044 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2046 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2048 cupsdCloseClient(con
);
2053 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2059 cupsdProcessIPPRequest(con
);
2063 unlink(con
->filename
);
2064 cupsdClearString(&con
->filename
);
2073 break; /* Anti-compiler-warning-code */
2076 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2078 if (!httpGetKeepAlive(con
->http
))
2080 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2081 "Closing because Keep-Alive is disabled.");
2082 cupsdCloseClient(con
);
2086 cupsArrayRemove(ActiveClients
, con
);
2087 cupsdSetBusyState();
2094 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2097 int /* O - 1 on success, 0 on failure */
2099 cupsd_client_t
*con
, /* I - Client connection */
2100 char *command
, /* I - Command to run */
2101 char *options
, /* I - Command-line options */
2102 int root
) /* I - Run as root? */
2104 int fd
; /* Standard input file descriptor */
2109 fd
= open(con
->filename
, O_RDONLY
);
2113 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2114 "Unable to open \"%s\" for reading: %s",
2115 con
->filename
? con
->filename
: "/dev/null",
2120 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2125 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2126 con
->pipe_status
= HTTP_STATUS_OK
;
2128 httpClearFields(con
->http
);
2133 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2134 command
, con
->pipe_pid
, con
->file
);
2136 if (con
->pipe_pid
== 0)
2139 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2141 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2143 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2145 con
->sent_header
= 0;
2146 con
->file_ready
= 0;
2147 con
->got_fields
= 0;
2148 con
->header_used
= 0;
2155 * 'cupsdSendError()' - Send an error message via HTTP.
2158 int /* O - 1 if successful, 0 otherwise */
2159 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2160 http_status_t code
, /* I - Error code */
2161 int auth_type
)/* I - Authentication type */
2163 char location
[HTTP_MAX_VALUE
]; /* Location field */
2166 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d", code
, auth_type
);
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 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
2199 httpClearFields(con
->http
);
2201 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
2203 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2204 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2206 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2207 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2208 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2210 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2213 * Send a human-readable error message.
2216 char message
[4096], /* Message for user */
2217 urltext
[1024], /* URL redirection text */
2218 redirect
[1024]; /* Redirection link */
2219 const char *text
; /* Status-specific text */
2224 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2225 text
= _cupsLangString(con
->language
,
2226 _("Enter your username and password or the "
2227 "root username and password to access this "
2228 "page. If you are using Kerberos authentication, "
2229 "make sure you have a valid Kerberos ticket."));
2230 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2234 snprintf(urltext
, sizeof(urltext
),
2235 _cupsLangString(con
->language
,
2236 _("You must access this page using the URL "
2237 "<A HREF=\"https://%s:%d%s\">"
2238 "https://%s:%d%s</A>.")),
2239 con
->servername
, con
->serverport
, con
->uri
,
2240 con
->servername
, con
->serverport
, con
->uri
);
2242 snprintf(redirect
, sizeof(redirect
),
2243 "<META HTTP-EQUIV=\"Refresh\" "
2244 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2245 con
->servername
, con
->serverport
, con
->uri
);
2247 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2248 text
= _cupsLangString(con
->language
,
2249 _("The web interface is currently disabled. Run "
2250 "\"cupsctl WebInterface=yes\" to enable it."));
2254 snprintf(message
, sizeof(message
),
2255 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2256 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2259 "\t<META HTTP-EQUIV=\"Content-Type\" "
2260 "CONTENT=\"text/html; charset=utf-8\">\n"
2261 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2262 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2263 "HREF=\"/cups.css\">\n"
2271 _httpStatus(con
->language
, code
), redirect
,
2272 _httpStatus(con
->language
, code
), text
);
2275 * Send an error message back to the client. If the error code is a
2276 * 400 or 500 series, make sure the message contains some text, too!
2279 size_t length
= strlen(message
); /* Length of message */
2281 httpSetLength(con
->http
, length
);
2283 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2286 if (httpWrite2(con
->http
, message
, length
) < 0)
2289 if (httpFlushWrite(con
->http
) < 0)
2294 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2296 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2305 * 'cupsdSendHeader()' - Send an HTTP request.
2308 int /* O - 1 on success, 0 on failure */
2310 cupsd_client_t
*con
, /* I - Client to send to */
2311 http_status_t code
, /* I - HTTP status code */
2312 char *type
, /* I - MIME type of document */
2313 int auth_type
) /* I - Type of authentication */
2315 char auth_str
[1024]; /* Authorization string */
2318 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2321 * Send the HTTP status header...
2324 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2327 * Treat our special "web interface is disabled" status as "200 OK" for web
2331 code
= HTTP_STATUS_OK
;
2335 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2337 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2338 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2340 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2342 if (auth_type
== CUPSD_AUTH_NONE
)
2344 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2345 auth_type
= cupsdDefaultAuthType();
2347 auth_type
= con
->best
->type
;
2352 if (auth_type
== CUPSD_AUTH_BASIC
)
2353 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2355 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2358 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2359 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2361 # endif /* AF_LOCAL */
2362 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2364 #endif /* HAVE_GSSAPI */
2366 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2367 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2370 * Add a "trc" (try root certification) parameter for local non-Kerberos
2371 * requests when the request requires system group membership - then the
2372 * client knows the root certificate can/should be used.
2374 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2375 * parameter as needed...
2378 char *name
, /* Current user name */
2379 *auth_key
; /* Auth key buffer */
2380 size_t auth_size
; /* Size of remaining buffer */
2382 auth_key
= auth_str
+ strlen(auth_str
);
2383 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2385 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2387 name
= (char *)cupsArrayNext(con
->best
->names
))
2389 #ifdef HAVE_AUTHORIZATION_H
2390 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2392 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2393 /* end parenthesis is stripped in conf.c */
2397 #endif /* HAVE_AUTHORIZATION_H */
2398 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2400 #ifdef HAVE_AUTHORIZATION_H
2401 if (SystemGroupAuthKey
)
2402 snprintf(auth_key
, auth_size
,
2404 SystemGroupAuthKey
);
2407 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2408 #endif /* HAVE_AUTHORIZATION_H */
2416 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2418 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2422 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2423 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2427 if (!strcmp(type
, "text/html"))
2428 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2430 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2433 return (!httpWriteResponse(con
->http
, code
));
2438 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2442 cupsdUpdateCGI(void)
2444 char *ptr
, /* Pointer to end of line in buffer */
2445 message
[1024]; /* Pointer to message text */
2446 int loglevel
; /* Log level for message */
2449 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2450 message
, sizeof(message
))) != NULL
)
2452 if (loglevel
== CUPSD_LOG_INFO
)
2453 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2455 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2459 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2462 * Fatal error on pipe - should never happen!
2465 cupsdLogMessage(CUPSD_LOG_CRIT
,
2466 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2473 * 'cupsdWriteClient()' - Write data to a client as needed.
2477 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2479 int bytes
, /* Number of bytes written */
2480 field_col
; /* Current column */
2481 char *bufptr
, /* Pointer into buffer */
2482 *bufend
; /* Pointer to end of buffer */
2483 ipp_state_t ipp_state
; /* IPP state value */
2486 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2487 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2492 "data_encoding=HTTP_ENCODING_%s, "
2493 "data_remaining=" CUPS_LLFMT
", "
2497 httpError(con
->http
), (int)httpGetReady(con
->http
),
2498 httpStateString(httpGetState(con
->http
)),
2499 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2500 CUPS_LLCAST
httpGetLength2(con
->http
),
2502 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2503 con
->pipe_pid
, con
->file
);
2505 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2506 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2509 * If we get called in the wrong state, then something went wrong with the
2510 * connection and we need to shut it down...
2513 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2514 httpStateString(httpGetState(con
->http
)));
2515 cupsdCloseClient(con
);
2522 * Make sure we select on the CGI output...
2525 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2527 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2529 if (!con
->file_ready
)
2532 * Try again later when there is CGI output available...
2535 cupsdRemoveSelect(httpGetFd(con
->http
));
2539 con
->file_ready
= 0;
2542 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2544 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2547 * Limit GET bytes to original size of file (STR #3265)...
2550 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2553 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2555 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2560 * Write a single attribute or the IPP message header...
2563 ipp_state
= ippWrite(con
->http
, con
->response
);
2566 * If the write buffer has been flushed, stop buffering up attributes...
2569 if (httpGetPending(con
->http
) <= wused
)
2572 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2574 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2575 "Writing IPP response, ipp_state=%s, old "
2576 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2577 ippStateString(ipp_state
),
2578 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2580 if (httpGetPending(con
->http
) > 0)
2581 httpFlushWrite(con
->http
);
2583 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2584 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2586 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2587 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2588 (int)bytes
, httpGetState(con
->http
),
2589 CUPS_LLCAST
httpGetLength2(con
->http
));
2591 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2593 con
->header_used
+= bytes
;
2595 if (con
->pipe_pid
&& !con
->got_fields
)
2598 * Inspect the data for Content-Type and other fields.
2601 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2603 !con
->got_fields
&& bufptr
< bufend
;
2606 if (*bufptr
== '\n')
2609 * Send line to client...
2612 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2616 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2618 if (!con
->sent_header
)
2621 * Handle redirection and CGI status codes...
2624 http_field_t field
; /* HTTP field */
2625 char *value
= strchr(con
->header
, ':');
2626 /* Value of field */
2631 while (isspace(*value
& 255))
2635 field
= httpFieldValue(con
->header
);
2637 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2639 httpSetField(con
->http
, field
, value
);
2641 if (field
== HTTP_FIELD_LOCATION
)
2643 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2644 con
->sent_header
= 2;
2647 con
->sent_header
= 1;
2649 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2651 con
->pipe_status
= (http_status_t
)atoi(value
);
2652 con
->sent_header
= 2;
2654 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2656 httpSetCookie(con
->http
, value
);
2657 con
->sent_header
= 1;
2665 con
->header_used
-= bufptr
- con
->header
;
2667 if (con
->header_used
> 0)
2668 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2670 bufptr
= con
->header
- 1;
2673 * See if the line was empty...
2678 con
->got_fields
= 1;
2680 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2681 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2682 httpSetLength(con
->http
, 0);
2684 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2686 if (con
->pipe_status
== HTTP_STATUS_OK
)
2688 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2690 cupsdCloseClient(con
);
2696 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2698 cupsdCloseClient(con
);
2706 else if (*bufptr
!= '\r')
2710 if (!con
->got_fields
)
2714 if (con
->header_used
> 0)
2716 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2718 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2719 httpError(con
->http
), strerror(httpError(con
->http
)));
2720 cupsdCloseClient(con
);
2724 if (httpIsChunked(con
->http
))
2725 httpFlushWrite(con
->http
);
2727 con
->bytes
+= con
->header_used
;
2729 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2732 bytes
= con
->header_used
;
2734 con
->header_used
= 0;
2739 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2740 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2742 if (!con
->sent_header
&& con
->pipe_pid
)
2743 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2746 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2748 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2750 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2752 if (httpWrite2(con
->http
, "", 0) < 0)
2754 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2755 httpError(con
->http
), strerror(httpError(con
->http
)));
2756 cupsdCloseClient(con
);
2761 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2762 httpFlushWrite(con
->http
);
2763 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2766 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2768 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2772 cupsdRemoveSelect(con
->file
);
2775 cupsdEndProcess(con
->pipe_pid
, 0);
2784 unlink(con
->filename
);
2785 cupsdClearString(&con
->filename
);
2790 ippDelete(con
->request
);
2791 con
->request
= NULL
;
2796 ippDelete(con
->response
);
2797 con
->response
= NULL
;
2800 cupsdClearString(&con
->command
);
2801 cupsdClearString(&con
->options
);
2802 cupsdClearString(&con
->query_string
);
2804 if (!httpGetKeepAlive(con
->http
))
2806 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2807 "Closing because Keep-Alive is disabled.");
2808 cupsdCloseClient(con
);
2813 cupsArrayRemove(ActiveClients
, con
);
2814 cupsdSetBusyState();
2821 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2824 static int /* O - 1 if modified since */
2826 cupsd_client_t
*con
, /* I - Client connection */
2827 struct stat
*filestats
) /* I - File information */
2829 const char *ptr
; /* Pointer into field */
2830 time_t date
; /* Time/date value */
2831 off_t size
; /* Size/length value */
2836 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2841 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "check_if_modified: filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"", filestats
, CUPS_LLCAST filestats
->st_size
, (int)filestats
->st_mtime
, ptr
);
2843 while (*ptr
!= '\0')
2845 while (isspace(*ptr
) || *ptr
== ';')
2848 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2851 size
= strtoll(ptr
, NULL
, 10);
2853 while (isdigit(*ptr
))
2856 else if (isalpha(*ptr
))
2858 date
= httpGetDateTime(ptr
);
2859 while (*ptr
!= '\0' && *ptr
!= ';')
2866 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2867 (date
< filestats
->st_mtime
&& date
!= 0) ||
2868 (size
== 0 && date
== 0));
2873 * 'compare_clients()' - Compare two client connections.
2876 static int /* O - Result of comparison */
2877 compare_clients(cupsd_client_t
*a
, /* I - First client */
2878 cupsd_client_t
*b
, /* I - Second client */
2879 void *data
) /* I - User data (not used) */
2894 * 'cupsd_start_tls()' - Start encryption on a connection.
2897 static int /* O - 0 on success, -1 on error */
2898 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2899 http_encryption_t e
) /* I - Encryption mode */
2901 if (httpEncryption(con
->http
, e
))
2903 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2904 cupsLastErrorString());
2908 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Connection now encrypted.");
2911 #endif /* HAVE_SSL */
2915 * 'get_file()' - Get a filename and state info.
2918 static char * /* O - Real filename */
2919 get_file(cupsd_client_t
*con
, /* I - Client connection */
2920 struct stat
*filestats
, /* O - File information */
2921 char *filename
, /* IO - Filename buffer */
2922 size_t len
) /* I - Buffer length */
2924 int status
; /* Status of filesystem calls */
2925 char *ptr
; /* Pointer info filename */
2926 size_t plen
; /* Remaining length after pointer */
2927 char language
[7], /* Language subdirectory, if any */
2928 dest
[1024]; /* Destination name */
2929 int perm_check
= 1; /* Do permissions check? */
2933 * Figure out the real filename...
2938 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2940 strlcpy(dest
, con
->uri
+ 5, sizeof(dest
));
2941 ptr
= dest
+ strlen(dest
) - 4;
2943 if (ptr
<= dest
|| strcmp(ptr
, ".ppd"))
2945 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2950 if (!cupsdFindPrinter(dest
))
2952 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2956 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2960 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2962 strlcpy(dest
, con
->uri
+ 7, sizeof(dest
));
2963 ptr
= dest
+ strlen(dest
) - 4;
2965 if (ptr
<= dest
|| strcmp(ptr
, ".png"))
2967 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Disallowed path \"%s\".", con
->uri
);
2972 if (!cupsdFindDest(dest
))
2974 cupsdLogClient(con
, CUPSD_LOG_INFO
, "No printer \"%s\" found.", dest
);
2978 snprintf(filename
, len
, "%s/%s.png", CacheDir
, dest
);
2979 if (access(filename
, F_OK
) < 0)
2980 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2984 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2985 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2986 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2988 strlcpy(filename
, ConfigurationFile
, len
);
2992 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2994 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2995 strlcpy(filename
, AccessLog
, len
);
2996 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2997 strlcpy(filename
, ErrorLog
, len
);
2998 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2999 strlcpy(filename
, PageLog
, len
);
3005 else if (con
->language
)
3007 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3008 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3011 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3013 if ((ptr
= strchr(filename
, '?')) != NULL
)
3017 * Grab the status for this language; if there isn't a language-specific file
3018 * then fallback to the default one...
3021 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
3022 strncmp(con
->uri
, "/icons/", 7) &&
3023 strncmp(con
->uri
, "/ppd/", 5) &&
3024 strncmp(con
->uri
, "/rss/", 5) &&
3025 strncmp(con
->uri
, "/admin/conf/", 12) &&
3026 strncmp(con
->uri
, "/admin/log/", 11))
3029 * Drop the country code...
3033 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3035 if ((ptr
= strchr(filename
, '?')) != NULL
)
3038 if ((status
= lstat(filename
, filestats
)) != 0)
3041 * Drop the language prefix and try the root directory...
3045 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3047 if ((ptr
= strchr(filename
, '?')) != NULL
)
3050 status
= lstat(filename
, filestats
);
3055 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3058 if (!status
&& S_ISLNK(filestats
->st_mode
))
3060 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3065 * Similarly, if the file/directory does not have world read permissions, do
3066 * not allow access...
3069 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3071 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3076 * If we've found a directory, get the index.html file instead...
3079 if (!status
&& S_ISDIR(filestats
->st_mode
))
3082 * Make sure the URI ends with a slash...
3085 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3086 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3089 * Find the directory index file, trying every language...
3094 if (status
&& language
[0])
3097 * Try a different language subset...
3101 language
[0] = '\0'; /* Strip country code */
3103 language
[0] = '\0'; /* Strip language */
3107 * Look for the index file...
3110 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3112 if ((ptr
= strchr(filename
, '?')) != NULL
)
3115 ptr
= filename
+ strlen(filename
);
3116 plen
= len
- (size_t)(ptr
- filename
);
3118 strlcpy(ptr
, "index.html", plen
);
3119 status
= lstat(filename
, filestats
);
3124 strlcpy(ptr
, "index.class", plen
);
3125 status
= lstat(filename
, filestats
);
3127 #endif /* HAVE_JAVA */
3132 strlcpy(ptr
, "index.pl", plen
);
3133 status
= lstat(filename
, filestats
);
3135 #endif /* HAVE_PERL */
3140 strlcpy(ptr
, "index.php", plen
);
3141 status
= lstat(filename
, filestats
);
3143 #endif /* HAVE_PHP */
3148 strlcpy(ptr
, "index.pyc", plen
);
3149 status
= lstat(filename
, filestats
);
3154 strlcpy(ptr
, "index.py", plen
);
3155 status
= lstat(filename
, filestats
);
3157 #endif /* HAVE_PYTHON */
3160 while (status
&& language
[0]);
3163 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3166 if (!status
&& S_ISLNK(filestats
->st_mode
))
3168 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3173 * Similarly, if the file/directory does not have world read permissions, do
3174 * not allow access...
3177 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3179 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3184 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3194 * 'install_cupsd_conf()' - Install a configuration file.
3197 static http_status_t
/* O - Status */
3198 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3200 char filename
[1024]; /* Configuration filename */
3201 cups_file_t
*in
, /* Input file */
3202 *out
; /* Output file */
3203 char buffer
[16384]; /* Copy buffer */
3204 ssize_t bytes
; /* Number of bytes */
3208 * Open the request file...
3211 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3213 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3214 con
->filename
, strerror(errno
));
3219 * Open the new config file...
3222 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3228 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3232 * Copy from the request to the new config file...
3235 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3236 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3238 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3239 "Unable to copy to config file \"%s\": %s",
3240 ConfigurationFile
, strerror(errno
));
3245 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3246 cupsdUnlinkOrRemoveFile(filename
);
3252 * Close the files...
3257 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3261 * Remove the request file...
3264 cupsdUnlinkOrRemoveFile(con
->filename
);
3265 cupsdClearString(&con
->filename
);
3268 * Set the NeedReload flag...
3271 NeedReload
= RELOAD_CUPSD
;
3272 ReloadTime
= time(NULL
);
3275 * Return that the file was created successfully...
3278 return (HTTP_STATUS_CREATED
);
3281 * Common exit for errors...
3286 cupsdUnlinkOrRemoveFile(con
->filename
);
3287 cupsdClearString(&con
->filename
);
3289 return (HTTP_STATUS_SERVER_ERROR
);
3294 * 'is_cgi()' - Is the resource a CGI script/program?
3297 static int /* O - 1 = CGI, 0 = file */
3298 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3299 const char *filename
, /* I - Real filename */
3300 struct stat
*filestats
, /* I - File information */
3301 mime_type_t
*type
) /* I - MIME type */
3303 const char *options
; /* Options on URL */
3307 * Get the options, if any...
3310 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3313 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3317 * Check for known types...
3320 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3322 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
? type
->super
: "unknown", type
? type
->type
: "unknown");
3326 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3327 (filestats
->st_mode
& 0111))
3330 * "application/x-httpd-cgi" is a CGI script.
3333 cupsdSetString(&con
->command
, filename
);
3336 cupsdSetStringf(&con
->options
, " %s", options
);
3338 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3342 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3345 * "application/x-httpd-java" is a Java servlet.
3348 cupsdSetString(&con
->command
, CUPS_JAVA
);
3351 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3353 cupsdSetStringf(&con
->options
, " %s", filename
);
3355 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3358 #endif /* HAVE_JAVA */
3360 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3363 * "application/x-httpd-perl" is a Perl page.
3366 cupsdSetString(&con
->command
, CUPS_PERL
);
3369 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3371 cupsdSetStringf(&con
->options
, " %s", filename
);
3373 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3376 #endif /* HAVE_PERL */
3378 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3381 * "application/x-httpd-php" is a PHP page.
3384 cupsdSetString(&con
->command
, CUPS_PHP
);
3387 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3389 cupsdSetStringf(&con
->options
, " %s", filename
);
3391 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3394 #endif /* HAVE_PHP */
3396 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3399 * "application/x-httpd-python" is a Python page.
3402 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3405 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3407 cupsdSetStringf(&con
->options
, " %s", filename
);
3409 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename
, filestats
, type
->super
, type
->type
);
3412 #endif /* HAVE_PYTHON */
3414 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename
, filestats
, type
->super
, type
->type
);
3420 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3423 static int /* O - 0 if relative, 1 if absolute */
3424 is_path_absolute(const char *path
) /* I - Input path */
3427 * Check for a leading slash...
3434 * Check for "<" or quotes in the path and reject since this is probably
3435 * someone trying to inject HTML...
3438 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3442 * Check for "/.." in the path...
3445 while ((path
= strstr(path
, "/..")) != NULL
)
3447 if (!path
[3] || path
[3] == '/')
3454 * If we haven't found any relative paths, return 1 indicating an
3463 * 'pipe_command()' - Pipe the output of a command to the remote client.
3466 static int /* O - Process ID */
3467 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3468 int infile
, /* I - Standard input for command */
3469 int *outfile
, /* O - Standard output for command */
3470 char *command
, /* I - Command to run */
3471 char *options
, /* I - Options for command */
3472 int root
) /* I - Run as root? */
3474 int i
; /* Looping var */
3475 int pid
; /* Process ID */
3476 char *commptr
, /* Command string pointer */
3477 commch
; /* Command string character */
3478 char *uriptr
; /* URI string pointer */
3479 int fds
[2]; /* Pipe FDs */
3480 int argc
; /* Number of arguments */
3481 int envc
; /* Number of environment variables */
3482 char argbuf
[10240], /* Argument buffer */
3483 *argv
[100], /* Argument strings */
3484 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3485 char auth_type
[256], /* AUTH_TYPE environment variable */
3486 content_length
[1024], /* CONTENT_LENGTH environment variable */
3487 content_type
[1024], /* CONTENT_TYPE environment variable */
3488 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3489 http_referer
[1024], /* HTTP_REFERER environment variable */
3490 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3491 lang
[1024], /* LANG environment variable */
3492 path_info
[1024], /* PATH_INFO environment variable */
3493 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3494 remote_host
[1024], /* REMOTE_HOST environment variable */
3495 remote_user
[1024], /* REMOTE_USER environment variable */
3496 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3497 script_name
[1024], /* SCRIPT_NAME environment variable */
3498 server_name
[1024], /* SERVER_NAME environment variable */
3499 server_port
[1024]; /* SERVER_PORT environment variable */
3500 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3504 * Parse a copy of the options string, which is of the form:
3506 * argument+argument+argument
3507 * ?argument+argument+argument
3508 * param=value¶m=value
3509 * ?param=value¶m=value
3510 * /name?argument+argument+argument
3511 * /name?param=value¶m=value
3513 * If the string contains an "=" character after the initial name,
3514 * then we treat it as a HTTP GET form request and make a copy of
3515 * the remaining string for the environment variable.
3517 * The string is always parsed out as command-line arguments, to
3518 * be consistent with Apache...
3521 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile
, outfile
, command
, options
? options
: "(null)", root
);
3526 strlcpy(argbuf
, options
, sizeof(argbuf
));
3530 if (argbuf
[0] == '/')
3533 * Found some trailing path information, set PATH_INFO...
3536 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3537 commptr
= argbuf
+ strlen(argbuf
);
3541 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3547 path_info
[0] = '\0';
3549 if (*commptr
== ' ')
3553 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3556 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3563 argv
[argc
++] = commptr
;
3565 for (; *commptr
&& argc
< 99; commptr
++)
3568 * Break arguments whenever we see a + or space...
3571 if (*commptr
== ' ' || *commptr
== '+')
3573 while (*commptr
== ' ' || *commptr
== '+')
3577 * If we don't have a blank string, save it as another argument...
3582 argv
[argc
] = commptr
;
3588 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3589 isxdigit(commptr
[2] & 255))
3592 * Convert the %xx notation to the individual character.
3595 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3596 *commptr
= (char)((commptr
[1] - '0') << 4);
3598 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3600 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3601 *commptr
|= commptr
[2] - '0';
3603 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3605 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3608 * Check for a %00 and break if that is the case...
3620 * Setup the environment variables as needed...
3623 if (con
->username
[0])
3625 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3626 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3628 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3632 auth_type
[0] = '\0';
3635 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3636 IPP_TAG_LANGUAGE
)) != NULL
)
3638 switch (strlen(attr
->values
[0].string
.text
))
3642 * This is an unknown or badly formatted language code; use
3643 * the POSIX locale...
3646 strlcpy(lang
, "LANG=C", sizeof(lang
));
3651 * Just the language code (ll)...
3654 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3655 attr
->values
[0].string
.text
);
3660 * Language and country code (ll-cc)...
3663 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3664 attr
->values
[0].string
.text
[0],
3665 attr
->values
[0].string
.text
[1],
3666 toupper(attr
->values
[0].string
.text
[3] & 255),
3667 toupper(attr
->values
[0].string
.text
[4] & 255));
3671 else if (con
->language
)
3672 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3674 strlcpy(lang
, "LANG=C", sizeof(lang
));
3676 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3677 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3678 sizeof(remote_addr
) - 12);
3680 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3681 httpGetHostname(con
->http
, NULL
, 0));
3683 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3684 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3687 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3688 DocumentRoot
, script_name
+ 12);
3690 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3692 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3694 char *nameptr
; /* Pointer to ":port" */
3696 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3697 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3698 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3699 *nameptr
= '\0'; /* Strip trailing ":port" */
3702 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3705 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3708 envp
[envc
++] = auth_type
;
3710 envp
[envc
++] = lang
;
3711 envp
[envc
++] = "REDIRECT_STATUS=1";
3712 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3713 envp
[envc
++] = server_name
;
3714 envp
[envc
++] = server_port
;
3715 envp
[envc
++] = remote_addr
;
3716 envp
[envc
++] = remote_host
;
3717 envp
[envc
++] = script_name
;
3718 envp
[envc
++] = script_filename
;
3721 envp
[envc
++] = path_info
;
3723 if (con
->username
[0])
3725 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3727 envp
[envc
++] = remote_user
;
3730 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3731 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3732 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3733 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3735 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3737 if (httpGetCookie(con
->http
))
3739 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3740 httpGetCookie(con
->http
));
3741 envp
[envc
++] = http_cookie
;
3744 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3746 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3747 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3748 envp
[envc
++] = http_user_agent
;
3751 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3753 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3754 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3755 envp
[envc
++] = http_referer
;
3758 if (con
->operation
== HTTP_STATE_GET
)
3760 envp
[envc
++] = "REQUEST_METHOD=GET";
3762 if (con
->query_string
)
3765 * Add GET form variables after ?...
3768 envp
[envc
++] = con
->query_string
;
3771 envp
[envc
++] = "QUERY_STRING=";
3775 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3776 CUPS_LLCAST con
->bytes
);
3777 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3778 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3780 envp
[envc
++] = "REQUEST_METHOD=POST";
3781 envp
[envc
++] = content_length
;
3782 envp
[envc
++] = content_type
;
3786 * Tell the CGI if we are using encryption...
3789 if (httpIsEncrypted(con
->http
))
3790 envp
[envc
++] = "HTTPS=ON";
3793 * Terminate the environment array...
3798 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3800 for (i
= 0; i
< argc
; i
++)
3801 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3802 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3803 for (i
= 0; i
< envc
; i
++)
3804 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3805 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3809 * Create a pipe for the output...
3812 if (cupsdOpenPipe(fds
))
3814 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3815 argv
[0], strerror(errno
));
3820 * Then execute the command...
3823 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3824 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3827 * Error - can't fork!
3830 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3833 cupsdClosePipe(fds
);
3839 * Fork successful - return the PID...
3842 if (con
->username
[0])
3843 cupsdAddCert(pid
, con
->username
, con
->type
);
3845 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3856 * 'valid_host()' - Is the Host: field valid?
3859 static int /* O - 1 if valid, 0 if not */
3860 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3862 cupsd_alias_t
*a
; /* Current alias */
3863 cupsd_netif_t
*netif
; /* Current network interface */
3864 const char *end
; /* End character */
3865 char *ptr
; /* Pointer into host value */
3869 * Copy the Host: header for later use...
3872 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3873 sizeof(con
->clientname
));
3874 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3877 con
->clientport
= atoi(ptr
);
3880 con
->clientport
= con
->serverport
;
3886 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3889 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3890 * addresses when accessing CUPS via the loopback interface...
3893 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3894 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3896 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3897 #endif /* __linux */
3898 !strcmp(con
->clientname
, "127.0.0.1") ||
3899 !strcmp(con
->clientname
, "[::1]"));
3902 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3904 * Check if the hostname is something.local (Bonjour); if so, allow it.
3907 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3911 * "." on end, work back to second-to-last "."...
3914 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3917 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3918 !_cups_strcasecmp(end
, ".local.")))
3920 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3923 * Check if the hostname is an IP address...
3926 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3929 * Possible IPv4/IPv6 address...
3932 http_addrlist_t
*addrlist
; /* List of addresses */
3935 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3938 * Good IPv4/IPv6 address...
3941 httpAddrFreeList(addrlist
);
3947 * Check for (alias) name matches...
3950 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3952 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3955 * "ServerAlias *" allows all host values through...
3958 if (!strcmp(a
->name
, "*"))
3961 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3964 * Prefix matches; check the character at the end - it must be "." or nul.
3967 end
= con
->clientname
+ a
->namelen
;
3969 if (!*end
|| (*end
== '.' && !end
[1]))
3974 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3975 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3977 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3980 * "ServerAlias *" allows all host values through...
3983 if (!strcmp(a
->name
, "*"))
3986 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3989 * Prefix matches; check the character at the end - it must be "." or nul.
3992 end
= con
->clientname
+ a
->namelen
;
3994 if (!*end
|| (*end
== '.' && !end
[1]))
3998 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4001 * Check for interface hostname matches...
4004 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4006 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4008 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4011 * Prefix matches; check the character at the end - it must be "." or nul.
4014 end
= con
->clientname
+ netif
->hostlen
;
4016 if (!*end
|| (*end
== '.' && !end
[1]))
4026 * 'write_file()' - Send a file via HTTP.
4029 static int /* O - 0 on failure, 1 on success */
4030 write_file(cupsd_client_t
*con
, /* I - Client connection */
4031 http_status_t code
, /* I - HTTP status */
4032 char *filename
, /* I - Filename */
4033 char *type
, /* I - File type */
4034 struct stat
*filestats
) /* O - File information */
4036 con
->file
= open(filename
, O_RDONLY
);
4038 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4043 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4046 con
->sent_header
= 1;
4048 httpClearFields(con
->http
);
4050 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
4052 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
4053 httpGetDateString(filestats
->st_mtime
));
4055 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4058 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4060 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4067 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4071 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4073 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d.", con
->file
);
4075 con
->file_ready
= 1;
4077 cupsdRemoveSelect(con
->file
);
4078 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4080 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");