4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2013 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * Include necessary headers...
23 #define _CUPS_NO_DEPRECATED
24 #define _HTTP_NO_PRIVATE
29 #endif /* __APPLE__ */
32 #endif /* HAVE_TCPD_H */
39 static int check_if_modified(cupsd_client_t
*con
,
40 struct stat
*filestats
);
41 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
44 static int cupsd_start_tls(cupsd_client_t
*con
, http_encryption_t e
);
46 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
47 char *filename
, int len
);
48 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
49 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
50 struct stat
*filestats
, mime_type_t
*type
);
51 static int is_path_absolute(const char *path
);
52 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
53 char *command
, char *options
, int root
);
54 static int valid_host(cupsd_client_t
*con
);
55 static int write_file(cupsd_client_t
*con
, http_status_t code
,
56 char *filename
, char *type
,
57 struct stat
*filestats
);
58 static void write_pipe(cupsd_client_t
*con
);
62 * 'cupsdAcceptClient()' - Accept a new client.
66 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
68 const char *hostname
; /* Hostname of client */
69 char name
[256]; /* Hostname of client */
70 int count
; /* Count of connections on a host */
71 cupsd_client_t
*con
, /* New client pointer */
72 *tempcon
; /* Temporary client pointer */
73 socklen_t addrlen
; /* Length of address */
74 http_addr_t temp
; /* Temporary address variable */
75 static time_t last_dos
= 0; /* Time of last DoS attack */
77 struct request_info wrap_req
; /* TCP wrappers request information */
78 #endif /* HAVE_TCPD_H */
81 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
82 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
83 lis
, lis
->fd
, cupsArrayCount(Clients
));
86 * Make sure we don't have a full set of clients already...
89 if (cupsArrayCount(Clients
) == MaxClients
)
93 * Get a pointer to the next available client...
97 Clients
= cupsArrayNew(NULL
, NULL
);
101 cupsdLogMessage(CUPSD_LOG_ERROR
,
102 "Unable to allocate memory for clients array!");
103 cupsdPauseListening();
108 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
112 cupsdLogMessage(CUPSD_LOG_ERROR
,
113 "Unable to allocate memory for active clients array!");
114 cupsdPauseListening();
118 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
120 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
121 cupsdPauseListening();
126 * Accept the client and get the remote address...
129 con
->number
= ++ LastClientNumber
;
132 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
134 if (errno
== ENFILE
|| errno
== EMFILE
)
135 cupsdPauseListening();
137 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
145 * Save the connected address and port number...
148 con
->clientaddr
= lis
->address
;
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(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
280 if (!proc_name(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), name
, (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
);
599 * Automatically check for a SSL/TLS handshake...
604 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
605 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
608 * Encrypt this connection...
611 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
612 "Saw first byte %02X, auto-negotiating "
613 "SSL/TLS session.", buf
[0] & 255);
615 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_ALWAYS
))
616 cupsdCloseClient(con
);
621 #endif /* HAVE_SSL */
623 switch (httpGetState(con
->http
))
625 case HTTP_STATE_WAITING
:
627 * See if we've received a request line...
630 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
631 if (con
->operation
== HTTP_STATE_ERROR
||
632 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
633 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
635 if (httpError(con
->http
))
636 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
637 "HTTP_STATE_WAITING Closing for error %d (%s)",
638 httpError(con
->http
), strerror(httpError(con
->http
)));
640 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
641 "HTTP_STATE_WAITING Closing on error: %s",
642 cupsLastErrorString());
644 cupsdCloseClient(con
);
649 * Ignore blank request lines...
652 if (con
->operation
== HTTP_STATE_WAITING
)
656 * Clear other state variables...
663 con
->username
[0] = '\0';
664 con
->password
[0] = '\0';
666 cupsdClearString(&con
->command
);
667 cupsdClearString(&con
->options
);
668 cupsdClearString(&con
->query_string
);
672 ippDelete(con
->request
);
678 ippDelete(con
->response
);
679 con
->response
= NULL
;
684 cupsLangFree(con
->language
);
685 con
->language
= NULL
;
691 #endif /* HAVE_GSSAPI */
694 * Handle full URLs in the request line...
697 if (strcmp(con
->uri
, "*"))
699 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
700 userpass
[HTTP_MAX_URI
], /* Username:password */
701 hostname
[HTTP_MAX_URI
], /* Hostname */
702 resource
[HTTP_MAX_URI
]; /* Resource path */
703 int port
; /* Port number */
706 * Separate the URI into its components...
709 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
710 scheme
, sizeof(scheme
),
711 userpass
, sizeof(userpass
),
712 hostname
, sizeof(hostname
), &port
,
713 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
715 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
717 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
718 cupsdCloseClient(con
);
723 * Only allow URIs with the servername, localhost, or an IP
727 if (strcmp(scheme
, "file") &&
728 _cups_strcasecmp(hostname
, ServerName
) &&
729 _cups_strcasecmp(hostname
, "localhost") &&
730 !cupsArrayFind(ServerAlias
, hostname
) &&
731 !isdigit(hostname
[0]) && hostname
[0] != '[')
734 * Nope, we don't do proxies...
737 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
739 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
740 cupsdCloseClient(con
);
745 * Copy the resource portion back into the URI; both resource and
746 * con->uri are HTTP_MAX_URI bytes in size...
749 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
753 * Process the request...
756 gettimeofday(&(con
->start
), NULL
);
758 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
759 httpStateString(con
->operation
) + 11, con
->uri
,
760 httpGetVersion(con
->http
) / 100,
761 httpGetVersion(con
->http
) % 100);
763 if (!cupsArrayFind(ActiveClients
, con
))
765 cupsArrayAdd(ActiveClients
, con
);
769 case HTTP_STATE_OPTIONS
:
770 case HTTP_STATE_DELETE
:
771 case HTTP_STATE_GET
:
772 case HTTP_STATE_HEAD
:
773 case HTTP_STATE_POST
:
774 case HTTP_STATE_PUT
:
775 case HTTP_STATE_TRACE
:
777 * Parse incoming parameters until the status changes...
780 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
781 if (!httpGetReady(con
->http
))
784 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
786 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
787 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
788 "Closing for error %d (%s) while reading headers.",
789 httpError(con
->http
), strerror(httpError(con
->http
)));
791 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
792 "Closing on EOF while reading headers.");
794 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
795 cupsdCloseClient(con
);
801 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
804 * Connection closed...
807 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
808 cupsdCloseClient(con
);
811 break; /* Anti-compiler-warning-code */
815 * Handle new transfers...
818 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Read: status=%d", status
);
820 if (status
== HTTP_STATUS_OK
)
822 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
825 * Figure out the locale from the Accept-Language and Content-Type
829 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
833 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
837 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
838 "charset=")) != NULL
)
841 * Combine language and charset, and trim any extra params in the
845 snprintf(locale
, sizeof(locale
), "%s.%s",
846 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
848 if ((ptr
= strchr(locale
, ',')) != NULL
)
852 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
853 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
855 con
->language
= cupsLangGet(locale
);
858 con
->language
= cupsLangGet(DefaultLocale
);
862 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
863 "Keep-Alive", 10) && KeepAlive
)
864 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
865 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
867 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
869 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
870 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
873 * HTTP/1.1 and higher require the "Host:" field...
876 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
878 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
879 cupsdCloseClient(con
);
883 else if (!valid_host(con
))
886 * Access to localhost must use "localhost" or the corresponding IPv4
887 * or IPv6 values in the Host: field.
890 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
891 "Request from \"%s\" using invalid Host: field \"%s\".",
892 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
894 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
896 cupsdCloseClient(con
);
900 else if (con
->operation
== HTTP_STATE_OPTIONS
)
903 * Do OPTIONS command...
906 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
908 httpClearFields(con
->http
);
910 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
912 cupsdCloseClient(con
);
917 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
918 !httpIsEncrypted(con
->http
))
922 * Do encryption stuff...
925 httpClearFields(con
->http
);
927 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
929 cupsdCloseClient(con
);
933 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
935 cupsdCloseClient(con
);
939 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
941 cupsdCloseClient(con
);
944 #endif /* HAVE_SSL */
947 httpClearFields(con
->http
);
948 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
949 "GET, HEAD, OPTIONS, POST, PUT");
950 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
952 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
954 cupsdCloseClient(con
);
958 else if (!is_path_absolute(con
->uri
))
961 * Protect against malicious users!
964 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
965 "Request for non-absolute resource \"%s\".", con
->uri
);
967 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
969 cupsdCloseClient(con
);
975 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
976 "Upgrade") && !httpIsEncrypted(con
->http
))
980 * Do encryption stuff...
983 httpClearFields(con
->http
);
985 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
988 cupsdCloseClient(con
);
992 if (cupsd_start_tls(con
, HTTP_ENCRYPTION_REQUIRED
))
994 cupsdCloseClient(con
);
998 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1000 cupsdCloseClient(con
);
1003 #endif /* HAVE_SSL */
1006 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1008 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1009 cupsdCloseClient(con
);
1013 if (httpGetExpect(con
->http
) &&
1014 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1016 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1019 * Send 100-continue header...
1022 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1024 cupsdCloseClient(con
);
1031 * Send 417-expectation-failed header...
1034 httpClearFields(con
->http
);
1035 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1037 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1038 cupsdCloseClient(con
);
1043 switch (httpGetState(con
->http
))
1045 case HTTP_STATE_GET_SEND
:
1046 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Processing GET %s", con
->uri
);
1048 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1049 !strncmp(con
->uri
, "/printers/", 10) ||
1050 !strncmp(con
->uri
, "/classes/", 9)) &&
1051 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1054 * Send PPD file - get the real printer name since printer
1055 * names are not case sensitive but filenames can be...
1058 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1060 if (!strncmp(con
->uri
, "/ppd/", 5))
1061 p
= cupsdFindPrinter(con
->uri
+ 5);
1062 else if (!strncmp(con
->uri
, "/printers/", 10))
1063 p
= cupsdFindPrinter(con
->uri
+ 10);
1066 p
= cupsdFindClass(con
->uri
+ 9);
1070 int i
; /* Looping var */
1072 for (i
= 0; i
< p
->num_printers
; i
++)
1074 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1076 char ppdname
[1024];/* PPD filename */
1078 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1079 ServerRoot
, p
->printers
[i
]->name
);
1080 if (!access(ppdname
, 0))
1088 if (i
>= p
->num_printers
)
1095 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1099 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1101 cupsdCloseClient(con
);
1108 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1109 !strncmp(con
->uri
, "/printers/", 10) ||
1110 !strncmp(con
->uri
, "/classes/", 9)) &&
1111 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1114 * Send icon file - get the real queue name since queue names are
1115 * not case sensitive but filenames can be...
1118 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1120 if (!strncmp(con
->uri
, "/icons/", 7))
1121 p
= cupsdFindPrinter(con
->uri
+ 7);
1122 else if (!strncmp(con
->uri
, "/printers/", 10))
1123 p
= cupsdFindPrinter(con
->uri
+ 10);
1126 p
= cupsdFindClass(con
->uri
+ 9);
1130 int i
; /* Looping var */
1132 for (i
= 0; i
< p
->num_printers
; i
++)
1134 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1136 char ppdname
[1024];/* PPD filename */
1138 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1139 ServerRoot
, p
->printers
[i
]->name
);
1140 if (!access(ppdname
, 0))
1148 if (i
>= p
->num_printers
)
1154 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1157 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1159 cupsdCloseClient(con
);
1166 else if (!WebInterface
)
1169 * Web interface is disabled. Show an appropriate message...
1172 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1174 cupsdCloseClient(con
);
1181 if ((!strncmp(con
->uri
, "/admin", 6) &&
1182 strncmp(con
->uri
, "/admin/conf/", 12) &&
1183 strncmp(con
->uri
, "/admin/log/", 11)) ||
1184 !strncmp(con
->uri
, "/printers", 9) ||
1185 !strncmp(con
->uri
, "/classes", 8) ||
1186 !strncmp(con
->uri
, "/help", 5) ||
1187 !strncmp(con
->uri
, "/jobs", 5))
1190 * Send CGI output...
1193 if (!strncmp(con
->uri
, "/admin", 6))
1195 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1198 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1200 else if (!strncmp(con
->uri
, "/printers", 9))
1202 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1205 if (con
->uri
[9] && con
->uri
[10])
1206 cupsdSetString(&con
->options
, con
->uri
+ 9);
1208 cupsdSetString(&con
->options
, NULL
);
1210 else if (!strncmp(con
->uri
, "/classes", 8))
1212 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1215 if (con
->uri
[8] && con
->uri
[9])
1216 cupsdSetString(&con
->options
, con
->uri
+ 8);
1218 cupsdSetString(&con
->options
, NULL
);
1220 else if (!strncmp(con
->uri
, "/jobs", 5))
1222 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1225 if (con
->uri
[5] && con
->uri
[6])
1226 cupsdSetString(&con
->options
, con
->uri
+ 5);
1228 cupsdSetString(&con
->options
, NULL
);
1232 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1235 if (con
->uri
[5] && con
->uri
[6])
1236 cupsdSetString(&con
->options
, con
->uri
+ 5);
1238 cupsdSetString(&con
->options
, NULL
);
1241 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1243 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1245 cupsdCloseClient(con
);
1250 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1252 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1253 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1255 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1256 (strchr(con
->uri
+ 12, '/') ||
1257 strlen(con
->uri
) == 12)) ||
1258 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1259 (strchr(con
->uri
+ 11, '/') ||
1260 strlen(con
->uri
) == 11)))
1263 * GET can only be done to configuration files directly under
1267 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1268 "Request for subdirectory \"%s\"!", con
->uri
);
1270 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1272 cupsdCloseClient(con
);
1284 if ((filename
= get_file(con
, &filestats
, buf
,
1285 sizeof(buf
))) == NULL
)
1287 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1289 cupsdCloseClient(con
);
1296 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1298 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "filename=\"%s\", type=%s/%s", filename
, type
? type
->super
: "", type
? type
->type
: "");
1300 if (is_cgi(con
, filename
, &filestats
, type
))
1303 * Note: con->command and con->options were set by
1307 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1309 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1311 cupsdCloseClient(con
);
1316 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1318 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1319 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1323 if (!check_if_modified(con
, &filestats
))
1325 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1327 cupsdCloseClient(con
);
1334 strlcpy(line
, "text/plain", sizeof(line
));
1336 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1338 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1340 cupsdCloseClient(con
);
1347 case HTTP_STATE_POST_RECV
:
1349 * See if the POST request includes a Content-Length field, and if
1350 * so check the length against any limits that are set...
1353 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1354 MaxRequestSize
> 0 &&
1355 httpGetLength2(con
->http
) > MaxRequestSize
)
1358 * Request too large...
1361 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1363 cupsdCloseClient(con
);
1369 else if (httpGetLength2(con
->http
) < 0)
1372 * Negative content lengths are invalid!
1375 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1377 cupsdCloseClient(con
);
1385 * See what kind of POST request this is; for IPP requests the
1386 * content-type field will be "application/ipp"...
1389 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1391 con
->request
= ippNew();
1392 else if (!WebInterface
)
1395 * Web interface is disabled. Show an appropriate message...
1398 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1400 cupsdCloseClient(con
);
1406 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1407 strncmp(con
->uri
, "/admin/conf/", 12) &&
1408 strncmp(con
->uri
, "/admin/log/", 11)) ||
1409 !strncmp(con
->uri
, "/printers", 9) ||
1410 !strncmp(con
->uri
, "/classes", 8) ||
1411 !strncmp(con
->uri
, "/help", 5) ||
1412 !strncmp(con
->uri
, "/jobs", 5))
1418 if (!strncmp(con
->uri
, "/admin", 6))
1420 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1423 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1425 else if (!strncmp(con
->uri
, "/printers", 9))
1427 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1430 if (con
->uri
[9] && con
->uri
[10])
1431 cupsdSetString(&con
->options
, con
->uri
+ 9);
1433 cupsdSetString(&con
->options
, NULL
);
1435 else if (!strncmp(con
->uri
, "/classes", 8))
1437 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1440 if (con
->uri
[8] && con
->uri
[9])
1441 cupsdSetString(&con
->options
, con
->uri
+ 8);
1443 cupsdSetString(&con
->options
, NULL
);
1445 else if (!strncmp(con
->uri
, "/jobs", 5))
1447 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1450 if (con
->uri
[5] && con
->uri
[6])
1451 cupsdSetString(&con
->options
, con
->uri
+ 5);
1453 cupsdSetString(&con
->options
, NULL
);
1457 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1460 if (con
->uri
[5] && con
->uri
[6])
1461 cupsdSetString(&con
->options
, con
->uri
+ 5);
1463 cupsdSetString(&con
->options
, NULL
);
1466 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1467 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1475 if ((filename
= get_file(con
, &filestats
, buf
,
1476 sizeof(buf
))) == NULL
)
1478 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1480 cupsdCloseClient(con
);
1487 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1489 if (!is_cgi(con
, filename
, &filestats
, type
))
1492 * Only POST to CGI's...
1495 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1497 cupsdCloseClient(con
);
1504 case HTTP_STATE_PUT_RECV
:
1506 * Validate the resource name...
1509 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1512 * PUT can only be done to the cupsd.conf file...
1515 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1516 "Disallowed PUT request for \"%s\".", con
->uri
);
1518 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1520 cupsdCloseClient(con
);
1528 * See if the PUT request includes a Content-Length field, and if
1529 * so check the length against any limits that are set...
1532 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1533 MaxRequestSize
> 0 &&
1534 httpGetLength2(con
->http
) > MaxRequestSize
)
1537 * Request too large...
1540 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1542 cupsdCloseClient(con
);
1548 else if (httpGetLength2(con
->http
) < 0)
1551 * Negative content lengths are invalid!
1554 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1556 cupsdCloseClient(con
);
1564 * Open a temporary file to hold the request...
1567 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1569 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1573 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1574 "Unable to create request file \"%s\": %s",
1575 con
->filename
, strerror(errno
));
1577 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1579 cupsdCloseClient(con
);
1584 fchmod(con
->file
, 0640);
1585 fchown(con
->file
, RunUser
, Group
);
1586 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1589 case HTTP_STATE_DELETE
:
1590 case HTTP_STATE_TRACE
:
1591 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1592 cupsdCloseClient(con
);
1595 case HTTP_STATE_HEAD
:
1596 if (!strncmp(con
->uri
, "/printers/", 10) &&
1597 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1600 * Send PPD file - get the real printer name since printer
1601 * names are not case sensitive but filenames can be...
1604 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1606 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1607 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1610 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1612 cupsdCloseClient(con
);
1616 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1620 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1621 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1624 * Send PNG file - get the real printer name since printer
1625 * names are not case sensitive but filenames can be...
1628 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1630 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1631 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1634 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1636 cupsdCloseClient(con
);
1640 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1644 else if (!WebInterface
)
1646 httpClearFields(con
->http
);
1648 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1650 cupsdCloseClient(con
);
1654 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1658 if ((!strncmp(con
->uri
, "/admin", 6) &&
1659 strncmp(con
->uri
, "/admin/conf/", 12) &&
1660 strncmp(con
->uri
, "/admin/log/", 11)) ||
1661 !strncmp(con
->uri
, "/printers", 9) ||
1662 !strncmp(con
->uri
, "/classes", 8) ||
1663 !strncmp(con
->uri
, "/help", 5) ||
1664 !strncmp(con
->uri
, "/jobs", 5))
1670 httpClearFields(con
->http
);
1672 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1674 cupsdCloseClient(con
);
1678 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1680 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1681 (strchr(con
->uri
+ 12, '/') ||
1682 strlen(con
->uri
) == 12)) ||
1683 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1684 (strchr(con
->uri
+ 11, '/') ||
1685 strlen(con
->uri
) == 11)))
1688 * HEAD can only be done to configuration files under
1692 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1693 "Request for subdirectory \"%s\".", con
->uri
);
1695 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1697 cupsdCloseClient(con
);
1701 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1704 else if ((filename
= get_file(con
, &filestats
, buf
,
1705 sizeof(buf
))) == NULL
)
1707 httpClearFields(con
->http
);
1709 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1712 cupsdCloseClient(con
);
1716 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1718 else if (!check_if_modified(con
, &filestats
))
1720 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1722 cupsdCloseClient(con
);
1726 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1734 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1736 strlcpy(line
, "text/plain", sizeof(line
));
1738 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1740 httpClearFields(con
->http
);
1742 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1743 httpGetDateString(filestats
.st_mtime
));
1744 httpSetLength(con
->http
, filestats
.st_size
);
1746 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1748 cupsdCloseClient(con
);
1752 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1757 break; /* Anti-compiler-warning-code */
1763 * Handle any incoming data...
1766 switch (httpGetState(con
->http
))
1768 case HTTP_STATE_PUT_RECV
:
1771 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1773 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1774 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1775 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1776 httpError(con
->http
), strerror(httpError(con
->http
)));
1778 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1779 "HTTP_STATE_PUT_RECV Closing on EOF.");
1781 cupsdCloseClient(con
);
1786 con
->bytes
+= bytes
;
1788 if (write(con
->file
, line
, bytes
) < bytes
)
1790 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1791 "Unable to write %d bytes to \"%s\": %s", bytes
,
1792 con
->filename
, strerror(errno
));
1796 unlink(con
->filename
);
1797 cupsdClearString(&con
->filename
);
1799 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1801 cupsdCloseClient(con
);
1807 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1809 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1812 * End of file, see how big it is...
1815 fstat(con
->file
, &filestats
);
1820 if (filestats
.st_size
> MaxRequestSize
&&
1824 * Request is too big; remove it and send an error...
1827 unlink(con
->filename
);
1828 cupsdClearString(&con
->filename
);
1830 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1832 cupsdCloseClient(con
);
1838 * Install the configuration file...
1841 status
= install_cupsd_conf(con
);
1844 * Return the status to the client...
1847 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1849 cupsdCloseClient(con
);
1855 case HTTP_STATE_POST_RECV
:
1858 if (con
->request
&& con
->file
< 0)
1861 * Grab any request data from the connection...
1864 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1866 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1867 cupsLastErrorString());
1869 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1870 cupsdCloseClient(con
);
1873 else if (ipp_state
!= IPP_STATE_DATA
)
1875 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1877 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1878 cupsdCloseClient(con
);
1882 if (httpGetReady(con
->http
))
1888 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1889 con
->request
->request
.op
.version
[0],
1890 con
->request
->request
.op
.version
[1],
1891 ippOpString(con
->request
->request
.op
.operation_id
),
1892 con
->request
->request
.op
.request_id
);
1893 con
->bytes
+= ippLength(con
->request
);
1897 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1900 * Create a file as needed for the request data...
1903 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1905 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1909 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1910 "Unable to create request file \"%s\": %s",
1911 con
->filename
, strerror(errno
));
1913 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1915 cupsdCloseClient(con
);
1920 fchmod(con
->file
, 0640);
1921 fchown(con
->file
, RunUser
, Group
);
1922 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1925 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1927 if (!httpWait(con
->http
, 0))
1929 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1931 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1932 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1933 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1934 httpError(con
->http
), strerror(httpError(con
->http
)));
1936 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1937 "HTTP_STATE_POST_SEND Closing on EOF.");
1939 cupsdCloseClient(con
);
1944 con
->bytes
+= bytes
;
1946 if (write(con
->file
, line
, bytes
) < bytes
)
1948 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1949 "Unable to write %d bytes to \"%s\": %s",
1950 bytes
, con
->filename
, strerror(errno
));
1954 unlink(con
->filename
);
1955 cupsdClearString(&con
->filename
);
1957 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1960 cupsdCloseClient(con
);
1965 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1967 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1969 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1970 "Closing on unexpected state %s.",
1971 httpStateString(httpGetState(con
->http
)));
1972 cupsdCloseClient(con
);
1977 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1979 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1983 fstat(con
->file
, &filestats
);
1988 if (filestats
.st_size
> MaxRequestSize
&&
1992 * Request is too big; remove it and send an error...
1995 unlink(con
->filename
);
1996 cupsdClearString(&con
->filename
);
2001 * Delete any IPP request data...
2004 ippDelete(con
->request
);
2005 con
->request
= NULL
;
2008 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2010 cupsdCloseClient(con
);
2014 else if (filestats
.st_size
== 0)
2017 * Don't allow empty file...
2020 unlink(con
->filename
);
2021 cupsdClearString(&con
->filename
);
2026 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2028 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2030 cupsdCloseClient(con
);
2035 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2041 cupsdProcessIPPRequest(con
);
2045 unlink(con
->filename
);
2046 cupsdClearString(&con
->filename
);
2055 break; /* Anti-compiler-warning-code */
2058 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2060 if (!httpGetKeepAlive(con
->http
))
2062 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2063 "Closing because Keep-Alive is disabled.");
2064 cupsdCloseClient(con
);
2068 cupsArrayRemove(ActiveClients
, con
);
2069 cupsdSetBusyState();
2076 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2079 int /* O - 1 on success, 0 on failure */
2081 cupsd_client_t
*con
, /* I - Client connection */
2082 char *command
, /* I - Command to run */
2083 char *options
, /* I - Command-line options */
2084 int root
) /* I - Run as root? */
2086 int fd
; /* Standard input file descriptor */
2091 fd
= open(con
->filename
, O_RDONLY
);
2095 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2096 "Unable to open \"%s\" for reading: %s",
2097 con
->filename
? con
->filename
: "/dev/null",
2102 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2107 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2108 con
->pipe_status
= HTTP_STATUS_OK
;
2110 httpClearFields(con
->http
);
2115 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2116 command
, con
->pipe_pid
, con
->file
);
2118 if (con
->pipe_pid
== 0)
2121 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2123 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2125 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2127 con
->sent_header
= 0;
2128 con
->file_ready
= 0;
2129 con
->got_fields
= 0;
2130 con
->header_used
= 0;
2137 * 'cupsdSendError()' - Send an error message via HTTP.
2140 int /* O - 1 if successful, 0 otherwise */
2141 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2142 http_status_t code
, /* I - Error code */
2143 int auth_type
)/* I - Authentication type */
2145 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2150 * Force client to upgrade for authentication if that is how the
2151 * server is configured...
2154 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2155 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2156 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2157 !httpIsEncrypted(con
->http
))
2159 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2161 #endif /* HAVE_SSL */
2164 * Put the request in the access_log file...
2167 cupsdLogRequest(con
, code
);
2170 * To work around bugs in some proxies, don't use Keep-Alive for some
2173 * Kerberos authentication doesn't work without Keep-Alive, so
2174 * never disable it in that case.
2177 httpClearFields(con
->http
);
2179 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2180 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2182 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2183 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2184 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2186 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2189 * Send a human-readable error message.
2192 char message
[4096], /* Message for user */
2193 urltext
[1024], /* URL redirection text */
2194 redirect
[1024]; /* Redirection link */
2195 const char *text
; /* Status-specific text */
2200 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2201 text
= _cupsLangString(con
->language
,
2202 _("Enter your username and password or the "
2203 "root username and password to access this "
2204 "page. If you are using Kerberos authentication, "
2205 "make sure you have a valid Kerberos ticket."));
2206 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2210 snprintf(urltext
, sizeof(urltext
),
2211 _cupsLangString(con
->language
,
2212 _("You must access this page using the URL "
2213 "<A HREF=\"https://%s:%d%s\">"
2214 "https://%s:%d%s</A>.")),
2215 con
->servername
, con
->serverport
, con
->uri
,
2216 con
->servername
, con
->serverport
, con
->uri
);
2218 snprintf(redirect
, sizeof(redirect
),
2219 "<META HTTP-EQUIV=\"Refresh\" "
2220 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2221 con
->servername
, con
->serverport
, con
->uri
);
2223 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2224 text
= _cupsLangString(con
->language
,
2225 _("The web interface is currently disabled. Run "
2226 "\"cupsctl WebInterface=yes\" to enable it."));
2230 snprintf(message
, sizeof(message
),
2231 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2232 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2235 "\t<META HTTP-EQUIV=\"Content-Type\" "
2236 "CONTENT=\"text/html; charset=utf-8\">\n"
2237 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2238 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2239 "HREF=\"/cups.css\">\n"
2247 _httpStatus(con
->language
, code
), redirect
,
2248 _httpStatus(con
->language
, code
), text
);
2251 * Send an error message back to the client. If the error code is a
2252 * 400 or 500 series, make sure the message contains some text, too!
2255 size_t length
= strlen(message
); /* Length of message */
2257 httpSetLength(con
->http
, length
);
2259 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2262 if (httpWrite2(con
->http
, message
, length
) < 0)
2265 if (httpFlushWrite(con
->http
) < 0)
2270 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2272 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2281 * 'cupsdSendHeader()' - Send an HTTP request.
2284 int /* O - 1 on success, 0 on failure */
2286 cupsd_client_t
*con
, /* I - Client to send to */
2287 http_status_t code
, /* I - HTTP status code */
2288 char *type
, /* I - MIME type of document */
2289 int auth_type
) /* I - Type of authentication */
2291 char auth_str
[1024]; /* Authorization string */
2295 * Send the HTTP status header...
2298 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2301 * Treat our special "web interface is disabled" status as "200 OK" for web
2305 code
= HTTP_STATUS_OK
;
2309 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2311 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2312 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2314 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2316 if (auth_type
== CUPSD_AUTH_NONE
)
2318 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2319 auth_type
= cupsdDefaultAuthType();
2321 auth_type
= con
->best
->type
;
2326 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2327 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2328 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2329 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2330 httpGetHostname(con
->http
, NULL
, 0));
2332 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2335 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2336 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2338 # endif /* AF_LOCAL */
2339 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2341 #endif /* HAVE_GSSAPI */
2343 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2344 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2347 * Add a "trc" (try root certification) parameter for local non-Kerberos
2348 * requests when the request requires system group membership - then the
2349 * client knows the root certificate can/should be used.
2351 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2352 * parameter as needed...
2355 char *name
, /* Current user name */
2356 *auth_key
; /* Auth key buffer */
2357 size_t auth_size
; /* Size of remaining buffer */
2359 auth_key
= auth_str
+ strlen(auth_str
);
2360 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2362 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2364 name
= (char *)cupsArrayNext(con
->best
->names
))
2366 #ifdef HAVE_AUTHORIZATION_H
2367 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2369 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2370 /* end parenthesis is stripped in conf.c */
2374 #endif /* HAVE_AUTHORIZATION_H */
2375 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2377 #ifdef HAVE_AUTHORIZATION_H
2378 if (SystemGroupAuthKey
)
2379 snprintf(auth_key
, auth_size
,
2381 SystemGroupAuthKey
);
2384 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2385 #endif /* HAVE_AUTHORIZATION_H */
2393 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2395 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2399 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2400 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2404 if (!strcmp(type
, "text/html"))
2405 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2407 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2410 return (!httpWriteResponse(con
->http
, code
));
2415 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2419 cupsdUpdateCGI(void)
2421 char *ptr
, /* Pointer to end of line in buffer */
2422 message
[1024]; /* Pointer to message text */
2423 int loglevel
; /* Log level for message */
2426 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2427 message
, sizeof(message
))) != NULL
)
2429 if (loglevel
== CUPSD_LOG_INFO
)
2430 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2432 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2436 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2439 * Fatal error on pipe - should never happen!
2442 cupsdLogMessage(CUPSD_LOG_CRIT
,
2443 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2450 * 'cupsdWriteClient()' - Write data to a client as needed.
2454 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2456 int bytes
, /* Number of bytes written */
2457 field_col
; /* Current column */
2458 char *bufptr
, /* Pointer into buffer */
2459 *bufend
; /* Pointer to end of buffer */
2460 ipp_state_t ipp_state
; /* IPP state value */
2463 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2464 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2469 "data_encoding=HTTP_ENCODING_%s, "
2470 "data_remaining=" CUPS_LLFMT
", "
2474 httpError(con
->http
), (int)httpGetReady(con
->http
),
2475 httpStateString(httpGetState(con
->http
)),
2476 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2477 CUPS_LLCAST
httpGetLength2(con
->http
),
2479 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2480 con
->pipe_pid
, con
->file
);
2482 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2483 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2486 * If we get called in the wrong state, then something went wrong with the
2487 * connection and we need to shut it down...
2490 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP write state %s.",
2491 httpStateString(httpGetState(con
->http
)));
2492 cupsdCloseClient(con
);
2499 * Make sure we select on the CGI output...
2502 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2504 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2506 if (!con
->file_ready
)
2509 * Try again later when there is CGI output available...
2512 cupsdRemoveSelect(httpGetFd(con
->http
));
2516 con
->file_ready
= 0;
2519 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2521 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2526 * Write a single attribute or the IPP message header...
2529 ipp_state
= ippWrite(con
->http
, con
->response
);
2532 * If the write buffer has been flushed, stop buffering up attributes...
2535 if (httpGetPending(con
->http
) <= wused
)
2538 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2540 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2541 "Writing IPP response, ipp_state=%s, old "
2542 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2543 ippStateString(ipp_state
),
2544 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2546 if (httpGetPending(con
->http
) > 0)
2547 httpFlushWrite(con
->http
);
2549 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2550 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2552 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2553 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2554 (int)bytes
, httpGetState(con
->http
),
2555 CUPS_LLCAST
httpGetLength2(con
->http
));
2557 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2558 sizeof(con
->header
) - con
->header_used
)) > 0)
2560 con
->header_used
+= bytes
;
2562 if (con
->pipe_pid
&& !con
->got_fields
)
2565 * Inspect the data for Content-Type and other fields.
2568 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2570 !con
->got_fields
&& bufptr
< bufend
;
2573 if (*bufptr
== '\n')
2576 * Send line to client...
2579 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2583 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2585 if (!con
->sent_header
)
2588 * Handle redirection and CGI status codes...
2591 http_field_t field
; /* HTTP field */
2592 char *value
= strchr(con
->header
, ':');
2593 /* Value of field */
2598 while (isspace(*value
& 255))
2602 field
= httpFieldValue(con
->header
);
2604 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2606 httpSetField(con
->http
, field
, value
);
2608 if (field
== HTTP_FIELD_LOCATION
)
2610 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2611 con
->sent_header
= 2;
2614 con
->sent_header
= 1;
2616 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2618 con
->pipe_status
= (http_status_t
)atoi(value
);
2619 con
->sent_header
= 2;
2621 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2623 char *sep
= strchr(value
, ';');
2624 /* Separator between name=value and the rest */
2629 httpSetCookie(con
->http
, value
);
2630 con
->sent_header
= 1;
2638 con
->header_used
-= bufptr
- con
->header
;
2640 if (con
->header_used
> 0)
2641 memmove(con
->header
, bufptr
, con
->header_used
);
2643 bufptr
= con
->header
- 1;
2646 * See if the line was empty...
2651 con
->got_fields
= 1;
2653 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2654 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2655 httpSetLength(con
->http
, 0);
2657 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2659 cupsdCloseClient(con
);
2666 else if (*bufptr
!= '\r')
2670 if (!con
->got_fields
)
2674 if (con
->header_used
> 0)
2676 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2678 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2679 httpError(con
->http
), strerror(httpError(con
->http
)));
2680 cupsdCloseClient(con
);
2684 if (httpIsChunked(con
->http
))
2685 httpFlushWrite(con
->http
);
2687 con
->bytes
+= con
->header_used
;
2689 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2692 bytes
= con
->header_used
;
2694 con
->header_used
= 0;
2699 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2700 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2702 if (!con
->sent_header
&& con
->pipe_pid
)
2703 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2706 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2708 if (httpIsChunked(con
->http
) && (!con
->pipe_pid
|| con
->sent_header
== 1))
2710 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending 0-length chunk.");
2712 if (httpWrite2(con
->http
, "", 0) < 0)
2714 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2715 httpError(con
->http
), strerror(httpError(con
->http
)));
2716 cupsdCloseClient(con
);
2721 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Flushing write buffer.");
2722 httpFlushWrite(con
->http
);
2723 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "New state is %s", httpStateString(httpGetState(con
->http
)));
2726 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2728 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2732 cupsdRemoveSelect(con
->file
);
2735 cupsdEndProcess(con
->pipe_pid
, 0);
2744 unlink(con
->filename
);
2745 cupsdClearString(&con
->filename
);
2750 ippDelete(con
->request
);
2751 con
->request
= NULL
;
2756 ippDelete(con
->response
);
2757 con
->response
= NULL
;
2760 cupsdClearString(&con
->command
);
2761 cupsdClearString(&con
->options
);
2762 cupsdClearString(&con
->query_string
);
2764 if (!httpGetKeepAlive(con
->http
))
2766 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2767 "Closing because Keep-Alive is disabled.");
2768 cupsdCloseClient(con
);
2773 cupsArrayRemove(ActiveClients
, con
);
2774 cupsdSetBusyState();
2781 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2784 static int /* O - 1 if modified since */
2786 cupsd_client_t
*con
, /* I - Client connection */
2787 struct stat
*filestats
) /* I - File information */
2789 const char *ptr
; /* Pointer into field */
2790 time_t date
; /* Time/date value */
2791 off_t size
; /* Size/length value */
2796 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2801 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2802 "check_if_modified "
2803 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2804 filestats
, CUPS_LLCAST filestats
->st_size
,
2805 (int)filestats
->st_mtime
, ptr
);
2807 while (*ptr
!= '\0')
2809 while (isspace(*ptr
) || *ptr
== ';')
2812 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2815 size
= strtoll(ptr
, NULL
, 10);
2817 while (isdigit(*ptr
))
2820 else if (isalpha(*ptr
))
2822 date
= httpGetDateTime(ptr
);
2823 while (*ptr
!= '\0' && *ptr
!= ';')
2830 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2831 (date
< filestats
->st_mtime
&& date
!= 0) ||
2832 (size
== 0 && date
== 0));
2837 * 'compare_clients()' - Compare two client connections.
2840 static int /* O - Result of comparison */
2841 compare_clients(cupsd_client_t
*a
, /* I - First client */
2842 cupsd_client_t
*b
, /* I - Second client */
2843 void *data
) /* I - User data (not used) */
2858 * 'cupsd_start_tls()' - Start encryption on a connection.
2861 static int /* O - 0 on success, -1 on error */
2862 cupsd_start_tls(cupsd_client_t
*con
, /* I - Client connection */
2863 http_encryption_t e
) /* I - Encryption mode */
2865 if (httpEncryption(con
->http
, e
))
2867 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to encrypt connection: %s",
2868 cupsLastErrorString());
2872 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Connection now encrypted.");
2875 #endif /* HAVE_SSL */
2879 * 'get_file()' - Get a filename and state info.
2882 static char * /* O - Real filename */
2883 get_file(cupsd_client_t
*con
, /* I - Client connection */
2884 struct stat
*filestats
, /* O - File information */
2885 char *filename
, /* IO - Filename buffer */
2886 int len
) /* I - Buffer length */
2888 int status
; /* Status of filesystem calls */
2889 char *ptr
; /* Pointer info filename */
2890 int plen
; /* Remaining length after pointer */
2891 char language
[7]; /* Language subdirectory, if any */
2895 * Figure out the real filename...
2900 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2901 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2902 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2904 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
2905 if (access(filename
, F_OK
) < 0)
2906 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2908 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2909 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2910 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2911 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2912 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2914 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2915 strlcpy(filename
, AccessLog
, len
);
2916 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2917 strlcpy(filename
, ErrorLog
, len
);
2918 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2919 strlcpy(filename
, PageLog
, len
);
2923 else if (con
->language
)
2925 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2926 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2929 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2931 if ((ptr
= strchr(filename
, '?')) != NULL
)
2935 * Grab the status for this language; if there isn't a language-specific file
2936 * then fallback to the default one...
2939 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
2940 strncmp(con
->uri
, "/icons/", 7) &&
2941 strncmp(con
->uri
, "/ppd/", 5) &&
2942 strncmp(con
->uri
, "/rss/", 5) &&
2943 strncmp(con
->uri
, "/admin/conf/", 12) &&
2944 strncmp(con
->uri
, "/admin/log/", 11))
2947 * Drop the country code...
2951 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2953 if ((ptr
= strchr(filename
, '?')) != NULL
)
2956 if ((status
= stat(filename
, filestats
)) != 0)
2959 * Drop the language prefix and try the root directory...
2963 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2965 if ((ptr
= strchr(filename
, '?')) != NULL
)
2968 status
= stat(filename
, filestats
);
2973 * If we're found a directory, get the index.html file instead...
2976 if (!status
&& S_ISDIR(filestats
->st_mode
))
2979 * Make sure the URI ends with a slash...
2982 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
2983 strlcat(con
->uri
, "/", sizeof(con
->uri
));
2986 * Find the directory index file, trying every language...
2991 if (status
&& language
[0])
2994 * Try a different language subset...
2998 language
[0] = '\0'; /* Strip country code */
3000 language
[0] = '\0'; /* Strip language */
3004 * Look for the index file...
3007 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3009 if ((ptr
= strchr(filename
, '?')) != NULL
)
3012 ptr
= filename
+ strlen(filename
);
3013 plen
= len
- (ptr
- filename
);
3015 strlcpy(ptr
, "index.html", plen
);
3016 status
= stat(filename
, filestats
);
3021 strlcpy(ptr
, "index.class", plen
);
3022 status
= stat(filename
, filestats
);
3024 #endif /* HAVE_JAVA */
3029 strlcpy(ptr
, "index.pl", plen
);
3030 status
= stat(filename
, filestats
);
3032 #endif /* HAVE_PERL */
3037 strlcpy(ptr
, "index.php", plen
);
3038 status
= stat(filename
, filestats
);
3040 #endif /* HAVE_PHP */
3045 strlcpy(ptr
, "index.pyc", plen
);
3046 status
= stat(filename
, filestats
);
3051 strlcpy(ptr
, "index.py", plen
);
3052 status
= stat(filename
, filestats
);
3054 #endif /* HAVE_PYTHON */
3057 while (status
&& language
[0]);
3060 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3061 "get_file filestats=%p, filename=%p, len=%d, "
3062 "returning \"%s\".", filestats
, filename
, len
,
3063 status
? "(null)" : filename
);
3073 * 'install_cupsd_conf()' - Install a configuration file.
3076 static http_status_t
/* O - Status */
3077 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3079 char filename
[1024]; /* Configuration filename */
3080 cups_file_t
*in
, /* Input file */
3081 *out
; /* Output file */
3082 char buffer
[16384]; /* Copy buffer */
3083 ssize_t bytes
; /* Number of bytes */
3087 * Open the request file...
3090 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3092 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3093 con
->filename
, strerror(errno
));
3094 return (HTTP_STATUS_SERVER_ERROR
);
3098 * Open the new config file...
3101 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3104 return (HTTP_STATUS_SERVER_ERROR
);
3107 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3111 * Copy from the request to the new config file...
3114 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3115 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3117 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3118 "Unable to copy to config file \"%s\": %s",
3119 ConfigurationFile
, strerror(errno
));
3124 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3125 cupsdUnlinkOrRemoveFile(filename
);
3127 return (HTTP_STATUS_SERVER_ERROR
);
3131 * Close the files...
3136 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3137 return (HTTP_STATUS_SERVER_ERROR
);
3140 * Remove the request file...
3143 cupsdUnlinkOrRemoveFile(con
->filename
);
3144 cupsdClearString(&con
->filename
);
3147 * Set the NeedReload flag...
3150 NeedReload
= RELOAD_CUPSD
;
3151 ReloadTime
= time(NULL
);
3154 * Return that the file was created successfully...
3157 return (HTTP_STATUS_CREATED
);
3162 * 'is_cgi()' - Is the resource a CGI script/program?
3165 static int /* O - 1 = CGI, 0 = file */
3166 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3167 const char *filename
, /* I - Real filename */
3168 struct stat
*filestats
, /* I - File information */
3169 mime_type_t
*type
) /* I - MIME type */
3171 const char *options
; /* Options on URL */
3175 * Get the options, if any...
3178 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3181 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3185 * Check for known types...
3188 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3190 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3191 "is_cgi filename=\"%s\", filestats=%p, "
3192 "type=%s/%s, returning 0", filename
,
3193 filestats
, type
? type
->super
: "unknown",
3194 type
? type
->type
: "unknown");
3198 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3199 (filestats
->st_mode
& 0111))
3202 * "application/x-httpd-cgi" is a CGI script.
3205 cupsdSetString(&con
->command
, filename
);
3208 cupsdSetStringf(&con
->options
, " %s", options
);
3210 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3211 "is_cgi filename=\"%s\", filestats=%p, "
3212 "type=%s/%s, returning 1", filename
,
3213 filestats
, type
->super
, type
->type
);
3217 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3220 * "application/x-httpd-java" is a Java servlet.
3223 cupsdSetString(&con
->command
, CUPS_JAVA
);
3226 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3228 cupsdSetStringf(&con
->options
, " %s", filename
);
3230 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3231 "is_cgi filename=\"%s\", filestats=%p, "
3232 "type=%s/%s, returning 1", filename
,
3233 filestats
, type
->super
, type
->type
);
3236 #endif /* HAVE_JAVA */
3238 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3241 * "application/x-httpd-perl" is a Perl page.
3244 cupsdSetString(&con
->command
, CUPS_PERL
);
3247 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3249 cupsdSetStringf(&con
->options
, " %s", filename
);
3251 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3252 "is_cgi filename=\"%s\", filestats=%p, "
3253 "type=%s/%s, returning 1", filename
,
3254 filestats
, type
->super
, type
->type
);
3257 #endif /* HAVE_PERL */
3259 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3262 * "application/x-httpd-php" is a PHP page.
3265 cupsdSetString(&con
->command
, CUPS_PHP
);
3268 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3270 cupsdSetStringf(&con
->options
, " %s", filename
);
3272 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3273 "is_cgi filename=\"%s\", filestats=%p, "
3274 "type=%s/%s, returning 1", filename
,
3275 filestats
, type
->super
, type
->type
);
3278 #endif /* HAVE_PHP */
3280 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3283 * "application/x-httpd-python" is a Python page.
3286 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3289 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3291 cupsdSetStringf(&con
->options
, " %s", filename
);
3293 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3294 "is_cgi filename=\"%s\", filestats=%p, "
3295 "type=%s/%s, returning 1", filename
,
3296 filestats
, type
->super
, type
->type
);
3299 #endif /* HAVE_PYTHON */
3301 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3302 "is_cgi filename=\"%s\", filestats=%p, "
3303 "type=%s/%s, returning 0", filename
,
3304 filestats
, type
->super
, type
->type
);
3310 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3313 static int /* O - 0 if relative, 1 if absolute */
3314 is_path_absolute(const char *path
) /* I - Input path */
3317 * Check for a leading slash...
3324 * Check for "/.." in the path...
3327 while ((path
= strstr(path
, "/..")) != NULL
)
3329 if (!path
[3] || path
[3] == '/')
3336 * If we haven't found any relative paths, return 1 indicating an
3345 * 'pipe_command()' - Pipe the output of a command to the remote client.
3348 static int /* O - Process ID */
3349 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3350 int infile
, /* I - Standard input for command */
3351 int *outfile
, /* O - Standard output for command */
3352 char *command
, /* I - Command to run */
3353 char *options
, /* I - Options for command */
3354 int root
) /* I - Run as root? */
3356 int i
; /* Looping var */
3357 int pid
; /* Process ID */
3358 char *commptr
, /* Command string pointer */
3359 commch
; /* Command string character */
3360 char *uriptr
; /* URI string pointer */
3361 int fds
[2]; /* Pipe FDs */
3362 int argc
; /* Number of arguments */
3363 int envc
; /* Number of environment variables */
3364 char argbuf
[10240], /* Argument buffer */
3365 *argv
[100], /* Argument strings */
3366 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3367 char auth_type
[256], /* AUTH_TYPE environment variable */
3368 content_length
[1024], /* CONTENT_LENGTH environment variable */
3369 content_type
[1024], /* CONTENT_TYPE environment variable */
3370 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3371 http_referer
[1024], /* HTTP_REFERER environment variable */
3372 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3373 lang
[1024], /* LANG environment variable */
3374 path_info
[1024], /* PATH_INFO environment variable */
3375 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3376 remote_host
[1024], /* REMOTE_HOST environment variable */
3377 remote_user
[1024], /* REMOTE_USER environment variable */
3378 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3379 script_name
[1024], /* SCRIPT_NAME environment variable */
3380 server_name
[1024], /* SERVER_NAME environment variable */
3381 server_port
[1024]; /* SERVER_PORT environment variable */
3382 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3386 * Parse a copy of the options string, which is of the form:
3388 * argument+argument+argument
3389 * ?argument+argument+argument
3390 * param=value¶m=value
3391 * ?param=value¶m=value
3392 * /name?argument+argument+argument
3393 * /name?param=value¶m=value
3395 * If the string contains an "=" character after the initial name,
3396 * then we treat it as a HTTP GET form request and make a copy of
3397 * the remaining string for the environment variable.
3399 * The string is always parsed out as command-line arguments, to
3400 * be consistent with Apache...
3403 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3404 "pipe_command infile=%d, outfile=%p, "
3405 "command=\"%s\", options=\"%s\", root=%d",
3406 infile
, outfile
, command
,
3407 options
? options
: "(null)", root
);
3414 if (*commptr
== ' ')
3416 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3421 if (argbuf
[0] == '/')
3424 * Found some trailing path information, set PATH_INFO...
3427 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3428 commptr
= argbuf
+ strlen(argbuf
);
3432 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3438 path_info
[0] = '\0';
3440 if (*commptr
== ' ')
3444 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3447 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3454 argv
[argc
++] = commptr
;
3456 for (; *commptr
&& argc
< 99; commptr
++)
3459 * Break arguments whenever we see a + or space...
3462 if (*commptr
== ' ' || *commptr
== '+')
3464 while (*commptr
== ' ' || *commptr
== '+')
3468 * If we don't have a blank string, save it as another argument...
3473 argv
[argc
] = commptr
;
3479 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3480 isxdigit(commptr
[2] & 255))
3483 * Convert the %xx notation to the individual character.
3486 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3487 *commptr
= (commptr
[1] - '0') << 4;
3489 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3491 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3492 *commptr
|= commptr
[2] - '0';
3494 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3496 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3499 * Check for a %00 and break if that is the case...
3511 * Setup the environment variables as needed...
3514 if (con
->username
[0])
3516 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3517 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3519 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3523 auth_type
[0] = '\0';
3526 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3527 IPP_TAG_LANGUAGE
)) != NULL
)
3529 switch (strlen(attr
->values
[0].string
.text
))
3533 * This is an unknown or badly formatted language code; use
3534 * the POSIX locale...
3537 strlcpy(lang
, "LANG=C", sizeof(lang
));
3542 * Just the language code (ll)...
3545 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3546 attr
->values
[0].string
.text
);
3551 * Language and country code (ll-cc)...
3554 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3555 attr
->values
[0].string
.text
[0],
3556 attr
->values
[0].string
.text
[1],
3557 toupper(attr
->values
[0].string
.text
[3] & 255),
3558 toupper(attr
->values
[0].string
.text
[4] & 255));
3562 else if (con
->language
)
3563 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3565 strlcpy(lang
, "LANG=C", sizeof(lang
));
3567 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3568 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3569 sizeof(remote_addr
) - 12);
3571 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3572 httpGetHostname(con
->http
, NULL
, 0));
3574 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3575 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3578 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3579 DocumentRoot
, script_name
+ 12);
3581 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3583 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3585 char *nameptr
; /* Pointer to ":port" */
3587 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3588 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3589 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3590 *nameptr
= '\0'; /* Strip trailing ":port" */
3593 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3596 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3599 envp
[envc
++] = auth_type
;
3601 envp
[envc
++] = lang
;
3602 envp
[envc
++] = "REDIRECT_STATUS=1";
3603 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3604 envp
[envc
++] = server_name
;
3605 envp
[envc
++] = server_port
;
3606 envp
[envc
++] = remote_addr
;
3607 envp
[envc
++] = remote_host
;
3608 envp
[envc
++] = script_name
;
3609 envp
[envc
++] = script_filename
;
3612 envp
[envc
++] = path_info
;
3614 if (con
->username
[0])
3616 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3618 envp
[envc
++] = remote_user
;
3621 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3622 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3623 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3624 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3626 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3628 if (httpGetCookie(con
->http
))
3630 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3631 httpGetCookie(con
->http
));
3632 envp
[envc
++] = http_cookie
;
3635 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3637 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3638 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3639 envp
[envc
++] = http_user_agent
;
3642 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3644 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3645 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3646 envp
[envc
++] = http_referer
;
3649 if (con
->operation
== HTTP_STATE_GET
)
3651 envp
[envc
++] = "REQUEST_METHOD=GET";
3653 if (con
->query_string
)
3656 * Add GET form variables after ?...
3659 envp
[envc
++] = con
->query_string
;
3662 envp
[envc
++] = "QUERY_STRING=";
3666 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3667 CUPS_LLCAST con
->bytes
);
3668 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3669 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3671 envp
[envc
++] = "REQUEST_METHOD=POST";
3672 envp
[envc
++] = content_length
;
3673 envp
[envc
++] = content_type
;
3677 * Tell the CGI if we are using encryption...
3680 if (httpIsEncrypted(con
->http
))
3681 envp
[envc
++] = "HTTPS=ON";
3684 * Terminate the environment array...
3689 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3691 for (i
= 0; i
< argc
; i
++)
3692 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3693 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3694 for (i
= 0; i
< envc
; i
++)
3695 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3696 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3700 * Create a pipe for the output...
3703 if (cupsdOpenPipe(fds
))
3705 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3706 argv
[0], strerror(errno
));
3711 * Then execute the command...
3714 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3715 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3718 * Error - can't fork!
3721 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3724 cupsdClosePipe(fds
);
3730 * Fork successful - return the PID...
3733 if (con
->username
[0])
3734 cupsdAddCert(pid
, con
->username
, con
->type
);
3736 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3747 * 'valid_host()' - Is the Host: field valid?
3750 static int /* O - 1 if valid, 0 if not */
3751 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3753 cupsd_alias_t
*a
; /* Current alias */
3754 cupsd_netif_t
*netif
; /* Current network interface */
3755 const char *end
; /* End character */
3756 char *ptr
; /* Pointer into host value */
3760 * Copy the Host: header for later use...
3763 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3764 sizeof(con
->clientname
));
3765 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3768 con
->clientport
= atoi(ptr
);
3771 con
->clientport
= con
->serverport
;
3777 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3780 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3781 * addresses when accessing CUPS via the loopback interface...
3784 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3785 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3787 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3788 #endif /* __linux */
3789 !strcmp(con
->clientname
, "127.0.0.1") ||
3790 !strcmp(con
->clientname
, "[::1]"));
3793 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3795 * Check if the hostname is something.local (Bonjour); if so, allow it.
3798 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3802 * "." on end, work back to second-to-last "."...
3805 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3808 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3809 !_cups_strcasecmp(end
, ".local.")))
3811 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3814 * Check if the hostname is an IP address...
3817 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3820 * Possible IPv4/IPv6 address...
3823 http_addrlist_t
*addrlist
; /* List of addresses */
3826 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3829 * Good IPv4/IPv6 address...
3832 httpAddrFreeList(addrlist
);
3838 * Check for (alias) name matches...
3841 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3843 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3846 * "ServerAlias *" allows all host values through...
3849 if (!strcmp(a
->name
, "*"))
3852 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3855 * Prefix matches; check the character at the end - it must be "." or nul.
3858 end
= con
->clientname
+ a
->namelen
;
3860 if (!*end
|| (*end
== '.' && !end
[1]))
3865 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3866 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3868 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3871 * "ServerAlias *" allows all host values through...
3874 if (!strcmp(a
->name
, "*"))
3877 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3880 * Prefix matches; check the character at the end - it must be "." or nul.
3883 end
= con
->clientname
+ a
->namelen
;
3885 if (!*end
|| (*end
== '.' && !end
[1]))
3889 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3892 * Check for interface hostname matches...
3895 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3897 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3899 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3902 * Prefix matches; check the character at the end - it must be "." or nul.
3905 end
= con
->clientname
+ netif
->hostlen
;
3907 if (!*end
|| (*end
== '.' && !end
[1]))
3917 * 'write_file()' - Send a file via HTTP.
3920 static int /* O - 0 on failure, 1 on success */
3921 write_file(cupsd_client_t
*con
, /* I - Client connection */
3922 http_status_t code
, /* I - HTTP status */
3923 char *filename
, /* I - Filename */
3924 char *type
, /* I - File type */
3925 struct stat
*filestats
) /* O - File information */
3927 con
->file
= open(filename
, O_RDONLY
);
3929 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3930 "write_file code=%d, filename=\"%s\" (%d), "
3931 "type=\"%s\", filestats=%p",
3932 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3937 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3940 con
->sent_header
= 1;
3942 httpClearFields(con
->http
);
3944 httpSetLength(con
->http
, filestats
->st_size
);
3946 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3947 httpGetDateString(filestats
->st_mtime
));
3949 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3952 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3954 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3961 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3965 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3967 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
3970 con
->file_ready
= 1;
3972 cupsdRemoveSelect(con
->file
);
3973 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3975 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");