4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2014 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
);
487 cupsdClearString(&con
->filename
);
488 cupsdClearString(&con
->command
);
489 cupsdClearString(&con
->options
);
490 cupsdClearString(&con
->query_string
);
494 ippDelete(con
->request
);
500 ippDelete(con
->response
);
501 con
->response
= NULL
;
506 cupsLangFree(con
->language
);
507 con
->language
= NULL
;
510 #ifdef HAVE_AUTHORIZATION_H
513 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
516 #endif /* HAVE_AUTHORIZATION_H */
519 * Re-enable new client connections if we are going back under the
523 if (cupsArrayCount(Clients
) == MaxClients
)
524 cupsdResumeListening();
527 * Compact the list of clients as necessary...
530 cupsArrayRemove(Clients
, con
);
540 * 'cupsdReadClient()' - Read data from a client.
544 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
546 char line
[32768], /* Line from client... */
547 locale
[64], /* Locale */
548 *ptr
; /* Pointer into strings */
549 http_status_t status
; /* Transfer status */
550 ipp_state_t ipp_state
; /* State of IPP transfer */
551 int bytes
; /* Number of bytes to POST */
552 char *filename
; /* Name of file for GET/HEAD */
553 char buf
[1024]; /* Buffer for real filename */
554 struct stat filestats
; /* File information */
555 mime_type_t
*type
; /* MIME type of file */
556 cupsd_printer_t
*p
; /* Printer */
557 static unsigned request_id
= 0; /* Request ID for temp files */
560 status
= HTTP_STATUS_CONTINUE
;
562 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
567 "data_encoding=HTTP_ENCODING_%s, "
568 "data_remaining=" CUPS_LLFMT
", "
571 httpError(con
->http
), (int)httpGetReady(con
->http
),
572 httpStateString(httpGetState(con
->http
)),
573 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
574 CUPS_LLCAST
httpGetRemaining(con
->http
),
576 con
->request
? ippStateString(ippGetState(con
->request
)) : "",
579 if (httpGetState(con
->http
) == HTTP_STATE_GET_SEND
||
580 httpGetState(con
->http
) == HTTP_STATE_POST_SEND
||
581 httpGetState(con
->http
) == HTTP_STATE_STATUS
)
584 * If we get called in the wrong state, then something went wrong with the
585 * connection and we need to shut it down...
588 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP read state %s.",
589 httpStateString(httpGetState(con
->http
)));
590 cupsdCloseClient(con
);
598 * Automatically check for a SSL/TLS handshake...
603 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
604 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
607 * Encrypt this connection...
610 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
611 "Saw first byte %02X, auto-negotiating "
612 "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_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_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
);
1164 else if (!WebInterface
)
1167 * Web interface is disabled. Show an appropriate message...
1170 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1172 cupsdCloseClient(con
);
1179 if ((!strncmp(con
->uri
, "/admin", 6) &&
1180 strncmp(con
->uri
, "/admin/conf/", 12) &&
1181 strncmp(con
->uri
, "/admin/log/", 11)) ||
1182 !strncmp(con
->uri
, "/printers", 9) ||
1183 !strncmp(con
->uri
, "/classes", 8) ||
1184 !strncmp(con
->uri
, "/help", 5) ||
1185 !strncmp(con
->uri
, "/jobs", 5))
1188 * Send CGI output...
1191 if (!strncmp(con
->uri
, "/admin", 6))
1193 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1196 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1198 else if (!strncmp(con
->uri
, "/printers", 9))
1200 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1203 if (con
->uri
[9] && con
->uri
[10])
1204 cupsdSetString(&con
->options
, con
->uri
+ 9);
1206 cupsdSetString(&con
->options
, NULL
);
1208 else if (!strncmp(con
->uri
, "/classes", 8))
1210 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1213 if (con
->uri
[8] && con
->uri
[9])
1214 cupsdSetString(&con
->options
, con
->uri
+ 8);
1216 cupsdSetString(&con
->options
, NULL
);
1218 else if (!strncmp(con
->uri
, "/jobs", 5))
1220 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1223 if (con
->uri
[5] && con
->uri
[6])
1224 cupsdSetString(&con
->options
, con
->uri
+ 5);
1226 cupsdSetString(&con
->options
, NULL
);
1230 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1233 if (con
->uri
[5] && con
->uri
[6])
1234 cupsdSetString(&con
->options
, con
->uri
+ 5);
1236 cupsdSetString(&con
->options
, NULL
);
1239 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1241 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1243 cupsdCloseClient(con
);
1248 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1250 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1251 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1253 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1254 (strchr(con
->uri
+ 12, '/') ||
1255 strlen(con
->uri
) == 12)) ||
1256 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1257 (strchr(con
->uri
+ 11, '/') ||
1258 strlen(con
->uri
) == 11)))
1261 * GET can only be done to configuration files directly under
1265 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1266 "Request for subdirectory \"%s\"!", con
->uri
);
1268 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1270 cupsdCloseClient(con
);
1282 if ((filename
= get_file(con
, &filestats
, buf
,
1283 sizeof(buf
))) == NULL
)
1285 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1287 cupsdCloseClient(con
);
1294 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1296 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1298 if (is_cgi(con
, filename
, &filestats
, type
))
1301 * Note: con->command and con->options were set by
1305 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1307 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1309 cupsdCloseClient(con
);
1314 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1316 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1317 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1321 if (!check_if_modified(con
, &filestats
))
1323 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1325 cupsdCloseClient(con
);
1332 strlcpy(line
, "text/plain", sizeof(line
));
1334 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1336 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1338 cupsdCloseClient(con
);
1345 case HTTP_STATE_POST_RECV
:
1347 * See if the POST request includes a Content-Length field, and if
1348 * so check the length against any limits that are set...
1351 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1352 MaxRequestSize
> 0 &&
1353 httpGetLength2(con
->http
) > MaxRequestSize
)
1356 * Request too large...
1359 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1361 cupsdCloseClient(con
);
1367 else if (httpGetLength2(con
->http
) < 0)
1370 * Negative content lengths are invalid!
1373 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1375 cupsdCloseClient(con
);
1383 * See what kind of POST request this is; for IPP requests the
1384 * content-type field will be "application/ipp"...
1387 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1389 con
->request
= ippNew();
1390 else if (!WebInterface
)
1393 * Web interface is disabled. Show an appropriate message...
1396 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1398 cupsdCloseClient(con
);
1404 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1405 strncmp(con
->uri
, "/admin/conf/", 12) &&
1406 strncmp(con
->uri
, "/admin/log/", 11)) ||
1407 !strncmp(con
->uri
, "/printers", 9) ||
1408 !strncmp(con
->uri
, "/classes", 8) ||
1409 !strncmp(con
->uri
, "/help", 5) ||
1410 !strncmp(con
->uri
, "/jobs", 5))
1416 if (!strncmp(con
->uri
, "/admin", 6))
1418 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1421 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1423 else if (!strncmp(con
->uri
, "/printers", 9))
1425 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1428 if (con
->uri
[9] && con
->uri
[10])
1429 cupsdSetString(&con
->options
, con
->uri
+ 9);
1431 cupsdSetString(&con
->options
, NULL
);
1433 else if (!strncmp(con
->uri
, "/classes", 8))
1435 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1438 if (con
->uri
[8] && con
->uri
[9])
1439 cupsdSetString(&con
->options
, con
->uri
+ 8);
1441 cupsdSetString(&con
->options
, NULL
);
1443 else if (!strncmp(con
->uri
, "/jobs", 5))
1445 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1448 if (con
->uri
[5] && con
->uri
[6])
1449 cupsdSetString(&con
->options
, con
->uri
+ 5);
1451 cupsdSetString(&con
->options
, NULL
);
1455 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1458 if (con
->uri
[5] && con
->uri
[6])
1459 cupsdSetString(&con
->options
, con
->uri
+ 5);
1461 cupsdSetString(&con
->options
, NULL
);
1464 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1465 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1473 if ((filename
= get_file(con
, &filestats
, buf
,
1474 sizeof(buf
))) == NULL
)
1476 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1478 cupsdCloseClient(con
);
1485 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1487 if (!is_cgi(con
, filename
, &filestats
, type
))
1490 * Only POST to CGI's...
1493 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1495 cupsdCloseClient(con
);
1502 case HTTP_STATE_PUT_RECV
:
1504 * Validate the resource name...
1507 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1510 * PUT can only be done to the cupsd.conf file...
1513 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1514 "Disallowed PUT request for \"%s\".", con
->uri
);
1516 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1518 cupsdCloseClient(con
);
1526 * See if the PUT request includes a Content-Length field, and if
1527 * so check the length against any limits that are set...
1530 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1531 MaxRequestSize
> 0 &&
1532 httpGetLength2(con
->http
) > MaxRequestSize
)
1535 * Request too large...
1538 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1540 cupsdCloseClient(con
);
1546 else if (httpGetLength2(con
->http
) < 0)
1549 * Negative content lengths are invalid!
1552 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1554 cupsdCloseClient(con
);
1562 * Open a temporary file to hold the request...
1565 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1567 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1571 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1572 "Unable to create request file \"%s\": %s",
1573 con
->filename
, strerror(errno
));
1575 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1577 cupsdCloseClient(con
);
1582 fchmod(con
->file
, 0640);
1583 fchown(con
->file
, RunUser
, Group
);
1584 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1587 case HTTP_STATE_DELETE
:
1588 case HTTP_STATE_TRACE
:
1589 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1590 cupsdCloseClient(con
);
1593 case HTTP_STATE_HEAD
:
1594 if (!strncmp(con
->uri
, "/printers/", 10) &&
1595 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1598 * Send PPD file - get the real printer name since printer
1599 * names are not case sensitive but filenames can be...
1602 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1604 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1605 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1608 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1610 cupsdCloseClient(con
);
1614 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1618 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1619 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1622 * Send PNG file - get the real printer name since printer
1623 * names are not case sensitive but filenames can be...
1626 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1628 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1629 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1632 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1634 cupsdCloseClient(con
);
1638 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1642 else if (!WebInterface
)
1644 httpClearFields(con
->http
);
1646 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1648 cupsdCloseClient(con
);
1652 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1656 if ((!strncmp(con
->uri
, "/admin", 6) &&
1657 strncmp(con
->uri
, "/admin/conf/", 12) &&
1658 strncmp(con
->uri
, "/admin/log/", 11)) ||
1659 !strncmp(con
->uri
, "/printers", 9) ||
1660 !strncmp(con
->uri
, "/classes", 8) ||
1661 !strncmp(con
->uri
, "/help", 5) ||
1662 !strncmp(con
->uri
, "/jobs", 5))
1668 httpClearFields(con
->http
);
1670 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1672 cupsdCloseClient(con
);
1676 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1678 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1679 (strchr(con
->uri
+ 12, '/') ||
1680 strlen(con
->uri
) == 12)) ||
1681 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1682 (strchr(con
->uri
+ 11, '/') ||
1683 strlen(con
->uri
) == 11)))
1686 * HEAD can only be done to configuration files under
1690 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1691 "Request for subdirectory \"%s\".", con
->uri
);
1693 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1695 cupsdCloseClient(con
);
1699 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1702 else if ((filename
= get_file(con
, &filestats
, buf
,
1703 sizeof(buf
))) == NULL
)
1705 httpClearFields(con
->http
);
1707 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1710 cupsdCloseClient(con
);
1714 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1716 else if (!check_if_modified(con
, &filestats
))
1718 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1720 cupsdCloseClient(con
);
1724 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1732 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1734 strlcpy(line
, "text/plain", sizeof(line
));
1736 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1738 httpClearFields(con
->http
);
1740 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1741 httpGetDateString(filestats
.st_mtime
));
1742 httpSetLength(con
->http
, (size_t)filestats
.st_size
);
1744 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1746 cupsdCloseClient(con
);
1750 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1755 break; /* Anti-compiler-warning-code */
1761 * Handle any incoming data...
1764 switch (httpGetState(con
->http
))
1766 case HTTP_STATE_PUT_RECV
:
1769 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1771 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1772 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1773 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1774 httpError(con
->http
), strerror(httpError(con
->http
)));
1776 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1777 "HTTP_STATE_PUT_RECV Closing on EOF.");
1779 cupsdCloseClient(con
);
1784 con
->bytes
+= bytes
;
1786 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1788 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1789 "Unable to write %d bytes to \"%s\": %s", bytes
,
1790 con
->filename
, strerror(errno
));
1794 unlink(con
->filename
);
1795 cupsdClearString(&con
->filename
);
1797 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1799 cupsdCloseClient(con
);
1805 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1807 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1810 * End of file, see how big it is...
1813 fstat(con
->file
, &filestats
);
1818 if (filestats
.st_size
> MaxRequestSize
&&
1822 * Request is too big; remove it and send an error...
1825 unlink(con
->filename
);
1826 cupsdClearString(&con
->filename
);
1828 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1830 cupsdCloseClient(con
);
1836 * Install the configuration file...
1839 status
= install_cupsd_conf(con
);
1842 * Return the status to the client...
1845 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1847 cupsdCloseClient(con
);
1853 case HTTP_STATE_POST_RECV
:
1856 if (con
->request
&& con
->file
< 0)
1859 * Grab any request data from the connection...
1862 if (!httpWait(con
->http
, 0))
1865 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1867 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1868 cupsLastErrorString());
1870 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1871 cupsdCloseClient(con
);
1874 else if (ipp_state
!= IPP_STATE_DATA
)
1876 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1878 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1879 cupsdCloseClient(con
);
1883 if (httpGetReady(con
->http
))
1889 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1890 con
->request
->request
.op
.version
[0],
1891 con
->request
->request
.op
.version
[1],
1892 ippOpString(con
->request
->request
.op
.operation_id
),
1893 con
->request
->request
.op
.request_id
);
1894 con
->bytes
+= ippLength(con
->request
);
1898 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1901 * Create a file as needed for the request data...
1904 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1906 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1910 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1911 "Unable to create request file \"%s\": %s",
1912 con
->filename
, strerror(errno
));
1914 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1916 cupsdCloseClient(con
);
1921 fchmod(con
->file
, 0640);
1922 fchown(con
->file
, RunUser
, Group
);
1923 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1926 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1928 if (!httpWait(con
->http
, 0))
1930 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1932 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1933 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1934 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1935 httpError(con
->http
), strerror(httpError(con
->http
)));
1937 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1938 "HTTP_STATE_POST_SEND Closing on EOF.");
1940 cupsdCloseClient(con
);
1945 con
->bytes
+= bytes
;
1947 if (write(con
->file
, line
, (size_t)bytes
) < bytes
)
1949 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1950 "Unable to write %d bytes to \"%s\": %s",
1951 bytes
, con
->filename
, strerror(errno
));
1955 unlink(con
->filename
);
1956 cupsdClearString(&con
->filename
);
1958 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1961 cupsdCloseClient(con
);
1966 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1968 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1970 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1971 "Closing on unexpected state %s.",
1972 httpStateString(httpGetState(con
->http
)));
1973 cupsdCloseClient(con
);
1978 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1980 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1983 * Don't listen for activity until we decide to do something with this...
1986 cupsdAddSelect(httpGetFd(con
->http
), NULL
, NULL
, con
);
1990 fstat(con
->file
, &filestats
);
1995 if (filestats
.st_size
> MaxRequestSize
&&
1999 * Request is too big; remove it and send an error...
2002 unlink(con
->filename
);
2003 cupsdClearString(&con
->filename
);
2008 * Delete any IPP request data...
2011 ippDelete(con
->request
);
2012 con
->request
= NULL
;
2015 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2017 cupsdCloseClient(con
);
2021 else if (filestats
.st_size
== 0)
2024 * Don't allow empty file...
2027 unlink(con
->filename
);
2028 cupsdClearString(&con
->filename
);
2033 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2035 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2037 cupsdCloseClient(con
);
2042 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2048 cupsdProcessIPPRequest(con
);
2052 unlink(con
->filename
);
2053 cupsdClearString(&con
->filename
);
2062 break; /* Anti-compiler-warning-code */
2065 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2067 if (!httpGetKeepAlive(con
->http
))
2069 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2070 "Closing because Keep-Alive is disabled.");
2071 cupsdCloseClient(con
);
2075 cupsArrayRemove(ActiveClients
, con
);
2076 cupsdSetBusyState();
2083 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2086 int /* O - 1 on success, 0 on failure */
2088 cupsd_client_t
*con
, /* I - Client connection */
2089 char *command
, /* I - Command to run */
2090 char *options
, /* I - Command-line options */
2091 int root
) /* I - Run as root? */
2093 int fd
; /* Standard input file descriptor */
2098 fd
= open(con
->filename
, O_RDONLY
);
2102 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2103 "Unable to open \"%s\" for reading: %s",
2104 con
->filename
? con
->filename
: "/dev/null",
2109 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2114 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2115 con
->pipe_status
= HTTP_STATUS_OK
;
2117 httpClearFields(con
->http
);
2122 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2123 command
, con
->pipe_pid
, con
->file
);
2125 if (con
->pipe_pid
== 0)
2128 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2130 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2132 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2134 con
->sent_header
= 0;
2135 con
->file_ready
= 0;
2136 con
->got_fields
= 0;
2137 con
->header_used
= 0;
2144 * 'cupsdSendError()' - Send an error message via HTTP.
2147 int /* O - 1 if successful, 0 otherwise */
2148 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2149 http_status_t code
, /* I - Error code */
2150 int auth_type
)/* I - Authentication type */
2152 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2157 * Force client to upgrade for authentication if that is how the
2158 * server is configured...
2161 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2162 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2163 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2164 !httpIsEncrypted(con
->http
))
2166 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2168 #endif /* HAVE_SSL */
2171 * Put the request in the access_log file...
2174 cupsdLogRequest(con
, code
);
2177 * To work around bugs in some proxies, don't use Keep-Alive for some
2180 * Kerberos authentication doesn't work without Keep-Alive, so
2181 * never disable it in that case.
2184 httpClearFields(con
->http
);
2186 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2187 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2189 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2190 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2191 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2193 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2196 * Send a human-readable error message.
2199 char message
[4096], /* Message for user */
2200 urltext
[1024], /* URL redirection text */
2201 redirect
[1024]; /* Redirection link */
2202 const char *text
; /* Status-specific text */
2207 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2208 text
= _cupsLangString(con
->language
,
2209 _("Enter your username and password or the "
2210 "root username and password to access this "
2211 "page. If you are using Kerberos authentication, "
2212 "make sure you have a valid Kerberos ticket."));
2213 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2217 snprintf(urltext
, sizeof(urltext
),
2218 _cupsLangString(con
->language
,
2219 _("You must access this page using the URL "
2220 "<A HREF=\"https://%s:%d%s\">"
2221 "https://%s:%d%s</A>.")),
2222 con
->servername
, con
->serverport
, con
->uri
,
2223 con
->servername
, con
->serverport
, con
->uri
);
2225 snprintf(redirect
, sizeof(redirect
),
2226 "<META HTTP-EQUIV=\"Refresh\" "
2227 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2228 con
->servername
, con
->serverport
, con
->uri
);
2230 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2231 text
= _cupsLangString(con
->language
,
2232 _("The web interface is currently disabled. Run "
2233 "\"cupsctl WebInterface=yes\" to enable it."));
2237 snprintf(message
, sizeof(message
),
2238 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2239 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2242 "\t<META HTTP-EQUIV=\"Content-Type\" "
2243 "CONTENT=\"text/html; charset=utf-8\">\n"
2244 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2245 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2246 "HREF=\"/cups.css\">\n"
2254 _httpStatus(con
->language
, code
), redirect
,
2255 _httpStatus(con
->language
, code
), text
);
2258 * Send an error message back to the client. If the error code is a
2259 * 400 or 500 series, make sure the message contains some text, too!
2262 size_t length
= strlen(message
); /* Length of message */
2264 httpSetLength(con
->http
, length
);
2266 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2269 if (httpWrite2(con
->http
, message
, length
) < 0)
2272 if (httpFlushWrite(con
->http
) < 0)
2277 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2279 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2288 * 'cupsdSendHeader()' - Send an HTTP request.
2291 int /* O - 1 on success, 0 on failure */
2293 cupsd_client_t
*con
, /* I - Client to send to */
2294 http_status_t code
, /* I - HTTP status code */
2295 char *type
, /* I - MIME type of document */
2296 int auth_type
) /* I - Type of authentication */
2298 char auth_str
[1024]; /* Authorization string */
2301 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code
, type
, auth_type
);
2304 * Send the HTTP status header...
2307 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2310 * Treat our special "web interface is disabled" status as "200 OK" for web
2314 code
= HTTP_STATUS_OK
;
2318 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2320 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2321 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2323 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2325 if (auth_type
== CUPSD_AUTH_NONE
)
2327 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2328 auth_type
= cupsdDefaultAuthType();
2330 auth_type
= con
->best
->type
;
2335 if (auth_type
== CUPSD_AUTH_BASIC
)
2336 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2338 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2341 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2342 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2344 # endif /* AF_LOCAL */
2345 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2347 #endif /* HAVE_GSSAPI */
2349 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2350 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2353 * Add a "trc" (try root certification) parameter for local non-Kerberos
2354 * requests when the request requires system group membership - then the
2355 * client knows the root certificate can/should be used.
2357 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2358 * parameter as needed...
2361 char *name
, /* Current user name */
2362 *auth_key
; /* Auth key buffer */
2363 size_t auth_size
; /* Size of remaining buffer */
2365 auth_key
= auth_str
+ strlen(auth_str
);
2366 auth_size
= sizeof(auth_str
) - (size_t)(auth_key
- auth_str
);
2368 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2370 name
= (char *)cupsArrayNext(con
->best
->names
))
2372 #ifdef HAVE_AUTHORIZATION_H
2373 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2375 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2376 /* end parenthesis is stripped in conf.c */
2380 #endif /* HAVE_AUTHORIZATION_H */
2381 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2383 #ifdef HAVE_AUTHORIZATION_H
2384 if (SystemGroupAuthKey
)
2385 snprintf(auth_key
, auth_size
,
2387 SystemGroupAuthKey
);
2390 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2391 #endif /* HAVE_AUTHORIZATION_H */
2399 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2401 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2405 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2406 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2410 if (!strcmp(type
, "text/html"))
2411 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2413 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2416 return (!httpWriteResponse(con
->http
, code
));
2421 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2425 cupsdUpdateCGI(void)
2427 char *ptr
, /* Pointer to end of line in buffer */
2428 message
[1024]; /* Pointer to message text */
2429 int loglevel
; /* Log level for message */
2432 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2433 message
, sizeof(message
))) != NULL
)
2435 if (loglevel
== CUPSD_LOG_INFO
)
2436 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2438 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2442 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2445 * Fatal error on pipe - should never happen!
2448 cupsdLogMessage(CUPSD_LOG_CRIT
,
2449 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2456 * 'cupsdWriteClient()' - Write data to a client as needed.
2460 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2462 int bytes
, /* Number of bytes written */
2463 field_col
; /* Current column */
2464 char *bufptr
, /* Pointer into buffer */
2465 *bufend
; /* Pointer to end of buffer */
2466 ipp_state_t ipp_state
; /* IPP state value */
2469 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2470 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2475 "data_encoding=HTTP_ENCODING_%s, "
2476 "data_remaining=" CUPS_LLFMT
", "
2480 httpError(con
->http
), (int)httpGetReady(con
->http
),
2481 httpStateString(httpGetState(con
->http
)),
2482 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2483 CUPS_LLCAST
httpGetLength2(con
->http
),
2485 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2486 con
->pipe_pid
, con
->file
);
2488 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2489 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2492 * If we get called in the wrong state, then something went wrong with the
2493 * connection and we need to shut it down...
2496 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2497 httpStateString(httpGetState(con
->http
)));
2498 cupsdCloseClient(con
);
2505 * Make sure we select on the CGI output...
2508 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2510 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2512 if (!con
->file_ready
)
2515 * Try again later when there is CGI output available...
2518 cupsdRemoveSelect(httpGetFd(con
->http
));
2522 con
->file_ready
= 0;
2525 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2527 if (!con
->pipe_pid
&& bytes
> (ssize_t
)httpGetRemaining(con
->http
))
2530 * Limit GET bytes to original size of file (STR #3265)...
2533 bytes
= (ssize_t
)httpGetRemaining(con
->http
);
2536 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2538 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2543 * Write a single attribute or the IPP message header...
2546 ipp_state
= ippWrite(con
->http
, con
->response
);
2549 * If the write buffer has been flushed, stop buffering up attributes...
2552 if (httpGetPending(con
->http
) <= wused
)
2555 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2557 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2558 "Writing IPP response, ipp_state=%s, old "
2559 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2560 ippStateString(ipp_state
),
2561 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2563 if (httpGetPending(con
->http
) > 0)
2564 httpFlushWrite(con
->http
);
2566 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2567 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2569 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2570 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2571 (int)bytes
, httpGetState(con
->http
),
2572 CUPS_LLCAST
httpGetLength2(con
->http
));
2574 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2576 con
->header_used
+= bytes
;
2578 if (con
->pipe_pid
&& !con
->got_fields
)
2581 * Inspect the data for Content-Type and other fields.
2584 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2586 !con
->got_fields
&& bufptr
< bufend
;
2589 if (*bufptr
== '\n')
2592 * Send line to client...
2595 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2599 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2601 if (!con
->sent_header
)
2604 * Handle redirection and CGI status codes...
2607 http_field_t field
; /* HTTP field */
2608 char *value
= strchr(con
->header
, ':');
2609 /* Value of field */
2614 while (isspace(*value
& 255))
2618 field
= httpFieldValue(con
->header
);
2620 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2622 httpSetField(con
->http
, field
, value
);
2624 if (field
== HTTP_FIELD_LOCATION
)
2626 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2627 con
->sent_header
= 2;
2630 con
->sent_header
= 1;
2632 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2634 con
->pipe_status
= (http_status_t
)atoi(value
);
2635 con
->sent_header
= 2;
2637 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2639 httpSetCookie(con
->http
, value
);
2640 con
->sent_header
= 1;
2648 con
->header_used
-= bufptr
- con
->header
;
2650 if (con
->header_used
> 0)
2651 memmove(con
->header
, bufptr
, (size_t)con
->header_used
);
2653 bufptr
= con
->header
- 1;
2656 * See if the line was empty...
2661 con
->got_fields
= 1;
2663 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2664 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2665 httpSetLength(con
->http
, 0);
2667 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending status %d for CGI.", con
->pipe_status
);
2669 if (con
->pipe_status
== HTTP_STATUS_OK
)
2671 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2673 cupsdCloseClient(con
);
2679 if (!cupsdSendError(con
, con
->pipe_status
, CUPSD_AUTH_NONE
))
2681 cupsdCloseClient(con
);
2689 else if (*bufptr
!= '\r')
2693 if (!con
->got_fields
)
2697 if (con
->header_used
> 0)
2699 if (httpWrite2(con
->http
, con
->header
, (size_t)con
->header_used
) < 0)
2701 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2702 httpError(con
->http
), strerror(httpError(con
->http
)));
2703 cupsdCloseClient(con
);
2707 if (httpIsChunked(con
->http
))
2708 httpFlushWrite(con
->http
);
2710 con
->bytes
+= con
->header_used
;
2712 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2715 bytes
= con
->header_used
;
2717 con
->header_used
= 0;
2722 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2723 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2725 if (!con
->sent_header
&& con
->pipe_pid
)
2726 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2729 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2731 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
> 0))
2733 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2735 if (httpWrite2(con
->http
, "", 0) < 0)
2737 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2738 httpError(con
->http
), strerror(httpError(con
->http
)));
2739 cupsdCloseClient(con
);
2744 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2745 httpFlushWrite(con
->http
);
2746 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2749 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2751 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2755 cupsdRemoveSelect(con
->file
);
2758 cupsdEndProcess(con
->pipe_pid
, 0);
2767 unlink(con
->filename
);
2768 cupsdClearString(&con
->filename
);
2773 ippDelete(con
->request
);
2774 con
->request
= NULL
;
2779 ippDelete(con
->response
);
2780 con
->response
= NULL
;
2783 cupsdClearString(&con
->command
);
2784 cupsdClearString(&con
->options
);
2785 cupsdClearString(&con
->query_string
);
2787 if (!httpGetKeepAlive(con
->http
))
2789 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2790 "Closing because Keep-Alive is disabled.");
2791 cupsdCloseClient(con
);
2796 cupsArrayRemove(ActiveClients
, con
);
2797 cupsdSetBusyState();
2804 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2807 static int /* O - 1 if modified since */
2809 cupsd_client_t
*con
, /* I - Client connection */
2810 struct stat
*filestats
) /* I - File information */
2812 const char *ptr
; /* Pointer into field */
2813 time_t date
; /* Time/date value */
2814 off_t size
; /* Size/length value */
2819 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2824 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2825 "check_if_modified "
2826 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2827 filestats
, CUPS_LLCAST filestats
->st_size
,
2828 (int)filestats
->st_mtime
, ptr
);
2830 while (*ptr
!= '\0')
2832 while (isspace(*ptr
) || *ptr
== ';')
2835 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2838 size
= strtoll(ptr
, NULL
, 10);
2840 while (isdigit(*ptr
))
2843 else if (isalpha(*ptr
))
2845 date
= httpGetDateTime(ptr
);
2846 while (*ptr
!= '\0' && *ptr
!= ';')
2853 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2854 (date
< filestats
->st_mtime
&& date
!= 0) ||
2855 (size
== 0 && date
== 0));
2860 * 'compare_clients()' - Compare two client connections.
2863 static int /* O - Result of comparison */
2864 compare_clients(cupsd_client_t
*a
, /* I - First client */
2865 cupsd_client_t
*b
, /* I - Second client */
2866 void *data
) /* I - User data (not used) */
2881 * 'cupsd_start_tls()' - Start encryption on a connection.
2884 static int /* O - 0 on success, -1 on error */
2885 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2886 http_encryption_t e
) /* I - Encryption mode */
2888 if (httpEncryption(con
->http
, e
))
2890 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2891 cupsLastErrorString());
2895 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Connection now encrypted.");
2898 #endif /* HAVE_SSL */
2902 * 'get_file()' - Get a filename and state info.
2905 static char * /* O - Real filename */
2906 get_file(cupsd_client_t
*con
, /* I - Client connection */
2907 struct stat
*filestats
, /* O - File information */
2908 char *filename
, /* IO - Filename buffer */
2909 size_t len
) /* I - Buffer length */
2911 int status
; /* Status of filesystem calls */
2912 char *ptr
; /* Pointer info filename */
2913 size_t plen
; /* Remaining length after pointer */
2914 char language
[7]; /* Language subdirectory, if any */
2918 * Figure out the real filename...
2923 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2924 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2925 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2927 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
2928 if (access(filename
, F_OK
) < 0)
2929 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2931 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2932 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2933 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2934 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2935 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2937 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2938 strlcpy(filename
, AccessLog
, len
);
2939 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2940 strlcpy(filename
, ErrorLog
, len
);
2941 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2942 strlcpy(filename
, PageLog
, len
);
2946 else if (con
->language
)
2948 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2949 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2952 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2954 if ((ptr
= strchr(filename
, '?')) != NULL
)
2958 * Grab the status for this language; if there isn't a language-specific file
2959 * then fallback to the default one...
2962 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
2963 strncmp(con
->uri
, "/icons/", 7) &&
2964 strncmp(con
->uri
, "/ppd/", 5) &&
2965 strncmp(con
->uri
, "/rss/", 5) &&
2966 strncmp(con
->uri
, "/admin/conf/", 12) &&
2967 strncmp(con
->uri
, "/admin/log/", 11))
2970 * Drop the country code...
2974 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2976 if ((ptr
= strchr(filename
, '?')) != NULL
)
2979 if ((status
= lstat(filename
, filestats
)) != 0)
2982 * Drop the language prefix and try the root directory...
2986 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2988 if ((ptr
= strchr(filename
, '?')) != NULL
)
2991 status
= lstat(filename
, filestats
);
2996 * If we've found a symlink, 404 the sucker to avoid disclosing information.
2999 if (!status
&& S_ISLNK(filestats
->st_mode
))
3001 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3006 * Similarly, if the file/directory does not have world read permissions, do
3007 * not allow access...
3010 if (!status
&& !(filestats
->st_mode
& S_IROTH
))
3012 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3017 * If we've found a directory, get the index.html file instead...
3020 if (!status
&& S_ISDIR(filestats
->st_mode
))
3023 * Make sure the URI ends with a slash...
3026 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3027 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3030 * Find the directory index file, trying every language...
3035 if (status
&& language
[0])
3038 * Try a different language subset...
3042 language
[0] = '\0'; /* Strip country code */
3044 language
[0] = '\0'; /* Strip language */
3048 * Look for the index file...
3051 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3053 if ((ptr
= strchr(filename
, '?')) != NULL
)
3056 ptr
= filename
+ strlen(filename
);
3057 plen
= len
- (size_t)(ptr
- filename
);
3059 strlcpy(ptr
, "index.html", plen
);
3060 status
= stat(filename
, filestats
);
3065 strlcpy(ptr
, "index.class", plen
);
3066 status
= stat(filename
, filestats
);
3068 #endif /* HAVE_JAVA */
3073 strlcpy(ptr
, "index.pl", plen
);
3074 status
= stat(filename
, filestats
);
3076 #endif /* HAVE_PERL */
3081 strlcpy(ptr
, "index.php", plen
);
3082 status
= stat(filename
, filestats
);
3084 #endif /* HAVE_PHP */
3089 strlcpy(ptr
, "index.pyc", plen
);
3090 status
= stat(filename
, filestats
);
3095 strlcpy(ptr
, "index.py", plen
);
3096 status
= stat(filename
, filestats
);
3098 #endif /* HAVE_PYTHON */
3101 while (status
&& language
[0]);
3104 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "get_file filestats=%p, filename=%p, len=" CUPS_LLFMT
", returning \"%s\".", filestats
, filename
, CUPS_LLCAST len
, status
? "(null)" : filename
);
3114 * 'install_cupsd_conf()' - Install a configuration file.
3117 static http_status_t
/* O - Status */
3118 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3120 char filename
[1024]; /* Configuration filename */
3121 cups_file_t
*in
, /* Input file */
3122 *out
; /* Output file */
3123 char buffer
[16384]; /* Copy buffer */
3124 ssize_t bytes
; /* Number of bytes */
3128 * Open the request file...
3131 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3133 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3134 con
->filename
, strerror(errno
));
3135 return (HTTP_STATUS_SERVER_ERROR
);
3139 * Open the new config file...
3142 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3145 return (HTTP_STATUS_SERVER_ERROR
);
3148 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3152 * Copy from the request to the new config file...
3155 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3156 if (cupsFileWrite(out
, buffer
, (size_t)bytes
) < bytes
)
3158 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3159 "Unable to copy to config file \"%s\": %s",
3160 ConfigurationFile
, strerror(errno
));
3165 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3166 cupsdUnlinkOrRemoveFile(filename
);
3168 return (HTTP_STATUS_SERVER_ERROR
);
3172 * Close the files...
3177 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3178 return (HTTP_STATUS_SERVER_ERROR
);
3181 * Remove the request file...
3184 cupsdUnlinkOrRemoveFile(con
->filename
);
3185 cupsdClearString(&con
->filename
);
3188 * Set the NeedReload flag...
3191 NeedReload
= RELOAD_CUPSD
;
3192 ReloadTime
= time(NULL
);
3195 * Return that the file was created successfully...
3198 return (HTTP_STATUS_CREATED
);
3203 * 'is_cgi()' - Is the resource a CGI script/program?
3206 static int /* O - 1 = CGI, 0 = file */
3207 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3208 const char *filename
, /* I - Real filename */
3209 struct stat
*filestats
, /* I - File information */
3210 mime_type_t
*type
) /* I - MIME type */
3212 const char *options
; /* Options on URL */
3216 * Get the options, if any...
3219 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3222 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3226 * Check for known types...
3229 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3231 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3232 "is_cgi filename=\"%s\", filestats=%p, "
3233 "type=%s/%s, returning 0", filename
,
3234 filestats
, type
? type
->super
: "unknown",
3235 type
? type
->type
: "unknown");
3239 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3240 (filestats
->st_mode
& 0111))
3243 * "application/x-httpd-cgi" is a CGI script.
3246 cupsdSetString(&con
->command
, filename
);
3249 cupsdSetStringf(&con
->options
, " %s", options
);
3251 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3252 "is_cgi filename=\"%s\", filestats=%p, "
3253 "type=%s/%s, returning 1", filename
,
3254 filestats
, type
->super
, type
->type
);
3258 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3261 * "application/x-httpd-java" is a Java servlet.
3264 cupsdSetString(&con
->command
, CUPS_JAVA
);
3267 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3269 cupsdSetStringf(&con
->options
, " %s", filename
);
3271 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3272 "is_cgi filename=\"%s\", filestats=%p, "
3273 "type=%s/%s, returning 1", filename
,
3274 filestats
, type
->super
, type
->type
);
3277 #endif /* HAVE_JAVA */
3279 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3282 * "application/x-httpd-perl" is a Perl page.
3285 cupsdSetString(&con
->command
, CUPS_PERL
);
3288 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3290 cupsdSetStringf(&con
->options
, " %s", filename
);
3292 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3293 "is_cgi filename=\"%s\", filestats=%p, "
3294 "type=%s/%s, returning 1", filename
,
3295 filestats
, type
->super
, type
->type
);
3298 #endif /* HAVE_PERL */
3300 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3303 * "application/x-httpd-php" is a PHP page.
3306 cupsdSetString(&con
->command
, CUPS_PHP
);
3309 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3311 cupsdSetStringf(&con
->options
, " %s", filename
);
3313 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3314 "is_cgi filename=\"%s\", filestats=%p, "
3315 "type=%s/%s, returning 1", filename
,
3316 filestats
, type
->super
, type
->type
);
3319 #endif /* HAVE_PHP */
3321 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3324 * "application/x-httpd-python" is a Python page.
3327 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3330 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3332 cupsdSetStringf(&con
->options
, " %s", filename
);
3334 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3335 "is_cgi filename=\"%s\", filestats=%p, "
3336 "type=%s/%s, returning 1", filename
,
3337 filestats
, type
->super
, type
->type
);
3340 #endif /* HAVE_PYTHON */
3342 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3343 "is_cgi filename=\"%s\", filestats=%p, "
3344 "type=%s/%s, returning 0", filename
,
3345 filestats
, type
->super
, type
->type
);
3351 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3354 static int /* O - 0 if relative, 1 if absolute */
3355 is_path_absolute(const char *path
) /* I - Input path */
3358 * Check for a leading slash...
3365 * Check for "<" or quotes in the path and reject since this is probably
3366 * someone trying to inject HTML...
3369 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3373 * Check for "/.." in the path...
3376 while ((path
= strstr(path
, "/..")) != NULL
)
3378 if (!path
[3] || path
[3] == '/')
3385 * If we haven't found any relative paths, return 1 indicating an
3394 * 'pipe_command()' - Pipe the output of a command to the remote client.
3397 static int /* O - Process ID */
3398 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3399 int infile
, /* I - Standard input for command */
3400 int *outfile
, /* O - Standard output for command */
3401 char *command
, /* I - Command to run */
3402 char *options
, /* I - Options for command */
3403 int root
) /* I - Run as root? */
3405 int i
; /* Looping var */
3406 int pid
; /* Process ID */
3407 char *commptr
, /* Command string pointer */
3408 commch
; /* Command string character */
3409 char *uriptr
; /* URI string pointer */
3410 int fds
[2]; /* Pipe FDs */
3411 int argc
; /* Number of arguments */
3412 int envc
; /* Number of environment variables */
3413 char argbuf
[10240], /* Argument buffer */
3414 *argv
[100], /* Argument strings */
3415 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3416 char auth_type
[256], /* AUTH_TYPE environment variable */
3417 content_length
[1024], /* CONTENT_LENGTH environment variable */
3418 content_type
[1024], /* CONTENT_TYPE environment variable */
3419 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3420 http_referer
[1024], /* HTTP_REFERER environment variable */
3421 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3422 lang
[1024], /* LANG environment variable */
3423 path_info
[1024], /* PATH_INFO environment variable */
3424 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3425 remote_host
[1024], /* REMOTE_HOST environment variable */
3426 remote_user
[1024], /* REMOTE_USER environment variable */
3427 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3428 script_name
[1024], /* SCRIPT_NAME environment variable */
3429 server_name
[1024], /* SERVER_NAME environment variable */
3430 server_port
[1024]; /* SERVER_PORT environment variable */
3431 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3435 * Parse a copy of the options string, which is of the form:
3437 * argument+argument+argument
3438 * ?argument+argument+argument
3439 * param=value¶m=value
3440 * ?param=value¶m=value
3441 * /name?argument+argument+argument
3442 * /name?param=value¶m=value
3444 * If the string contains an "=" character after the initial name,
3445 * then we treat it as a HTTP GET form request and make a copy of
3446 * the remaining string for the environment variable.
3448 * The string is always parsed out as command-line arguments, to
3449 * be consistent with Apache...
3452 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3453 "pipe_command infile=%d, outfile=%p, "
3454 "command=\"%s\", options=\"%s\", root=%d",
3455 infile
, outfile
, command
,
3456 options
? options
: "(null)", root
);
3463 if (*commptr
== ' ')
3465 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3470 if (argbuf
[0] == '/')
3473 * Found some trailing path information, set PATH_INFO...
3476 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3477 commptr
= argbuf
+ strlen(argbuf
);
3481 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3487 path_info
[0] = '\0';
3489 if (*commptr
== ' ')
3493 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3496 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3503 argv
[argc
++] = commptr
;
3505 for (; *commptr
&& argc
< 99; commptr
++)
3508 * Break arguments whenever we see a + or space...
3511 if (*commptr
== ' ' || *commptr
== '+')
3513 while (*commptr
== ' ' || *commptr
== '+')
3517 * If we don't have a blank string, save it as another argument...
3522 argv
[argc
] = commptr
;
3528 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3529 isxdigit(commptr
[2] & 255))
3532 * Convert the %xx notation to the individual character.
3535 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3536 *commptr
= (char)((commptr
[1] - '0') << 4);
3538 *commptr
= (char)((tolower(commptr
[1]) - 'a' + 10) << 4);
3540 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3541 *commptr
|= commptr
[2] - '0';
3543 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3545 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3548 * Check for a %00 and break if that is the case...
3560 * Setup the environment variables as needed...
3563 if (con
->username
[0])
3565 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3566 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3568 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3572 auth_type
[0] = '\0';
3575 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3576 IPP_TAG_LANGUAGE
)) != NULL
)
3578 switch (strlen(attr
->values
[0].string
.text
))
3582 * This is an unknown or badly formatted language code; use
3583 * the POSIX locale...
3586 strlcpy(lang
, "LANG=C", sizeof(lang
));
3591 * Just the language code (ll)...
3594 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3595 attr
->values
[0].string
.text
);
3600 * Language and country code (ll-cc)...
3603 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3604 attr
->values
[0].string
.text
[0],
3605 attr
->values
[0].string
.text
[1],
3606 toupper(attr
->values
[0].string
.text
[3] & 255),
3607 toupper(attr
->values
[0].string
.text
[4] & 255));
3611 else if (con
->language
)
3612 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3614 strlcpy(lang
, "LANG=C", sizeof(lang
));
3616 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3617 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3618 sizeof(remote_addr
) - 12);
3620 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3621 httpGetHostname(con
->http
, NULL
, 0));
3623 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3624 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3627 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3628 DocumentRoot
, script_name
+ 12);
3630 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3632 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3634 char *nameptr
; /* Pointer to ":port" */
3636 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3637 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3638 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3639 *nameptr
= '\0'; /* Strip trailing ":port" */
3642 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3645 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3648 envp
[envc
++] = auth_type
;
3650 envp
[envc
++] = lang
;
3651 envp
[envc
++] = "REDIRECT_STATUS=1";
3652 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3653 envp
[envc
++] = server_name
;
3654 envp
[envc
++] = server_port
;
3655 envp
[envc
++] = remote_addr
;
3656 envp
[envc
++] = remote_host
;
3657 envp
[envc
++] = script_name
;
3658 envp
[envc
++] = script_filename
;
3661 envp
[envc
++] = path_info
;
3663 if (con
->username
[0])
3665 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3667 envp
[envc
++] = remote_user
;
3670 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3671 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3672 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3673 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3675 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3677 if (httpGetCookie(con
->http
))
3679 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3680 httpGetCookie(con
->http
));
3681 envp
[envc
++] = http_cookie
;
3684 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3686 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3687 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3688 envp
[envc
++] = http_user_agent
;
3691 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3693 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3694 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3695 envp
[envc
++] = http_referer
;
3698 if (con
->operation
== HTTP_STATE_GET
)
3700 envp
[envc
++] = "REQUEST_METHOD=GET";
3702 if (con
->query_string
)
3705 * Add GET form variables after ?...
3708 envp
[envc
++] = con
->query_string
;
3711 envp
[envc
++] = "QUERY_STRING=";
3715 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3716 CUPS_LLCAST con
->bytes
);
3717 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3718 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3720 envp
[envc
++] = "REQUEST_METHOD=POST";
3721 envp
[envc
++] = content_length
;
3722 envp
[envc
++] = content_type
;
3726 * Tell the CGI if we are using encryption...
3729 if (httpIsEncrypted(con
->http
))
3730 envp
[envc
++] = "HTTPS=ON";
3733 * Terminate the environment array...
3738 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3740 for (i
= 0; i
< argc
; i
++)
3741 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3742 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3743 for (i
= 0; i
< envc
; i
++)
3744 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3745 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3749 * Create a pipe for the output...
3752 if (cupsdOpenPipe(fds
))
3754 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3755 argv
[0], strerror(errno
));
3760 * Then execute the command...
3763 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3764 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3767 * Error - can't fork!
3770 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3773 cupsdClosePipe(fds
);
3779 * Fork successful - return the PID...
3782 if (con
->username
[0])
3783 cupsdAddCert(pid
, con
->username
, con
->type
);
3785 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3796 * 'valid_host()' - Is the Host: field valid?
3799 static int /* O - 1 if valid, 0 if not */
3800 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3802 cupsd_alias_t
*a
; /* Current alias */
3803 cupsd_netif_t
*netif
; /* Current network interface */
3804 const char *end
; /* End character */
3805 char *ptr
; /* Pointer into host value */
3809 * Copy the Host: header for later use...
3812 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3813 sizeof(con
->clientname
));
3814 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3817 con
->clientport
= atoi(ptr
);
3820 con
->clientport
= con
->serverport
;
3826 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3829 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3830 * addresses when accessing CUPS via the loopback interface...
3833 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3834 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3836 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3837 #endif /* __linux */
3838 !strcmp(con
->clientname
, "127.0.0.1") ||
3839 !strcmp(con
->clientname
, "[::1]"));
3842 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3844 * Check if the hostname is something.local (Bonjour); if so, allow it.
3847 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3851 * "." on end, work back to second-to-last "."...
3854 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3857 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3858 !_cups_strcasecmp(end
, ".local.")))
3860 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3863 * Check if the hostname is an IP address...
3866 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3869 * Possible IPv4/IPv6 address...
3872 http_addrlist_t
*addrlist
; /* List of addresses */
3875 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3878 * Good IPv4/IPv6 address...
3881 httpAddrFreeList(addrlist
);
3887 * Check for (alias) name matches...
3890 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3892 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3895 * "ServerAlias *" allows all host values through...
3898 if (!strcmp(a
->name
, "*"))
3901 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3904 * Prefix matches; check the character at the end - it must be "." or nul.
3907 end
= con
->clientname
+ a
->namelen
;
3909 if (!*end
|| (*end
== '.' && !end
[1]))
3914 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3915 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3917 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3920 * "ServerAlias *" allows all host values through...
3923 if (!strcmp(a
->name
, "*"))
3926 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3929 * Prefix matches; check the character at the end - it must be "." or nul.
3932 end
= con
->clientname
+ a
->namelen
;
3934 if (!*end
|| (*end
== '.' && !end
[1]))
3938 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3941 * Check for interface hostname matches...
3944 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3946 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3948 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3951 * Prefix matches; check the character at the end - it must be "." or nul.
3954 end
= con
->clientname
+ netif
->hostlen
;
3956 if (!*end
|| (*end
== '.' && !end
[1]))
3966 * 'write_file()' - Send a file via HTTP.
3969 static int /* O - 0 on failure, 1 on success */
3970 write_file(cupsd_client_t
*con
, /* I - Client connection */
3971 http_status_t code
, /* I - HTTP status */
3972 char *filename
, /* I - Filename */
3973 char *type
, /* I - File type */
3974 struct stat
*filestats
) /* O - File information */
3976 con
->file
= open(filename
, O_RDONLY
);
3978 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3979 "write_file code=%d, filename=\"%s\" (%d), "
3980 "type=\"%s\", filestats=%p",
3981 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3986 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3989 con
->sent_header
= 1;
3991 httpClearFields(con
->http
);
3993 httpSetLength(con
->http
, (size_t)filestats
->st_size
);
3995 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3996 httpGetDateString(filestats
->st_mtime
));
3998 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4001 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4003 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4010 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4014 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4016 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4019 con
->file_ready
= 1;
4021 cupsdRemoveSelect(con
->file
);
4022 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4024 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");