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
,
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
;
151 * Check the number of clients on the same address...
154 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
156 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
157 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
160 if (count
>= MaxClientsPerHost
)
164 if (count
>= MaxClientsPerHost
)
166 if ((time(NULL
) - last_dos
) >= 60)
168 last_dos
= time(NULL
);
169 cupsdLogMessage(CUPSD_LOG_WARN
,
170 "Possible DoS attack - more than %d clients connecting "
173 httpGetHostname(con
->http
, name
, sizeof(name
)));
176 httpClose(con
->http
);
182 * Get the hostname or format the IP address as needed...
186 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
188 hostname
= httpGetHostname(con
->http
, NULL
, 0);
190 if (hostname
== NULL
&& HostNameLookups
== 2)
193 * Can't have an unresolved IP address with double-lookups enabled...
196 httpClose(con
->http
);
198 cupsdLogClient(con
, CUPSD_LOG_WARN
,
199 "Name lookup failed - connection from %s closed!",
200 httpGetHostname(con
->http
, NULL
, 0));
206 if (HostNameLookups
== 2)
209 * Do double lookups as needed...
212 http_addrlist_t
*addrlist
, /* List of addresses */
213 *addr
; /* Current address */
215 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
218 * See if the hostname maps to the same IP address...
221 for (addr
= addrlist
; addr
; addr
= addr
->next
)
222 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
228 httpAddrFreeList(addrlist
);
233 * Can't have a hostname that doesn't resolve to the same IP address
234 * with double-lookups enabled...
237 httpClose(con
->http
);
239 cupsdLogClient(con
, CUPSD_LOG_WARN
,
240 "IP lookup failed - connection from %s closed!",
241 httpGetHostname(con
->http
, NULL
, 0));
249 * See if the connection is denied by TCP wrappers...
252 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
256 if (!hosts_access(&wrap_req
))
258 httpClose(con
->http
);
260 cupsdLogClient(con
, CUPSD_LOG_WARN
,
261 "Connection from %s refused by /etc/hosts.allow and "
262 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
266 #endif /* HAVE_TCPD_H */
269 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
272 socklen_t peersize
; /* Size of peer credentials */
273 pid_t peerpid
; /* Peer process ID */
274 char peername
[256]; /* Name of process */
276 peersize
= sizeof(peerpid
);
277 if (!getsockopt(httpGetFd(con
->http
), SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
280 if (!proc_name((int)peerpid
, peername
, sizeof(peername
)))
281 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
282 "Accepted from %s (Domain ???[%d])",
283 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
285 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
286 "Accepted from %s (Domain %s[%d])",
287 httpGetHostname(con
->http
, NULL
, 0), peername
, (int)peerpid
);
290 # endif /* __APPLE__ */
292 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
293 httpGetHostname(con
->http
, NULL
, 0));
296 #endif /* AF_LOCAL */
297 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
298 httpGetHostname(con
->http
, NULL
, 0),
299 httpAddrPort(httpGetAddress(con
->http
)),
300 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
303 * Get the local address the client connected to...
306 addrlen
= sizeof(temp
);
307 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
309 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
312 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
313 con
->serverport
= LocalPort
;
316 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
318 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
319 con
->serverport
= LocalPort
;
321 #endif /* AF_LOCAL */
324 if (httpAddrLocalhost(&temp
))
325 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
326 else if (HostNameLookups
)
327 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
329 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
331 con
->serverport
= httpAddrPort(&(lis
->address
));
335 * Add the connection to the array of active clients...
338 cupsArrayAdd(Clients
, con
);
341 * Add the socket to the server select.
344 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
347 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
350 * Temporarily suspend accept()'s until we lose a client...
353 if (cupsArrayCount(Clients
) == MaxClients
)
354 cupsdPauseListening();
358 * See if we are connecting on a secure port...
361 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
364 * https connection; go secure...
367 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
368 cupsdCloseClient(con
);
372 #endif /* HAVE_SSL */
377 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
381 cupsdCloseAllClients(void)
383 cupsd_client_t
*con
; /* Current client */
386 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
387 cupsArrayCount(Clients
));
389 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
391 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
392 if (cupsdCloseClient(con
))
393 cupsdCloseClient(con
);
398 * 'cupsdCloseClient()' - Close a remote client.
401 int /* O - 1 if partial close, 0 if fully closed */
402 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
404 int partial
; /* Do partial close for SSL? */
407 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
410 * Flush pending writes before closing...
413 httpFlushWrite(con
->http
);
417 if (con
->pipe_pid
!= 0)
420 * Stop any CGI process...
423 cupsdEndProcess(con
->pipe_pid
, 1);
429 cupsdRemoveSelect(con
->file
);
436 * Close the socket and clear the file from the input set for select()...
439 if (httpGetFd(con
->http
) >= 0)
441 cupsArrayRemove(ActiveClients
, con
);
446 * Shutdown encryption as needed...
449 if (httpIsEncrypted(con
->http
))
451 #endif /* HAVE_SSL */
456 * Only do a partial close so that the encrypted client gets everything.
459 httpShutdown(con
->http
);
460 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
463 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
468 * Shut the socket down fully...
471 cupsdRemoveSelect(httpGetFd(con
->http
));
472 httpClose(con
->http
);
483 cupsdRemoveSelect(httpGetFd(con
->http
));
485 httpClose(con
->http
);
489 unlink(con
->filename
);
490 cupsdClearString(&con
->filename
);
493 cupsdClearString(&con
->command
);
494 cupsdClearString(&con
->options
);
495 cupsdClearString(&con
->query_string
);
499 ippDelete(con
->request
);
505 ippDelete(con
->response
);
506 con
->response
= NULL
;
511 cupsLangFree(con
->language
);
512 con
->language
= NULL
;
515 #ifdef HAVE_AUTHORIZATION_H
518 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
521 #endif /* HAVE_AUTHORIZATION_H */
524 * Re-enable new client connections if we are going back under the
528 if (cupsArrayCount(Clients
) == MaxClients
)
529 cupsdResumeListening();
532 * Compact the list of clients as necessary...
535 cupsArrayRemove(Clients
, con
);
545 * 'cupsdReadClient()' - Read data from a client.
549 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
551 char line
[32768], /* Line from client... */
552 locale
[64], /* Locale */
553 *ptr
; /* Pointer into strings */
554 http_status_t status
; /* Transfer status */
555 ipp_state_t ipp_state
; /* State of IPP transfer */
556 int bytes
; /* Number of bytes to POST */
557 char *filename
; /* Name of file for GET/HEAD */
558 char buf
[1024]; /* Buffer for real filename */
559 struct stat filestats
; /* File information */
560 mime_type_t
*type
; /* MIME type of file */
561 cupsd_printer_t
*p
; /* Printer */
562 static unsigned request_id
= 0; /* Request ID for temp files */
565 status
= HTTP_STATUS_CONTINUE
;
567 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
572 "data_encoding=HTTP_ENCODING_%s, "
573 "data_remaining=" CUPS_LLFMT
", "
576 httpError(con
->http
), (int)httpGetReady(con
->http
),
577 httpStateString(httpGetState(con
->http
)),
578 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
579 CUPS_LLCAST
httpGetRemaining(con
->http
),
581 con
->request
? ippStateString(ippGetState(con
->request
)) : "",
584 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
585 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
586 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
589 * If we get called in the wrong state, then something went wrong with the
590 * connection and we need to shut it down...
593 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
596 * Connection closed...
599 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
600 cupsdCloseClient(con
);
604 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.",
605 httpStateString(httpGetState(con
->http
)));
606 cupsdCloseClient(con
);
614 * Automatically check for a SSL/TLS handshake...
619 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
620 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
623 * Encrypt this connection...
626 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
627 "Saw first byte %02X, auto-negotiating "
628 "SSL/TLS session.", buf
[0] & 255);
630 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
631 cupsdCloseClient(con
);
636 #endif /* HAVE_SSL */
638 switch (httpGetState(con
->http
))
640 case HTTP_STATE_WAITING
:
642 * See if we've received a request line...
645 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
646 if (con
->operation
== HTTP_STATE_ERROR
||
647 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
648 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
650 if (httpError(con
->http
))
651 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
652 "HTTP_STATE_WAITING Closing for error %d (%s)",
653 httpError(con
->http
), strerror(httpError(con
->http
)));
655 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
656 "HTTP_STATE_WAITING Closing on error: %s",
657 cupsLastErrorString());
659 cupsdCloseClient(con
);
664 * Ignore blank request lines...
667 if (con
->operation
== HTTP_STATE_WAITING
)
671 * Clear other state variables...
678 con
->username
[0] = '\0';
679 con
->password
[0] = '\0';
681 cupsdClearString(&con
->command
);
682 cupsdClearString(&con
->options
);
683 cupsdClearString(&con
->query_string
);
687 ippDelete(con
->request
);
693 ippDelete(con
->response
);
694 con
->response
= NULL
;
699 cupsLangFree(con
->language
);
700 con
->language
= NULL
;
706 #endif /* HAVE_GSSAPI */
709 * Handle full URLs in the request line...
712 if (strcmp(con
->uri
, "*"))
714 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
715 userpass
[HTTP_MAX_URI
], /* Username:password */
716 hostname
[HTTP_MAX_URI
], /* Hostname */
717 resource
[HTTP_MAX_URI
]; /* Resource path */
718 int port
; /* Port number */
721 * Separate the URI into its components...
724 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
725 scheme
, sizeof(scheme
),
726 userpass
, sizeof(userpass
),
727 hostname
, sizeof(hostname
), &port
,
728 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
730 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
732 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
733 cupsdCloseClient(con
);
738 * Only allow URIs with the servername, localhost, or an IP
742 if (strcmp(scheme
, "file") &&
743 _cups_strcasecmp(hostname
, ServerName
) &&
744 _cups_strcasecmp(hostname
, "localhost") &&
745 !cupsArrayFind(ServerAlias
, hostname
) &&
746 !isdigit(hostname
[0]) && hostname
[0] != '[')
749 * Nope, we don't do proxies...
752 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
754 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
755 cupsdCloseClient(con
);
760 * Copy the resource portion back into the URI; both resource and
761 * con->uri are HTTP_MAX_URI bytes in size...
764 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
768 * Process the request...
771 gettimeofday(&(con
->start
), NULL
);
773 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
774 httpStateString(con
->operation
) + 11, con
->uri
,
775 httpGetVersion(con
->http
) / 100,
776 httpGetVersion(con
->http
) % 100);
778 if (!cupsArrayFind(ActiveClients
, con
))
780 cupsArrayAdd(ActiveClients
, con
);
784 case HTTP_STATE_OPTIONS
:
785 case HTTP_STATE_DELETE
:
786 case HTTP_STATE_GET
:
787 case HTTP_STATE_HEAD
:
788 case HTTP_STATE_POST
:
789 case HTTP_STATE_PUT
:
790 case HTTP_STATE_TRACE
:
792 * Parse incoming parameters until the status changes...
795 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
796 if (!httpGetReady(con
->http
))
799 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
801 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
802 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
803 "Closing for error %d (%s) while reading headers.",
804 httpError(con
->http
), strerror(httpError(con
->http
)));
806 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
807 "Closing on EOF while reading headers.");
809 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
810 cupsdCloseClient(con
);
816 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
819 * Connection closed...
822 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
823 cupsdCloseClient(con
);
826 break; /* Anti-compiler-warning-code */
830 * Handle new transfers...
833 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d", status
);
835 if (status
== HTTP_STATUS_OK
)
837 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
840 * Figure out the locale from the Accept-Language and Content-Type
844 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
848 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
852 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
853 "charset=")) != NULL
)
856 * Combine language and charset, and trim any extra params in the
860 snprintf(locale
, sizeof(locale
), "%s.%s",
861 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
863 if ((ptr
= strchr(locale
, ',')) != NULL
)
867 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
868 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
870 con
->language
= cupsLangGet(locale
);
873 con
->language
= cupsLangGet(DefaultLocale
);
877 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
878 "Keep-Alive", 10) && KeepAlive
)
879 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
880 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
882 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
884 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
885 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
888 * HTTP/1.1 and higher require the "Host:" field...
891 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
893 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
894 cupsdCloseClient(con
);
898 else if (!valid_host(con
))
901 * Access to localhost must use "localhost" or the corresponding IPv4
902 * or IPv6 values in the Host: field.
905 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
906 "Request from \"%s\" using invalid Host: field \"%s\".",
907 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
909 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
911 cupsdCloseClient(con
);
915 else if (con
->operation
== HTTP_STATE_OPTIONS
)
918 * Do OPTIONS command...
921 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
923 httpClearFields(con
->http
);
925 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
927 cupsdCloseClient(con
);
932 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") && strstr(httpGetField(con
->http
, HTTP_FIELD_UPGRADE
), "TLS/") != NULL
&& !httpIsEncrypted(con
->http
))
936 * Do encryption stuff...
939 httpClearFields(con
->http
);
941 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
943 cupsdCloseClient(con
);
947 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
949 cupsdCloseClient(con
);
953 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
955 cupsdCloseClient(con
);
958 #endif /* HAVE_SSL */
961 httpClearFields(con
->http
);
962 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
963 "GET, HEAD, OPTIONS, POST, PUT");
964 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
966 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
968 cupsdCloseClient(con
);
972 else if (!is_path_absolute(con
->uri
))
975 * Protect against malicious users!
978 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
979 "Request for non-absolute resource \"%s\".", con
->uri
);
981 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
983 cupsdCloseClient(con
);
989 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
990 "Upgrade") && !httpIsEncrypted(con
->http
))
994 * Do encryption stuff...
997 httpClearFields(con
->http
);
999 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1002 cupsdCloseClient(con
);
1006 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
1008 cupsdCloseClient(con
);
1012 if (!cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1014 cupsdCloseClient(con
);
1017 #endif /* HAVE_SSL */
1020 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1022 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1023 cupsdCloseClient(con
);
1027 if (httpGetExpect(con
->http
) &&
1028 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1030 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1033 * Send 100-continue header...
1036 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1038 cupsdCloseClient(con
);
1045 * Send 417-expectation-failed header...
1048 httpClearFields(con
->http
);
1049 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1051 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1052 cupsdCloseClient(con
);
1057 switch (httpGetState(con
->http
))
1059 case HTTP_STATE_GET_SEND
:
1060 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1062 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1063 !strncmp(con
->uri
, "/printers/", 10) ||
1064 !strncmp(con
->uri
, "/classes/", 9)) &&
1065 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1068 * Send PPD file - get the real printer name since printer
1069 * names are not case sensitive but filenames can be...
1072 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1074 if (!strncmp(con
->uri
, "/ppd/", 5))
1075 p
= cupsdFindPrinter(con
->uri
+ 5);
1076 else if (!strncmp(con
->uri
, "/printers/", 10))
1077 p
= cupsdFindPrinter(con
->uri
+ 10);
1080 p
= cupsdFindClass(con
->uri
+ 9);
1084 int i
; /* Looping var */
1086 for (i
= 0; i
< p
->num_printers
; i
++)
1088 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1090 char ppdname
[1024];/* PPD filename */
1092 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1093 ServerRoot
, p
->printers
[i
]->name
);
1094 if (!access(ppdname
, 0))
1102 if (i
>= p
->num_printers
)
1109 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1113 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1115 cupsdCloseClient(con
);
1122 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1123 !strncmp(con
->uri
, "/printers/", 10) ||
1124 !strncmp(con
->uri
, "/classes/", 9)) &&
1125 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1128 * Send icon file - get the real queue name since queue names are
1129 * not case sensitive but filenames can be...
1132 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1134 if (!strncmp(con
->uri
, "/icons/", 7))
1135 p
= cupsdFindPrinter(con
->uri
+ 7);
1136 else if (!strncmp(con
->uri
, "/printers/", 10))
1137 p
= cupsdFindPrinter(con
->uri
+ 10);
1140 p
= cupsdFindClass(con
->uri
+ 9);
1144 int i
; /* Looping var */
1146 for (i
= 0; i
< p
->num_printers
; i
++)
1148 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1150 char ppdname
[1024];/* PPD filename */
1152 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1153 ServerRoot
, p
->printers
[i
]->name
);
1154 if (!access(ppdname
, 0))
1162 if (i
>= p
->num_printers
)
1168 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1171 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1173 cupsdCloseClient(con
);
1180 else if (!WebInterface
)
1183 * Web interface is disabled. Show an appropriate message...
1186 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1188 cupsdCloseClient(con
);
1195 if ((!strncmp(con
->uri
, "/admin", 6) &&
1196 strncmp(con
->uri
, "/admin/conf/", 12) &&
1197 strncmp(con
->uri
, "/admin/log/", 11)) ||
1198 !strncmp(con
->uri
, "/printers", 9) ||
1199 !strncmp(con
->uri
, "/classes", 8) ||
1200 !strncmp(con
->uri
, "/help", 5) ||
1201 !strncmp(con
->uri
, "/jobs", 5))
1204 * Send CGI output...
1207 if (!strncmp(con
->uri
, "/admin", 6))
1209 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1212 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1214 else if (!strncmp(con
->uri
, "/printers", 9))
1216 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1219 if (con
->uri
[9] && con
->uri
[10])
1220 cupsdSetString(&con
->options
, con
->uri
+ 9);
1222 cupsdSetString(&con
->options
, NULL
);
1224 else if (!strncmp(con
->uri
, "/classes", 8))
1226 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1229 if (con
->uri
[8] && con
->uri
[9])
1230 cupsdSetString(&con
->options
, con
->uri
+ 8);
1232 cupsdSetString(&con
->options
, NULL
);
1234 else if (!strncmp(con
->uri
, "/jobs", 5))
1236 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1239 if (con
->uri
[5] && con
->uri
[6])
1240 cupsdSetString(&con
->options
, con
->uri
+ 5);
1242 cupsdSetString(&con
->options
, NULL
);
1246 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1249 if (con
->uri
[5] && con
->uri
[6])
1250 cupsdSetString(&con
->options
, con
->uri
+ 5);
1252 cupsdSetString(&con
->options
, NULL
);
1255 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1257 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1259 cupsdCloseClient(con
);
1264 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1266 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1267 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1269 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1270 (strchr(con
->uri
+ 12, '/') ||
1271 strlen(con
->uri
) == 12)) ||
1272 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1273 (strchr(con
->uri
+ 11, '/') ||
1274 strlen(con
->uri
) == 11)))
1277 * GET can only be done to configuration files directly under
1281 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1282 "Request for subdirectory \"%s\"!", con
->uri
);
1284 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1286 cupsdCloseClient(con
);
1298 if ((filename
= get_file(con
, &filestats
, buf
,
1299 sizeof(buf
))) == NULL
)
1301 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1303 cupsdCloseClient(con
);
1310 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1312 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1314 if (is_cgi(con
, filename
, &filestats
, type
))
1317 * Note: con->command and con->options were set by
1321 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1323 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1325 cupsdCloseClient(con
);
1330 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1332 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1333 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1337 if (!check_if_modified(con
, &filestats
))
1339 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1341 cupsdCloseClient(con
);
1348 strlcpy(line
, "text/plain", sizeof(line
));
1350 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1352 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1354 cupsdCloseClient(con
);
1361 case HTTP_STATE_POST_RECV
:
1363 * See if the POST request includes a Content-Length field, and if
1364 * so check the length against any limits that are set...
1367 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1368 MaxRequestSize
> 0 &&
1369 httpGetLength2(con
->http
) > MaxRequestSize
)
1372 * Request too large...
1375 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1377 cupsdCloseClient(con
);
1383 else if (httpGetLength2(con
->http
) < 0)
1386 * Negative content lengths are invalid!
1389 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1391 cupsdCloseClient(con
);
1399 * See what kind of POST request this is; for IPP requests the
1400 * content-type field will be "application/ipp"...
1403 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1405 con
->request
= ippNew();
1406 else if (!WebInterface
)
1409 * Web interface is disabled. Show an appropriate message...
1412 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1414 cupsdCloseClient(con
);
1420 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1421 strncmp(con
->uri
, "/admin/conf/", 12) &&
1422 strncmp(con
->uri
, "/admin/log/", 11)) ||
1423 !strncmp(con
->uri
, "/printers", 9) ||
1424 !strncmp(con
->uri
, "/classes", 8) ||
1425 !strncmp(con
->uri
, "/help", 5) ||
1426 !strncmp(con
->uri
, "/jobs", 5))
1432 if (!strncmp(con
->uri
, "/admin", 6))
1434 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1437 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1439 else if (!strncmp(con
->uri
, "/printers", 9))
1441 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1444 if (con
->uri
[9] && con
->uri
[10])
1445 cupsdSetString(&con
->options
, con
->uri
+ 9);
1447 cupsdSetString(&con
->options
, NULL
);
1449 else if (!strncmp(con
->uri
, "/classes", 8))
1451 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1454 if (con
->uri
[8] && con
->uri
[9])
1455 cupsdSetString(&con
->options
, con
->uri
+ 8);
1457 cupsdSetString(&con
->options
, NULL
);
1459 else if (!strncmp(con
->uri
, "/jobs", 5))
1461 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1464 if (con
->uri
[5] && con
->uri
[6])
1465 cupsdSetString(&con
->options
, con
->uri
+ 5);
1467 cupsdSetString(&con
->options
, NULL
);
1471 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1474 if (con
->uri
[5] && con
->uri
[6])
1475 cupsdSetString(&con
->options
, con
->uri
+ 5);
1477 cupsdSetString(&con
->options
, NULL
);
1480 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1481 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1489 if ((filename
= get_file(con
, &filestats
, buf
,
1490 sizeof(buf
))) == NULL
)
1492 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1494 cupsdCloseClient(con
);
1501 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1503 if (!is_cgi(con
, filename
, &filestats
, type
))
1506 * Only POST to CGI's...
1509 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1511 cupsdCloseClient(con
);
1518 case HTTP_STATE_PUT_RECV
:
1520 * Validate the resource name...
1523 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1526 * PUT can only be done to the cupsd.conf file...
1529 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1530 "Disallowed PUT request for \"%s\".", con
->uri
);
1532 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1534 cupsdCloseClient(con
);
1542 * See if the PUT request includes a Content-Length field, and if
1543 * so check the length against any limits that are set...
1546 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1547 MaxRequestSize
> 0 &&
1548 httpGetLength2(con
->http
) > MaxRequestSize
)
1551 * Request too large...
1554 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1556 cupsdCloseClient(con
);
1562 else if (httpGetLength2(con
->http
) < 0)
1565 * Negative content lengths are invalid!
1568 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1570 cupsdCloseClient(con
);
1578 * Open a temporary file to hold the request...
1581 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1583 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1587 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1588 "Unable to create request file \"%s\": %s",
1589 con
->filename
, strerror(errno
));
1591 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1593 cupsdCloseClient(con
);
1598 fchmod(con
->file
, 0640);
1599 fchown(con
->file
, RunUser
, Group
);
1600 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1603 case HTTP_STATE_DELETE
:
1604 case HTTP_STATE_TRACE
:
1605 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1606 cupsdCloseClient(con
);
1609 case HTTP_STATE_HEAD
:
1610 if (!strncmp(con
->uri
, "/printers/", 10) &&
1611 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1614 * Send PPD file - get the real printer name since printer
1615 * names are not case sensitive but filenames can be...
1618 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1620 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1621 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1624 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1626 cupsdCloseClient(con
);
1630 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1634 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1635 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1638 * Send PNG file - get the real printer name since printer
1639 * names are not case sensitive but filenames can be...
1642 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1644 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1645 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1648 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1650 cupsdCloseClient(con
);
1654 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1658 else if (!WebInterface
)
1660 httpClearFields(con
->http
);
1662 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1664 cupsdCloseClient(con
);
1668 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1672 if ((!strncmp(con
->uri
, "/admin", 6) &&
1673 strncmp(con
->uri
, "/admin/conf/", 12) &&
1674 strncmp(con
->uri
, "/admin/log/", 11)) ||
1675 !strncmp(con
->uri
, "/printers", 9) ||
1676 !strncmp(con
->uri
, "/classes", 8) ||
1677 !strncmp(con
->uri
, "/help", 5) ||
1678 !strncmp(con
->uri
, "/jobs", 5))
1684 httpClearFields(con
->http
);
1686 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1688 cupsdCloseClient(con
);
1692 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1694 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1695 (strchr(con
->uri
+ 12, '/') ||
1696 strlen(con
->uri
) == 12)) ||
1697 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1698 (strchr(con
->uri
+ 11, '/') ||
1699 strlen(con
->uri
) == 11)))
1702 * HEAD can only be done to configuration files under
1706 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1707 "Request for subdirectory \"%s\".", con
->uri
);
1709 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1711 cupsdCloseClient(con
);
1715 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1718 else if ((filename
= get_file(con
, &filestats
, buf
,
1719 sizeof(buf
))) == NULL
)
1721 httpClearFields(con
->http
);
1723 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1726 cupsdCloseClient(con
);
1730 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1732 else if (!check_if_modified(con
, &filestats
))
1734 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1736 cupsdCloseClient(con
);
1740 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1748 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1750 strlcpy(line
, "text/plain", sizeof(line
));
1752 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1754 httpClearFields(con
->http
);
1756 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1757 httpGetDateString(filestats
.st_mtime
));
1758 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1760 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1762 cupsdCloseClient(con
);
1766 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1771 break; /* Anti-compiler-warning-code */
1777 * Handle any incoming data...
1780 switch (httpGetState(con
->http
))
1782 case HTTP_STATE_PUT_RECV
:
1785 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1787 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1788 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1789 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1790 httpError(con
->http
), strerror(httpError(con
->http
)));
1792 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1793 "HTTP_STATE_PUT_RECV Closing on EOF.");
1795 cupsdCloseClient(con
);
1800 con
->bytes
+= bytes
;
1802 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1806 unlink(con
->filename
);
1807 cupsdClearString(&con
->filename
);
1809 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1811 cupsdCloseClient(con
);
1816 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1818 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1819 "Unable to write %d bytes to \"%s\": %s", bytes
,
1820 con
->filename
, strerror(errno
));
1824 unlink(con
->filename
);
1825 cupsdClearString(&con
->filename
);
1827 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1829 cupsdCloseClient(con
);
1837 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1839 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1842 * End of file, see how big it is...
1845 fstat(con
->file
, &filestats
);
1850 if (filestats
.st_size
> MaxRequestSize
&&
1854 * Request is too big; remove it and send an error...
1857 unlink(con
->filename
);
1858 cupsdClearString(&con
->filename
);
1860 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1862 cupsdCloseClient(con
);
1868 * Install the configuration file...
1871 status
= install_cupsd_conf(con
);
1874 * Return the status to the client...
1877 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1879 cupsdCloseClient(con
);
1885 case HTTP_STATE_POST_RECV
:
1888 if (con
->request
&& con
->file
< 0)
1891 * Grab any request data from the connection...
1894 if (!httpWait(con
->http
, 0))
1897 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1899 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1900 cupsLastErrorString());
1902 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1903 cupsdCloseClient(con
);
1906 else if (ipp_state
!= IPP_STATE_DATA
)
1908 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1910 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1911 cupsdCloseClient(con
);
1915 if (httpGetReady(con
->http
))
1921 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1922 con
->request
->request
.op
.version
[0],
1923 con
->request
->request
.op
.version
[1],
1924 ippOpString(con
->request
->request
.op
.operation_id
),
1925 con
->request
->request
.op
.request_id
);
1926 con
->bytes
+= (off_t
)ippLength(con
->request
);
1930 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1933 * Create a file as needed for the request data...
1936 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1938 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1942 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1943 "Unable to create request file \"%s\": %s",
1944 con
->filename
, strerror(errno
));
1946 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1948 cupsdCloseClient(con
);
1953 fchmod(con
->file
, 0640);
1954 fchown(con
->file
, RunUser
, Group
);
1955 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1958 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1960 if (!httpWait(con
->http
, 0))
1962 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1964 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1965 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1966 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1967 httpError(con
->http
), strerror(httpError(con
->http
)));
1969 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1970 "HTTP_STATE_POST_SEND Closing on EOF.");
1972 cupsdCloseClient(con
);
1977 con
->bytes
+= bytes
;
1979 if (MaxRequestSize
> 0 && con
->bytes
> MaxRequestSize
)
1983 unlink(con
->filename
);
1984 cupsdClearString(&con
->filename
);
1986 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1988 cupsdCloseClient(con
);
1993 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1995 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1996 "Unable to write %d bytes to \"%s\": %s",
1997 bytes
, con
->filename
, strerror(errno
));
2001 unlink(con
->filename
);
2002 cupsdClearString(&con
->filename
);
2004 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
2007 cupsdCloseClient(con
);
2012 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
2014 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2016 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2017 "Closing on unexpected state %s.",
2018 httpStateString(httpGetState(con
->http
)));
2019 cupsdCloseClient(con
);
2024 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
2026 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2030 fstat(con
->file
, &filestats
);
2035 if (filestats
.st_size
> MaxRequestSize
&&
2039 * Request is too big; remove it and send an error...
2042 unlink(con
->filename
);
2043 cupsdClearString(&con
->filename
);
2048 * Delete any IPP request data...
2051 ippDelete(con
->request
);
2052 con
->request
= NULL
;
2055 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2057 cupsdCloseClient(con
);
2061 else if (filestats
.st_size
== 0)
2064 * Don't allow empty file...
2067 unlink(con
->filename
);
2068 cupsdClearString(&con
->filename
);
2073 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2075 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2077 cupsdCloseClient(con
);
2082 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2088 cupsdProcessIPPRequest(con
);
2092 unlink(con
->filename
);
2093 cupsdClearString(&con
->filename
);
2102 break; /* Anti-compiler-warning-code */
2105 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2107 if (!httpGetKeepAlive(con
->http
))
2109 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2110 "Closing because Keep-Alive is disabled.");
2111 cupsdCloseClient(con
);
2115 cupsArrayRemove(ActiveClients
, con
);
2116 cupsdSetBusyState();
2123 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2126 int /* O - 1 on success, 0 on failure */
2128 cupsd_client_t
*con
, /* I - Client connection */
2129 char *command
, /* I - Command to run */
2130 char *options
, /* I - Command-line options */
2131 int root
) /* I - Run as root? */
2133 int fd
; /* Standard input file descriptor */
2138 fd
= open(con
->filename
, O_RDONLY
);
2142 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2143 "Unable to open \"%s\" for reading: %s",
2144 con
->filename
? con
->filename
: "/dev/null",
2149 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2154 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2155 con
->pipe_status
= HTTP_STATUS_OK
;
2157 httpClearFields(con
->http
);
2162 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2163 command
, con
->pipe_pid
, con
->file
);
2165 if (con
->pipe_pid
== 0)
2168 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2170 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2172 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2174 con
->sent_header
= 0;
2175 con
->file_ready
= 0;
2176 con
->got_fields
= 0;
2177 con
->header_used
= 0;
2184 * 'cupsdSendError()' - Send an error message via HTTP.
2187 int /* O - 1 if successful, 0 otherwise */
2188 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2189 http_status_t code
, /* I - Error code */
2190 int auth_type
)/* I - Authentication type */
2192 char location
[HTTP_MAX_VALUE
]; /* Location field */
2195 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2200 * Force client to upgrade for authentication if that is how the
2201 * server is configured...
2204 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2205 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2206 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2207 !httpIsEncrypted(con
->http
))
2209 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2211 #endif /* HAVE_SSL */
2214 * Put the request in the access_log file...
2217 cupsdLogRequest(con
, code
);
2220 * To work around bugs in some proxies, don't use Keep-Alive for some
2223 * Kerberos authentication doesn't work without Keep-Alive, so
2224 * never disable it in that case.
2227 strlcpy(location
, httpGetField(con
->http
, HTTP_FIELD_LOCATION
), sizeof(location
));
2229 httpClearFields(con
->http
);
2231 httpSetField(con
->http
, HTTP_FIELD_LOCATION
, location
);
2233 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2234 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2236 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2237 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2238 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2240 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2243 * Send a human-readable error message.
2246 char message
[4096], /* Message for user */
2247 urltext
[1024], /* URL redirection text */
2248 redirect
[1024]; /* Redirection link */
2249 const char *text
; /* Status-specific text */
2254 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2255 text
= _cupsLangString(con
->language
,
2256 _("Enter your username and password or the "
2257 "root username and password to access this "
2258 "page. If you are using Kerberos authentication, "
2259 "make sure you have a valid Kerberos ticket."));
2260 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2264 snprintf(urltext
, sizeof(urltext
),
2265 _cupsLangString(con
->language
,
2266 _("You must access this page using the URL "
2267 "<A HREF=\"https://%s:%d%s\">"
2268 "https://%s:%d%s</A>.")),
2269 con
->servername
, con
->serverport
, con
->uri
,
2270 con
->servername
, con
->serverport
, con
->uri
);
2272 snprintf(redirect
, sizeof(redirect
),
2273 "<META HTTP-EQUIV=\"Refresh\" "
2274 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2275 con
->servername
, con
->serverport
, con
->uri
);
2277 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2278 text
= _cupsLangString(con
->language
,
2279 _("The web interface is currently disabled. Run "
2280 "\"cupsctl WebInterface=yes\" to enable it."));
2284 snprintf(message
, sizeof(message
),
2285 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2286 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2289 "\t<META HTTP-EQUIV=\"Content-Type\" "
2290 "CONTENT=\"text/html; charset=utf-8\">\n"
2291 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2292 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2293 "HREF=\"/cups.css\">\n"
2301 _httpStatus(con
->language
, code
), redirect
,
2302 _httpStatus(con
->language
, code
), text
);
2305 * Send an error message back to the client. If the error code is a
2306 * 400 or 500 series, make sure the message contains some text, too!
2309 size_t length
= strlen(message
); /* Length of message */
2311 httpSetLength(con
->http
, length
);
2313 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2316 if (httpWrite2(con
->http
, message
, length
) < 0)
2319 if (httpFlushWrite(con
->http
) < 0)
2324 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2326 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2335 * 'cupsdSendHeader()' - Send an HTTP request.
2338 int /* O - 1 on success, 0 on failure */
2340 cupsd_client_t
*con
, /* I - Client to send to */
2341 http_status_t code
, /* I - HTTP status code */
2342 char *type
, /* I - MIME type of document */
2343 int auth_type
) /* I - Type of authentication */
2345 char auth_str
[1024]; /* Authorization string */
2348 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2351 * Send the HTTP status header...
2354 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2357 * Treat our special "web interface is disabled" status as "200 OK" for web
2361 code
= HTTP_STATUS_OK
;
2365 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2367 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2368 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2370 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2372 if (auth_type
== CUPSD_AUTH_NONE
)
2374 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2375 auth_type
= cupsdDefaultAuthType();
2377 auth_type
= con
->best
->type
;
2382 if (auth_type
== CUPSD_AUTH_BASIC
)
2383 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2385 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2388 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2389 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2391 # endif /* AF_LOCAL */
2392 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2394 #endif /* HAVE_GSSAPI */
2396 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2397 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2400 * Add a "trc" (try root certification) parameter for local non-Kerberos
2401 * requests when the request requires system group membership - then the
2402 * client knows the root certificate can/should be used.
2404 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2405 * parameter as needed...
2408 char *name
, /* Current user name */
2409 *auth_key
; /* Auth key buffer */
2410 size_t auth_size
; /* Size of remaining buffer */
2412 auth_key
= auth_str
+ strlen(auth_str
);
2413 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2415 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2417 name
= (char *)cupsArrayNext(con
->best
->names
))
2419 #ifdef HAVE_AUTHORIZATION_H
2420 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2422 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2423 /* end parenthesis is stripped in conf.c */
2427 #endif /* HAVE_AUTHORIZATION_H */
2428 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2430 #ifdef HAVE_AUTHORIZATION_H
2431 if (SystemGroupAuthKey
)
2432 snprintf(auth_key
, auth_size
,
2434 SystemGroupAuthKey
);
2437 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2438 #endif /* HAVE_AUTHORIZATION_H */
2446 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2448 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2452 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2453 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2457 if (!strcmp(type
, "text/html"))
2458 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2460 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2463 return (!httpWriteResponse(con
->http
, code
));
2468 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2472 cupsdUpdateCGI(void)
2474 char *ptr
, /* Pointer to end of line in buffer */
2475 message
[1024]; /* Pointer to message text */
2476 int loglevel
; /* Log level for message */
2479 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2480 message
, sizeof(message
))) != NULL
)
2482 if (loglevel
== CUPSD_LOG_INFO
)
2483 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2485 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2489 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2492 * Fatal error on pipe - should never happen!
2495 cupsdLogMessage(CUPSD_LOG_CRIT
,
2496 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2503 * 'cupsdWriteClient()' - Write data to a client as needed.
2507 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2509 int bytes
, /* Number of bytes written */
2510 field_col
; /* Current column */
2511 char *bufptr
, /* Pointer into buffer */
2512 *bufend
; /* Pointer to end of buffer */
2513 ipp_state_t ipp_state
; /* IPP state value */
2516 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2517 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2522 "data_encoding=HTTP_ENCODING_%s, "
2523 "data_remaining=" CUPS_LLFMT
", "
2527 httpError(con
->http
), (int)httpGetReady(con
->http
),
2528 httpStateString(httpGetState(con
->http
)),
2529 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2530 CUPS_LLCAST
httpGetLength2(con
->http
),
2532 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2533 con
->pipe_pid
, con
->file
);
2535 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2536 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2539 * If we get called in the wrong state, then something went wrong with the
2540 * connection and we need to shut it down...
2543 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2544 httpStateString(httpGetState(con
->http
)));
2545 cupsdCloseClient(con
);
2552 * Make sure we select on the CGI output...
2555 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2557 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2559 if (!con
->file_ready
)
2562 * Try again later when there is CGI output available...
2565 cupsdRemoveSelect(httpGetFd(con
->http
));
2569 con
->file_ready
= 0;
2572 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2574 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2577 * Limit GET bytes to original size of file (STR #3265)...
2580 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2583 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2585 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2590 * Write a single attribute or the IPP message header...
2593 ipp_state
= ippWrite(con
->http
, con
->response
);
2596 * If the write buffer has been flushed, stop buffering up attributes...
2599 if (httpGetPending(con
->http
) <= wused
)
2602 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2604 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2605 "Writing IPP response, ipp_state=%s, old "
2606 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2607 ippStateString(ipp_state
),
2608 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2610 if (httpGetPending(con
->http
) > 0)
2611 httpFlushWrite(con
->http
);
2613 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2614 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2616 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2617 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2618 (int)bytes
, httpGetState(con
->http
),
2619 CUPS_LLCAST
httpGetLength2(con
->http
));
2621 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2623 con
->header_used
+= bytes
;
2625 if (con
->pipe_pid
&& !con
->got_fields
)
2628 * Inspect the data for Content-Type and other fields.
2631 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2633 !con
->got_fields
&& bufptr
< bufend
;
2636 if (*bufptr
== '\n')
2639 * Send line to client...
2642 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2646 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2648 if (!con
->sent_header
)
2651 * Handle redirection and CGI status codes...
2654 http_field_t field
; /* HTTP field */
2655 char *value
= strchr(con
->header
, ':');
2656 /* Value of field */
2661 while (isspace(*value
& 255))
2665 field
= httpFieldValue(con
->header
);
2667 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2669 httpSetField(con
->http
, field
, value
);
2671 if (field
== HTTP_FIELD_LOCATION
)
2673 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2674 con
->sent_header
= 2;
2677 con
->sent_header
= 1;
2679 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2681 con
->pipe_status
= (http_status_t
)atoi(value
);
2682 con
->sent_header
= 2;
2684 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2686 httpSetCookie(con
->http
, value
);
2687 con
->sent_header
= 1;
2695 con
->header_used
-= bufptr
- con
->header
;
2697 if (con
->header_used
> 0)
2698 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2700 bufptr
= con
->header
- 1;
2703 * See if the line was empty...
2708 con
->got_fields
= 1;
2710 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2711 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2712 httpSetLength(con
->http
, 0);
2714 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2716 if (con
->pipe_status
== HTTP_STATUS_OK
)
2718 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2720 cupsdCloseClient(con
);
2726 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2728 cupsdCloseClient(con
);
2736 else if (*bufptr
!= '\r')
2740 if (!con
->got_fields
)
2744 if (con
->header_used
> 0)
2746 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2748 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2749 httpError(con
->http
), strerror(httpError(con
->http
)));
2750 cupsdCloseClient(con
);
2754 if (httpIsChunked(con
->http
))
2755 httpFlushWrite(con
->http
);
2757 con
->bytes
+= con
->header_used
;
2759 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2762 bytes
= con
->header_used
;
2764 con
->header_used
= 0;
2769 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2770 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2772 if (!con
->sent_header
&& con
->pipe_pid
)
2773 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2776 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2778 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2780 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2782 if (httpWrite2(con
->http
, "", 0) < 0)
2784 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2785 httpError(con
->http
), strerror(httpError(con
->http
)));
2786 cupsdCloseClient(con
);
2791 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2792 httpFlushWrite(con
->http
);
2793 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2796 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2798 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2802 cupsdRemoveSelect(con
->file
);
2805 cupsdEndProcess(con
->pipe_pid
, 0);
2814 unlink(con
->filename
);
2815 cupsdClearString(&con
->filename
);
2820 ippDelete(con
->request
);
2821 con
->request
= NULL
;
2826 ippDelete(con
->response
);
2827 con
->response
= NULL
;
2830 cupsdClearString(&con
->command
);
2831 cupsdClearString(&con
->options
);
2832 cupsdClearString(&con
->query_string
);
2834 if (!httpGetKeepAlive(con
->http
))
2836 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2837 "Closing because Keep-Alive is disabled.");
2838 cupsdCloseClient(con
);
2843 cupsArrayRemove(ActiveClients
, con
);
2844 cupsdSetBusyState();
2851 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2854 static int /* O - 1 if modified since */
2856 cupsd_client_t
*con
, /* I - Client connection */
2857 struct stat
*filestats
) /* I - File information */
2859 const char *ptr
; /* Pointer into field */
2860 time_t date
; /* Time/date value */
2861 off_t size
; /* Size/length value */
2866 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2871 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2872 "check_if_modified "
2873 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2874 filestats
, CUPS_LLCAST filestats
->st_size
,
2875 (int)filestats
->st_mtime
, ptr
);
2877 while (*ptr
!= '\0')
2879 while (isspace(*ptr
) || *ptr
== ';')
2882 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2885 size
= strtoll(ptr
, NULL
, 10);
2887 while (isdigit(*ptr
))
2890 else if (isalpha(*ptr
))
2892 date
= httpGetDateTime(ptr
);
2893 while (*ptr
!= '\0' && *ptr
!= ';')
2900 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2901 (date
< filestats
->st_mtime
&& date
!= 0) ||
2902 (size
== 0 && date
== 0));
2907 * 'compare_clients()' - Compare two client connections.
2910 static int /* O - Result of comparison */
2911 compare_clients(cupsd_client_t
*a
, /* I - First client */
2912 cupsd_client_t
*b
, /* I - Second client */
2913 void *data
) /* I - User data (not used) */
2928 * 'cupsd_start_tls()' - Start encryption on a connection.
2931 static int /* O - 0 on success, -1 on error */
2932 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2933 http_encryption_t e
) /* I - Encryption mode */
2935 if (httpEncryption(con
->http
, e
))
2937 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2938 cupsLastErrorString());
2942 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Connection now encrypted.");
2945 #endif /* HAVE_SSL */
2949 * 'get_file()' - Get a filename and state info.
2952 static char * /* O - Real filename */
2953 get_file(cupsd_client_t
*con
, /* I - Client connection */
2954 struct stat
*filestats
, /* O - File information */
2955 char *filename
, /* IO - Filename buffer */
2956 size_t len
) /* I - Buffer length */
2958 int status
; /* Status of filesystem calls */
2959 char *ptr
; /* Pointer info filename */
2960 size_t plen
; /* Remaining length after pointer */
2961 char language
[7]; /* Language subdirectory, if any */
2962 int perm_check
= 1; /* Do permissions check? */
2966 * Figure out the real filename...
2971 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2973 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2977 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2979 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
2980 if (access(filename
, F_OK
) < 0)
2981 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2985 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2986 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2987 else if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2989 strlcpy(filename
, ConfigurationFile
, len
);
2993 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2995 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2996 strlcpy(filename
, AccessLog
, len
);
2997 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2998 strlcpy(filename
, ErrorLog
, len
);
2999 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3000 strlcpy(filename
, PageLog
, len
);
3006 else if (con
->language
)
3008 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3009 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3012 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3014 if ((ptr
= strchr(filename
, '?')) != NULL
)
3018 * Grab the status for this language; if there isn't a language-specific file
3019 * then fallback to the default one...
3022 if ((status
= lstat(filename
, filestats
)) != 0 && language
[0] &&
3023 strncmp(con
->uri
, "/icons/", 7) &&
3024 strncmp(con
->uri
, "/ppd/", 5) &&
3025 strncmp(con
->uri
, "/rss/", 5) &&
3026 strncmp(con
->uri
, "/admin/conf/", 12) &&
3027 strncmp(con
->uri
, "/admin/log/", 11))
3030 * Drop the country code...
3034 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3036 if ((ptr
= strchr(filename
, '?')) != NULL
)
3039 if ((status
= lstat(filename
, filestats
)) != 0)
3042 * Drop the language prefix and try the root directory...
3046 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3048 if ((ptr
= strchr(filename
, '?')) != NULL
)
3051 status
= lstat(filename
, filestats
);
3056 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3059 if (!status
&& S_ISLNK(filestats
->st_mode
))
3061 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3066 * Similarly, if the file/directory does not have world read permissions, do
3067 * not allow access...
3070 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3072 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3077 * If we've found a directory, get the index.html file instead...
3080 if (!status
&& S_ISDIR(filestats
->st_mode
))
3083 * Make sure the URI ends with a slash...
3086 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3087 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3090 * Find the directory index file, trying every language...
3095 if (status
&& language
[0])
3098 * Try a different language subset...
3102 language
[0] = '\0'; /* Strip country code */
3104 language
[0] = '\0'; /* Strip language */
3108 * Look for the index file...
3111 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3113 if ((ptr
= strchr(filename
, '?')) != NULL
)
3116 ptr
= filename
+ strlen(filename
);
3117 plen
= len
- (size_t)(ptr
- filename
);
3119 strlcpy(ptr
, "index.html", plen
);
3120 status
= lstat(filename
, filestats
);
3125 strlcpy(ptr
, "index.class", plen
);
3126 status
= lstat(filename
, filestats
);
3128 #endif /* HAVE_JAVA */
3133 strlcpy(ptr
, "index.pl", plen
);
3134 status
= lstat(filename
, filestats
);
3136 #endif /* HAVE_PERL */
3141 strlcpy(ptr
, "index.php", plen
);
3142 status
= lstat(filename
, filestats
);
3144 #endif /* HAVE_PHP */
3149 strlcpy(ptr
, "index.pyc", plen
);
3150 status
= lstat(filename
, filestats
);
3155 strlcpy(ptr
, "index.py", plen
);
3156 status
= lstat(filename
, filestats
);
3158 #endif /* HAVE_PYTHON */
3161 while (status
&& language
[0]);
3164 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3167 if (!status
&& S_ISLNK(filestats
->st_mode
))
3169 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3174 * Similarly, if the file/directory does not have world read permissions, do
3175 * not allow access...
3178 if (!status
&& perm_check
&& !(filestats
->st_mode
& S_IROTH
))
3180 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3185 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3195 * 'install_cupsd_conf()' - Install a configuration file.
3198 static http_status_t
/* O - Status */
3199 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3201 char filename
[1024]; /* Configuration filename */
3202 cups_file_t
*in
, /* Input file */
3203 *out
; /* Output file */
3204 char buffer
[16384]; /* Copy buffer */
3205 ssize_t bytes
; /* Number of bytes */
3209 * Open the request file...
3212 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3214 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3215 con
->filename
, strerror(errno
));
3216 return (HTTP_STATUS_SERVER_ERROR
);
3220 * Open the new config file...
3223 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3226 return (HTTP_STATUS_SERVER_ERROR
);
3229 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3233 * Copy from the request to the new config file...
3236 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3237 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3239 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3240 "Unable to copy to config file \"%s\": %s",
3241 ConfigurationFile
, strerror(errno
));
3246 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3247 cupsdUnlinkOrRemoveFile(filename
);
3249 return (HTTP_STATUS_SERVER_ERROR
);
3253 * Close the files...
3258 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3259 return (HTTP_STATUS_SERVER_ERROR
);
3262 * Remove the request file...
3265 cupsdUnlinkOrRemoveFile(con
->filename
);
3266 cupsdClearString(&con
->filename
);
3269 * Set the NeedReload flag...
3272 NeedReload
= RELOAD_CUPSD
;
3273 ReloadTime
= time(NULL
);
3276 * Return that the file was created successfully...
3279 return (HTTP_STATUS_CREATED
);
3284 * 'is_cgi()' - Is the resource a CGI script/program?
3287 static int /* O - 1 = CGI, 0 = file */
3288 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3289 const char *filename
, /* I - Real filename */
3290 struct stat
*filestats
, /* I - File information */
3291 mime_type_t
*type
) /* I - MIME type */
3293 const char *options
; /* Options on URL */
3297 * Get the options, if any...
3300 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3303 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3307 * Check for known types...
3310 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3312 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3313 "is_cgi filename=\"%s\", filestats=%p, "
3314 "type=%s/%s, returning 0", filename
,
3315 filestats
, type
? type
->super
: "unknown",
3316 type
? type
->type
: "unknown");
3320 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3321 (filestats
->st_mode
& 0111))
3324 * "application/x-httpd-cgi" is a CGI script.
3327 cupsdSetString(&con
->command
, filename
);
3330 cupsdSetStringf(&con
->options
, " %s", options
);
3332 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3333 "is_cgi filename=\"%s\", filestats=%p, "
3334 "type=%s/%s, returning 1", filename
,
3335 filestats
, type
->super
, type
->type
);
3339 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3342 * "application/x-httpd-java" is a Java servlet.
3345 cupsdSetString(&con
->command
, CUPS_JAVA
);
3348 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3350 cupsdSetStringf(&con
->options
, " %s", filename
);
3352 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3353 "is_cgi filename=\"%s\", filestats=%p, "
3354 "type=%s/%s, returning 1", filename
,
3355 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
,
3374 "is_cgi filename=\"%s\", filestats=%p, "
3375 "type=%s/%s, returning 1", filename
,
3376 filestats
, type
->super
, type
->type
);
3379 #endif /* HAVE_PERL */
3381 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3384 * "application/x-httpd-php" is a PHP page.
3387 cupsdSetString(&con
->command
, CUPS_PHP
);
3390 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3392 cupsdSetStringf(&con
->options
, " %s", filename
);
3394 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3395 "is_cgi filename=\"%s\", filestats=%p, "
3396 "type=%s/%s, returning 1", filename
,
3397 filestats
, type
->super
, type
->type
);
3400 #endif /* HAVE_PHP */
3402 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3405 * "application/x-httpd-python" is a Python page.
3408 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3411 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3413 cupsdSetStringf(&con
->options
, " %s", filename
);
3415 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3416 "is_cgi filename=\"%s\", filestats=%p, "
3417 "type=%s/%s, returning 1", filename
,
3418 filestats
, type
->super
, type
->type
);
3421 #endif /* HAVE_PYTHON */
3423 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3424 "is_cgi filename=\"%s\", filestats=%p, "
3425 "type=%s/%s, returning 0", filename
,
3426 filestats
, type
->super
, type
->type
);
3432 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3435 static int /* O - 0 if relative, 1 if absolute */
3436 is_path_absolute(const char *path
) /* I - Input path */
3439 * Check for a leading slash...
3446 * Check for "<" or quotes in the path and reject since this is probably
3447 * someone trying to inject HTML...
3450 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3454 * Check for "/.." in the path...
3457 while ((path
= strstr(path
, "/..")) != NULL
)
3459 if (!path
[3] || path
[3] == '/')
3466 * If we haven't found any relative paths, return 1 indicating an
3475 * 'pipe_command()' - Pipe the output of a command to the remote client.
3478 static int /* O - Process ID */
3479 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3480 int infile
, /* I - Standard input for command */
3481 int *outfile
, /* O - Standard output for command */
3482 char *command
, /* I - Command to run */
3483 char *options
, /* I - Options for command */
3484 int root
) /* I - Run as root? */
3486 int i
; /* Looping var */
3487 int pid
; /* Process ID */
3488 char *commptr
, /* Command string pointer */
3489 commch
; /* Command string character */
3490 char *uriptr
; /* URI string pointer */
3491 int fds
[2]; /* Pipe FDs */
3492 int argc
; /* Number of arguments */
3493 int envc
; /* Number of environment variables */
3494 char argbuf
[10240], /* Argument buffer */
3495 *argv
[100], /* Argument strings */
3496 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3497 char auth_type
[256], /* AUTH_TYPE environment variable */
3498 content_length
[1024], /* CONTENT_LENGTH environment variable */
3499 content_type
[1024], /* CONTENT_TYPE environment variable */
3500 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3501 http_referer
[1024], /* HTTP_REFERER environment variable */
3502 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3503 lang
[1024], /* LANG environment variable */
3504 path_info
[1024], /* PATH_INFO environment variable */
3505 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3506 remote_host
[1024], /* REMOTE_HOST environment variable */
3507 remote_user
[1024], /* REMOTE_USER environment variable */
3508 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3509 script_name
[1024], /* SCRIPT_NAME environment variable */
3510 server_name
[1024], /* SERVER_NAME environment variable */
3511 server_port
[1024]; /* SERVER_PORT environment variable */
3512 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3516 * Parse a copy of the options string, which is of the form:
3518 * argument+argument+argument
3519 * ?argument+argument+argument
3520 * param=value¶m=value
3521 * ?param=value¶m=value
3522 * /name?argument+argument+argument
3523 * /name?param=value¶m=value
3525 * If the string contains an "=" character after the initial name,
3526 * then we treat it as a HTTP GET form request and make a copy of
3527 * the remaining string for the environment variable.
3529 * The string is always parsed out as command-line arguments, to
3530 * be consistent with Apache...
3533 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3534 "pipe_command infile=%d, outfile=%p, "
3535 "command=\"%s\", options=\"%s\", root=%d",
3536 infile
, outfile
, command
,
3537 options
? options
: "(null)", root
);
3542 strlcpy(argbuf
, options
, sizeof(argbuf
));
3546 if (argbuf
[0] == '/')
3549 * Found some trailing path information, set PATH_INFO...
3552 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3553 commptr
= argbuf
+ strlen(argbuf
);
3557 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3563 path_info
[0] = '\0';
3565 if (*commptr
== ' ')
3569 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3572 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3579 argv
[argc
++] = commptr
;
3581 for (; *commptr
&& argc
< 99; commptr
++)
3584 * Break arguments whenever we see a + or space...
3587 if (*commptr
== ' ' || *commptr
== '+')
3589 while (*commptr
== ' ' || *commptr
== '+')
3593 * If we don't have a blank string, save it as another argument...
3598 argv
[argc
] = commptr
;
3604 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3605 isxdigit(commptr
[2] & 255))
3608 * Convert the %xx notation to the individual character.
3611 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3612 *commptr
= (char)((commptr
[1] - '0') << 4);
3614 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3616 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3617 *commptr
|= commptr
[2] - '0';
3619 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3621 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3624 * Check for a %00 and break if that is the case...
3636 * Setup the environment variables as needed...
3639 if (con
->username
[0])
3641 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3642 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3644 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3648 auth_type
[0] = '\0';
3651 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3652 IPP_TAG_LANGUAGE
)) != NULL
)
3654 switch (strlen(attr
->values
[0].string
.text
))
3658 * This is an unknown or badly formatted language code; use
3659 * the POSIX locale...
3662 strlcpy(lang
, "LANG=C", sizeof(lang
));
3667 * Just the language code (ll)...
3670 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3671 attr
->values
[0].string
.text
);
3676 * Language and country code (ll-cc)...
3679 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3680 attr
->values
[0].string
.text
[0],
3681 attr
->values
[0].string
.text
[1],
3682 toupper(attr
->values
[0].string
.text
[3] & 255),
3683 toupper(attr
->values
[0].string
.text
[4] & 255));
3687 else if (con
->language
)
3688 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3690 strlcpy(lang
, "LANG=C", sizeof(lang
));
3692 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3693 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3694 sizeof(remote_addr
) - 12);
3696 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3697 httpGetHostname(con
->http
, NULL
, 0));
3699 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3700 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3703 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3704 DocumentRoot
, script_name
+ 12);
3706 snprintf(server_port
, sizeof(server_port
), "SERVER_PORT=%d", con
->serverport
);
3708 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3710 char *nameptr
; /* Pointer to ":port" */
3712 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3713 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3714 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3715 *nameptr
= '\0'; /* Strip trailing ":port" */
3718 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3721 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3724 envp
[envc
++] = auth_type
;
3726 envp
[envc
++] = lang
;
3727 envp
[envc
++] = "REDIRECT_STATUS=1";
3728 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3729 envp
[envc
++] = server_name
;
3730 envp
[envc
++] = server_port
;
3731 envp
[envc
++] = remote_addr
;
3732 envp
[envc
++] = remote_host
;
3733 envp
[envc
++] = script_name
;
3734 envp
[envc
++] = script_filename
;
3737 envp
[envc
++] = path_info
;
3739 if (con
->username
[0])
3741 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3743 envp
[envc
++] = remote_user
;
3746 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3747 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3748 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3749 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3751 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3753 if (httpGetCookie(con
->http
))
3755 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3756 httpGetCookie(con
->http
));
3757 envp
[envc
++] = http_cookie
;
3760 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3762 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3763 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3764 envp
[envc
++] = http_user_agent
;
3767 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3769 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3770 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3771 envp
[envc
++] = http_referer
;
3774 if (con
->operation
== HTTP_STATE_GET
)
3776 envp
[envc
++] = "REQUEST_METHOD=GET";
3778 if (con
->query_string
)
3781 * Add GET form variables after ?...
3784 envp
[envc
++] = con
->query_string
;
3787 envp
[envc
++] = "QUERY_STRING=";
3791 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3792 CUPS_LLCAST con
->bytes
);
3793 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3794 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3796 envp
[envc
++] = "REQUEST_METHOD=POST";
3797 envp
[envc
++] = content_length
;
3798 envp
[envc
++] = content_type
;
3802 * Tell the CGI if we are using encryption...
3805 if (httpIsEncrypted(con
->http
))
3806 envp
[envc
++] = "HTTPS=ON";
3809 * Terminate the environment array...
3814 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3816 for (i
= 0; i
< argc
; i
++)
3817 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3818 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3819 for (i
= 0; i
< envc
; i
++)
3820 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3821 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3825 * Create a pipe for the output...
3828 if (cupsdOpenPipe(fds
))
3830 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3831 argv
[0], strerror(errno
));
3836 * Then execute the command...
3839 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3840 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3843 * Error - can't fork!
3846 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3849 cupsdClosePipe(fds
);
3855 * Fork successful - return the PID...
3858 if (con
->username
[0])
3859 cupsdAddCert(pid
, con
->username
, con
->type
);
3861 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3872 * 'valid_host()' - Is the Host: field valid?
3875 static int /* O - 1 if valid, 0 if not */
3876 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3878 cupsd_alias_t
*a
; /* Current alias */
3879 cupsd_netif_t
*netif
; /* Current network interface */
3880 const char *end
; /* End character */
3881 char *ptr
; /* Pointer into host value */
3885 * Copy the Host: header for later use...
3888 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3889 sizeof(con
->clientname
));
3890 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3893 con
->clientport
= atoi(ptr
);
3896 con
->clientport
= con
->serverport
;
3902 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3905 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3906 * addresses when accessing CUPS via the loopback interface...
3909 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3910 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3912 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3913 #endif /* __linux */
3914 !strcmp(con
->clientname
, "127.0.0.1") ||
3915 !strcmp(con
->clientname
, "[::1]"));
3918 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3920 * Check if the hostname is something.local (Bonjour); if so, allow it.
3923 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3927 * "." on end, work back to second-to-last "."...
3930 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3933 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3934 !_cups_strcasecmp(end
, ".local.")))
3936 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3939 * Check if the hostname is an IP address...
3942 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3945 * Possible IPv4/IPv6 address...
3948 http_addrlist_t
*addrlist
; /* List of addresses */
3951 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3954 * Good IPv4/IPv6 address...
3957 httpAddrFreeList(addrlist
);
3963 * Check for (alias) name matches...
3966 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3968 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3971 * "ServerAlias *" allows all host values through...
3974 if (!strcmp(a
->name
, "*"))
3977 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3980 * Prefix matches; check the character at the end - it must be "." or nul.
3983 end
= con
->clientname
+ a
->namelen
;
3985 if (!*end
|| (*end
== '.' && !end
[1]))
3990 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3991 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3993 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3996 * "ServerAlias *" allows all host values through...
3999 if (!strcmp(a
->name
, "*"))
4002 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4005 * Prefix matches; check the character at the end - it must be "." or nul.
4008 end
= con
->clientname
+ a
->namelen
;
4010 if (!*end
|| (*end
== '.' && !end
[1]))
4014 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4017 * Check for interface hostname matches...
4020 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4022 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4024 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4027 * Prefix matches; check the character at the end - it must be "." or nul.
4030 end
= con
->clientname
+ netif
->hostlen
;
4032 if (!*end
|| (*end
== '.' && !end
[1]))
4042 * 'write_file()' - Send a file via HTTP.
4045 static int /* O - 0 on failure, 1 on success */
4046 write_file(cupsd_client_t
*con
, /* I - Client connection */
4047 http_status_t code
, /* I - HTTP status */
4048 char *filename
, /* I - Filename */
4049 char *type
, /* I - File type */
4050 struct stat
*filestats
) /* O - File information */
4052 con
->file
= open(filename
, O_RDONLY
);
4054 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
4055 "write_file code=%d, filename=\"%s\" (%d), "
4056 "type=\"%s\", filestats=%p",
4057 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4062 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4065 con
->sent_header
= 1;
4067 httpClearFields(con
->http
);
4069 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
4071 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
4072 httpGetDateString(filestats
->st_mtime
));
4074 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4077 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4079 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4086 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4090 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4092 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4095 con
->file_ready
= 1;
4097 cupsdRemoveSelect(con
->file
);
4098 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4100 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");