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 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and
30 * cupsdWriteClient() - Write data to a client as needed.
31 * check_if_modified() - Decode an "If-Modified-Since" line.
32 * compare_clients() - Compare two client connections.
33 * data_ready() - Check whether data is available from a client.
34 * get_file() - Get a filename and state info.
35 * install_cupsd_conf() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements
39 * pipe_command() - Pipe the output of a command to the remote
41 * valid_host() - Is the Host: field valid?
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
54 #endif /* __APPLE__ */
57 #endif /* HAVE_TCPD_H */
64 static const char * const http_states
[] =
65 { /* HTTP state strings */
70 "HTTP_STATE_GET_SEND",
73 "HTTP_STATE_POST_RECV",
74 "HTTP_STATE_POST_SEND",
76 "HTTP_STATE_PUT_RECV",
81 "HTTP_STATE_UNKNOWN_METHOD",
82 "HTTP_STATE_UNKNOWN_VERSION"
84 static const char * const ipp_states
[] =
85 { /* IPP state strings */
97 static int check_if_modified(cupsd_client_t
*con
,
98 struct stat
*filestats
);
99 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
101 static int data_ready(cupsd_client_t
*con
);
102 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
103 char *filename
, int len
);
104 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
105 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
106 struct stat
*filestats
, mime_type_t
*type
);
107 static int is_path_absolute(const char *path
);
108 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
109 char *command
, char *options
, int root
);
110 static int valid_host(cupsd_client_t
*con
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
135 struct request_info wrap_req
; /* TCP wrappers request information */
136 #endif /* HAVE_TCPD_H */
139 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
140 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
141 lis
, lis
->fd
, cupsArrayCount(Clients
));
144 * Make sure we don't have a full set of clients already...
147 if (cupsArrayCount(Clients
) == MaxClients
)
151 * Get a pointer to the next available client...
155 Clients
= cupsArrayNew(NULL
, NULL
);
159 cupsdLogMessage(CUPSD_LOG_ERROR
,
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
166 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
170 cupsdLogMessage(CUPSD_LOG_ERROR
,
171 "Unable to allocate memory for active clients array!");
172 cupsdPauseListening();
176 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
178 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
179 cupsdPauseListening();
184 con
->http
.activity
= time(NULL
);
185 con
->http
.hostaddr
= &(con
->clientaddr
);
186 con
->http
.wait_value
= 10000;
187 con
->http
.mode
= _HTTP_MODE_SERVER
;
190 * Accept the client and get the remote address...
193 addrlen
= sizeof(http_addr_t
);
195 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
198 if (errno
== ENFILE
|| errno
== EMFILE
)
199 cupsdPauseListening();
201 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
209 * Save the connected port number...
212 _httpAddrSetPort(con
->http
.hostaddr
, httpAddrPort(&(lis
->address
)));
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
220 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
222 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
223 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
224 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
225 #endif /* AF_INET6 */
228 * Check the number of clients on the same address...
231 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
233 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
234 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
237 if (count
>= MaxClientsPerHost
)
241 if (count
>= MaxClientsPerHost
)
243 if ((time(NULL
) - last_dos
) >= 60)
245 last_dos
= time(NULL
);
246 cupsdLogMessage(CUPSD_LOG_WARN
,
247 "Possible DoS attack - more than %d clients connecting "
250 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
251 sizeof(con
->http
.hostname
)));
255 closesocket(con
->http
.fd
);
265 * Get the hostname or format the IP address as needed...
268 if (httpAddrLocalhost(con
->http
.hostaddr
))
271 * Map accesses from the loopback interface to "localhost"...
274 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
275 hostname
= con
->http
.hostname
;
280 * Map accesses from the same host to the server name.
284 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
285 sizeof(con
->http
.hostname
));
289 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
290 sizeof(con
->http
.hostname
));
294 if (hostname
== NULL
&& HostNameLookups
== 2)
297 * Can't have an unresolved IP address with double-lookups enabled...
301 closesocket(con
->http
.fd
);
306 cupsdLogMessage(CUPSD_LOG_WARN
,
307 "Name lookup failed - connection from %s closed!",
314 if (HostNameLookups
== 2)
317 * Do double lookups as needed...
320 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
324 * See if the hostname maps to the same IP address...
327 for (addr
= addrlist
; addr
; addr
= addr
->next
)
328 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
334 httpAddrFreeList(addrlist
);
339 * Can't have a hostname that doesn't resolve to the same IP address
340 * with double-lookups enabled...
344 closesocket(con
->http
.fd
);
349 cupsdLogMessage(CUPSD_LOG_WARN
,
350 "IP lookup failed - connection from %s closed!",
359 * See if the connection is denied by TCP wrappers...
362 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
365 if (!hosts_access(&wrap_req
))
368 closesocket(con
->http
.fd
);
373 cupsdLogMessage(CUPSD_LOG_WARN
,
374 "Connection from %s refused by /etc/hosts.allow and "
375 "/etc/hosts.deny rules.", con
->http
.hostname
);
379 #endif /* HAVE_TCPD_H */
382 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
385 socklen_t peersize
; /* Size of peer credentials */
386 pid_t peerpid
; /* Peer process ID */
387 char name
[256]; /* Name of process */
389 peersize
= sizeof(peerpid
);
390 if (!getsockopt(con
->http
.fd
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
393 if (!proc_name(peerpid
, name
, sizeof(name
)))
394 cupsdLogMessage(CUPSD_LOG_DEBUG
,
395 "[Client %d] Accepted from %s (Domain ???[%d])",
396 con
->http
.fd
, con
->http
.hostname
, (int)peerpid
);
398 cupsdLogMessage(CUPSD_LOG_DEBUG
,
399 "[Client %d] Accepted from %s (Domain %s[%d])",
400 con
->http
.fd
, con
->http
.hostname
, name
, (int)peerpid
);
403 # endif /* __APPLE__ */
405 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
406 con
->http
.fd
, con
->http
.hostname
);
409 #endif /* AF_LOCAL */
410 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
411 con
->http
.fd
, con
->http
.hostname
,
412 httpAddrPort(con
->http
.hostaddr
),
413 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
416 * Get the local address the client connected to...
419 addrlen
= sizeof(temp
);
420 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
422 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
425 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
426 con
->serverport
= LocalPort
;
429 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
431 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
432 con
->serverport
= LocalPort
;
434 #endif /* AF_LOCAL */
437 if (httpAddrLocalhost(&temp
))
438 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
439 else if (HostNameLookups
)
440 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
442 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
444 con
->serverport
= httpAddrPort(&(lis
->address
));
448 * Add the connection to the array of active clients...
451 cupsArrayAdd(Clients
, con
);
454 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
455 * loopback interface. Since we write large buffers when sending print files
456 * and requests there shouldn't be any performance penalty for this...
460 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
463 * Close this file on all execs...
466 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
469 * Add the socket to the server select.
472 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
475 * Temporarily suspend accept()'s until we lose a client...
478 if (cupsArrayCount(Clients
) == MaxClients
)
479 cupsdPauseListening();
483 * See if we are connecting on a secure port...
486 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
489 * https connection; go secure...
492 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
494 if (!cupsdStartTLS(con
))
495 cupsdCloseClient(con
);
499 #endif /* HAVE_SSL */
504 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
508 cupsdCloseAllClients(void)
510 cupsd_client_t
*con
; /* Current client */
513 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
514 cupsArrayCount(Clients
));
516 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
518 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
519 if (cupsdCloseClient(con
))
520 cupsdCloseClient(con
);
525 * 'cupsdCloseClient()' - Close a remote client.
528 int /* O - 1 if partial close, 0 if fully closed */
529 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
531 int partial
; /* Do partial close for SSL? */
533 #elif defined(HAVE_GNUTLS)
534 # elif defined(HAVE_CDSASSL)
535 #endif /* HAVE_LIBSSL */
538 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
542 * Flush pending writes before closing...
545 httpFlushWrite(HTTP(con
));
551 * Shutdown encryption as needed...
560 #endif /* HAVE_SSL */
562 if (con
->pipe_pid
!= 0)
565 * Stop any CGI process...
568 cupsdEndProcess(con
->pipe_pid
, 1);
574 cupsdRemoveSelect(con
->file
);
581 * Close the socket and clear the file from the input set for select()...
584 if (con
->http
.fd
>= 0)
586 cupsArrayRemove(ActiveClients
, con
);
592 * Only do a partial close so that the encrypted client gets everything.
595 shutdown(con
->http
.fd
, 0);
596 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
601 * Shut the socket down fully...
604 cupsdRemoveSelect(con
->http
.fd
);
616 if (con
->http
.input_set
)
617 free(con
->http
.input_set
);
619 httpClearCookie(HTTP(con
));
620 httpClearFields(HTTP(con
));
622 cupsdClearString(&con
->filename
);
623 cupsdClearString(&con
->command
);
624 cupsdClearString(&con
->options
);
625 cupsdClearString(&con
->query_string
);
629 ippDelete(con
->request
);
635 ippDelete(con
->response
);
636 con
->response
= NULL
;
641 cupsLangFree(con
->language
);
642 con
->language
= NULL
;
645 #ifdef HAVE_AUTHORIZATION_H
648 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
651 #endif /* HAVE_AUTHORIZATION_H */
654 * Re-enable new client connections if we are going back under the
658 if (cupsArrayCount(Clients
) == MaxClients
)
659 cupsdResumeListening();
662 * Compact the list of clients as necessary...
665 cupsArrayRemove(Clients
, con
);
675 * 'cupsdFlushHeader()' - Flush the header fields to the client.
678 int /* I - Bytes written or -1 on error */
679 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
681 int bytes
= httpFlushWrite(HTTP(con
));
683 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
690 * 'cupsdReadClient()' - Read data from a client.
694 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
696 char line
[32768], /* Line from client... */
697 operation
[64], /* Operation code from socket */
698 version
[64], /* HTTP version number string */
699 locale
[64], /* Locale */
700 *ptr
; /* Pointer into strings */
701 int major
, minor
; /* HTTP version numbers */
702 http_status_t status
; /* Transfer status */
703 ipp_state_t ipp_state
; /* State of IPP transfer */
704 int bytes
; /* Number of bytes to POST */
705 char *filename
; /* Name of file for GET/HEAD */
706 char buf
[1024]; /* Buffer for real filename */
707 struct stat filestats
; /* File information */
708 mime_type_t
*type
; /* MIME type of file */
709 cupsd_printer_t
*p
; /* Printer */
710 static unsigned request_id
= 0; /* Request ID for temp files */
713 status
= HTTP_CONTINUE
;
715 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
716 "[Client %d] cupsdReadClient "
720 "data_encoding=HTTP_ENCODING_%s, "
721 "data_remaining=" CUPS_LLFMT
", "
724 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
725 http_states
[con
->http
.state
+ 1],
726 con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
?
727 "CHUNKED" : "LENGTH",
728 CUPS_LLCAST con
->http
.data_remaining
,
730 con
->request
? ipp_states
[con
->request
->state
] : "",
737 * Automatically check for a SSL/TLS handshake...
742 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
743 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
746 * Encrypt this connection...
749 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
750 "[Client %d] Saw first byte %02X, auto-negotiating "
751 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
753 if (!cupsdStartTLS(con
))
754 cupsdCloseClient(con
);
759 #endif /* HAVE_SSL */
761 switch (con
->http
.state
)
763 case HTTP_STATE_WAITING
:
765 * See if we've received a request line...
768 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
770 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
771 cupsdLogMessage(CUPSD_LOG_DEBUG
,
772 "[Client %d] HTTP_STATE_WAITING Closing for error %d "
773 "(%s)", con
->http
.fd
, con
->http
.error
,
774 strerror(con
->http
.error
));
776 cupsdLogMessage(CUPSD_LOG_DEBUG
,
777 "[Client %d] HTTP_STATE_WAITING Closing on EOF",
780 cupsdCloseClient(con
);
785 * Ignore blank request lines...
792 * Clear other state variables...
795 httpClearFields(HTTP(con
));
797 con
->http
.activity
= time(NULL
);
798 con
->http
.version
= HTTP_1_0
;
799 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
800 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
801 con
->http
.data_remaining
= 0;
802 con
->http
._data_remaining
= 0;
803 con
->operation
= HTTP_STATE_WAITING
;
808 con
->username
[0] = '\0';
809 con
->password
[0] = '\0';
812 cupsdClearString(&con
->command
);
813 cupsdClearString(&con
->options
);
814 cupsdClearString(&con
->query_string
);
818 ippDelete(con
->request
);
824 ippDelete(con
->response
);
825 con
->response
= NULL
;
830 cupsLangFree(con
->language
);
831 con
->language
= NULL
;
837 #endif /* HAVE_GSSAPI */
840 * Grab the request line...
843 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
848 cupsdLogMessage(CUPSD_LOG_ERROR
,
849 "[Client %d] Bad request line \"%s\" from %s.",
851 _httpEncodeURI(buf
, line
, sizeof(buf
)),
853 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
854 cupsdCloseClient(con
);
858 con
->http
.version
= HTTP_0_9
;
861 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
863 cupsdLogMessage(CUPSD_LOG_ERROR
,
864 "[Client %d] Bad request line \"%s\" from %s.",
866 _httpEncodeURI(buf
, line
, sizeof(buf
)),
868 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
869 cupsdCloseClient(con
);
875 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
876 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
877 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
879 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
883 cupsdLogMessage(CUPSD_LOG_ERROR
,
884 "[Client %d] Unsupported request line \"%s\" "
885 "from %s.", con
->http
.fd
,
886 _httpEncodeURI(buf
, line
, sizeof(buf
)),
888 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
889 cupsdCloseClient(con
);
896 * Handle full URLs in the request line...
899 if (strcmp(con
->uri
, "*"))
901 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
902 userpass
[HTTP_MAX_URI
], /* Username:password */
903 hostname
[HTTP_MAX_URI
], /* Hostname */
904 resource
[HTTP_MAX_URI
]; /* Resource path */
905 int port
; /* Port number */
909 * Separate the URI into its components...
912 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
913 scheme
, sizeof(scheme
),
914 userpass
, sizeof(userpass
),
915 hostname
, sizeof(hostname
), &port
,
916 resource
, sizeof(resource
));
919 * Only allow URIs with the servername, localhost, or an IP
923 if (strcmp(scheme
, "file") &&
924 _cups_strcasecmp(hostname
, ServerName
) &&
925 _cups_strcasecmp(hostname
, "localhost") &&
926 !isdigit(hostname
[0]) && hostname
[0] != '[')
929 * Nope, we don't do proxies...
932 cupsdLogMessage(CUPSD_LOG_ERROR
,
933 "[Client %d] Bad URI \"%s\" in request.",
934 con
->http
.fd
, con
->uri
);
935 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
936 cupsdCloseClient(con
);
941 * Copy the resource portion back into the URI; both resource and
942 * con->uri are HTTP_MAX_URI bytes in size...
945 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
949 * Process the request...
952 if (!strcmp(operation
, "GET"))
953 con
->http
.state
= HTTP_STATE_GET
;
954 else if (!strcmp(operation
, "PUT"))
955 con
->http
.state
= HTTP_STATE_PUT
;
956 else if (!strcmp(operation
, "POST"))
957 con
->http
.state
= HTTP_STATE_POST
;
958 else if (!strcmp(operation
, "DELETE"))
959 con
->http
.state
= HTTP_STATE_DELETE
;
960 else if (!strcmp(operation
, "TRACE"))
961 con
->http
.state
= HTTP_STATE_TRACE
;
962 else if (!strcmp(operation
, "OPTIONS"))
963 con
->http
.state
= HTTP_STATE_OPTIONS
;
964 else if (!strcmp(operation
, "HEAD"))
965 con
->http
.state
= HTTP_STATE_HEAD
;
968 cupsdLogMessage(CUPSD_LOG_ERROR
,
969 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
971 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
972 cupsdCloseClient(con
);
976 gettimeofday(&(con
->start
), NULL
);
977 con
->operation
= con
->http
.state
;
979 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
980 con
->http
.fd
, operation
, con
->uri
,
981 con
->http
.version
/ 100, con
->http
.version
% 100);
983 con
->http
.status
= HTTP_OK
;
985 if (!cupsArrayFind(ActiveClients
, con
))
987 cupsArrayAdd(ActiveClients
, con
);
991 case HTTP_STATE_OPTIONS
:
992 case HTTP_STATE_DELETE
:
993 case HTTP_STATE_GET
:
994 case HTTP_STATE_HEAD
:
995 case HTTP_STATE_POST
:
996 case HTTP_STATE_PUT
:
997 case HTTP_STATE_TRACE
:
999 * Parse incoming parameters until the status changes...
1002 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1003 if (!data_ready(con
))
1006 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1008 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1009 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1010 "[Client %d] Closing for error %d (%s) while "
1012 con
->http
.fd
, con
->http
.error
,
1013 strerror(con
->http
.error
));
1015 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1016 "[Client %d] Closing on EOF while reading headers.",
1019 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1020 cupsdCloseClient(con
);
1026 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1029 * Connection closed...
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1033 "[Client %d] Closing on EOF", con
->http
.fd
);
1034 cupsdCloseClient(con
);
1037 break; /* Anti-compiler-warning-code */
1041 * Handle new transfers...
1044 if (status
== HTTP_OK
)
1046 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1049 * Figure out the locale from the Accept-Language and Content-Type
1053 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1057 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1061 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1062 "charset=")) != NULL
)
1065 * Combine language and charset, and trim any extra params in the
1069 snprintf(locale
, sizeof(locale
), "%s.%s",
1070 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1072 if ((ptr
= strchr(locale
, ',')) != NULL
)
1076 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1077 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1079 con
->language
= cupsLangGet(locale
);
1082 con
->language
= cupsLangGet(DefaultLocale
);
1084 cupsdAuthorize(con
);
1086 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1087 "Keep-Alive", 10) && KeepAlive
)
1088 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1089 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1091 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1093 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1094 con
->http
.version
>= HTTP_1_1
)
1097 * HTTP/1.1 and higher require the "Host:" field...
1100 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1102 cupsdLogMessage(CUPSD_LOG_ERROR
,
1103 "[Client %d] Missing Host: field in request.",
1105 cupsdCloseClient(con
);
1109 else if (!valid_host(con
))
1112 * Access to localhost must use "localhost" or the corresponding IPv4
1113 * or IPv6 values in the Host: field.
1116 cupsdLogMessage(CUPSD_LOG_ERROR
,
1117 "[Client %d] Request from \"%s\" using invalid Host: "
1118 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1119 con
->http
.fields
[HTTP_FIELD_HOST
]);
1121 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1123 cupsdCloseClient(con
);
1127 else if (con
->operation
== HTTP_STATE_OPTIONS
)
1130 * Do OPTIONS command...
1133 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1135 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1137 cupsdCloseClient(con
);
1142 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1143 con
->http
.tls
== NULL
)
1147 * Do encryption stuff...
1150 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1152 cupsdCloseClient(con
);
1156 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1157 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1158 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1159 httpPrintf(HTTP(con
), "\r\n");
1161 if (cupsdFlushHeader(con
) < 0)
1163 cupsdCloseClient(con
);
1167 if (!cupsdStartTLS(con
))
1169 cupsdCloseClient(con
);
1173 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1175 cupsdCloseClient(con
);
1178 #endif /* HAVE_SSL */
1181 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1183 cupsdCloseClient(con
);
1187 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1188 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1189 httpPrintf(HTTP(con
), "\r\n");
1191 if (cupsdFlushHeader(con
) < 0)
1193 cupsdCloseClient(con
);
1197 else if (!is_path_absolute(con
->uri
))
1200 * Protect against malicious users!
1203 cupsdLogMessage(CUPSD_LOG_ERROR
,
1204 "[Client %d] Request for non-absolute resource \"%s\".",
1205 con
->http
.fd
, con
->uri
);
1207 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1209 cupsdCloseClient(con
);
1215 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1216 "Upgrade") && con
->http
.tls
== NULL
)
1220 * Do encryption stuff...
1223 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1226 cupsdCloseClient(con
);
1230 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1231 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1232 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1233 httpPrintf(HTTP(con
), "\r\n");
1235 if (cupsdFlushHeader(con
) < 0)
1237 cupsdCloseClient(con
);
1241 if (!cupsdStartTLS(con
))
1243 cupsdCloseClient(con
);
1247 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1249 cupsdCloseClient(con
);
1252 #endif /* HAVE_SSL */
1255 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1257 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1258 cupsdCloseClient(con
);
1262 if (con
->http
.expect
&&
1263 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1265 if (con
->http
.expect
== HTTP_CONTINUE
)
1268 * Send 100-continue header...
1271 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1273 cupsdCloseClient(con
);
1280 * Send 417-expectation-failed header...
1283 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1286 cupsdCloseClient(con
);
1290 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1291 httpPrintf(HTTP(con
), "\r\n");
1293 if (cupsdFlushHeader(con
) < 0)
1295 cupsdCloseClient(con
);
1301 switch (con
->http
.state
)
1303 case HTTP_STATE_GET_SEND
:
1304 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1305 !strncmp(con
->uri
, "/printers/", 10) ||
1306 !strncmp(con
->uri
, "/classes/", 9)) &&
1307 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1310 * Send PPD file - get the real printer name since printer
1311 * names are not case sensitive but filenames can be...
1314 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1316 if (!strncmp(con
->uri
, "/ppd/", 5))
1317 p
= cupsdFindPrinter(con
->uri
+ 5);
1318 else if (!strncmp(con
->uri
, "/printers/", 10))
1319 p
= cupsdFindPrinter(con
->uri
+ 10);
1322 p
= cupsdFindClass(con
->uri
+ 9);
1326 int i
; /* Looping var */
1328 for (i
= 0; i
< p
->num_printers
; i
++)
1330 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1332 char ppdname
[1024];/* PPD filename */
1334 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1335 ServerRoot
, p
->printers
[i
]->name
);
1336 if (!access(ppdname
, 0))
1344 if (i
>= p
->num_printers
)
1351 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1355 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1357 cupsdCloseClient(con
);
1364 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1365 !strncmp(con
->uri
, "/printers/", 10) ||
1366 !strncmp(con
->uri
, "/classes/", 9)) &&
1367 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1370 * Send icon file - get the real queue name since queue names are
1371 * not case sensitive but filenames can be...
1374 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1376 if (!strncmp(con
->uri
, "/icons/", 7))
1377 p
= cupsdFindPrinter(con
->uri
+ 7);
1378 else if (!strncmp(con
->uri
, "/printers/", 10))
1379 p
= cupsdFindPrinter(con
->uri
+ 10);
1382 p
= cupsdFindClass(con
->uri
+ 9);
1386 int i
; /* Looping var */
1388 for (i
= 0; i
< p
->num_printers
; i
++)
1390 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1392 char ppdname
[1024];/* PPD filename */
1394 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1395 ServerRoot
, p
->printers
[i
]->name
);
1396 if (!access(ppdname
, 0))
1404 if (i
>= p
->num_printers
)
1410 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1413 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1415 cupsdCloseClient(con
);
1422 else if (!WebInterface
)
1425 * Web interface is disabled. Show an appropriate message...
1428 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1430 cupsdCloseClient(con
);
1437 if ((!strncmp(con
->uri
, "/admin", 6) &&
1438 strncmp(con
->uri
, "/admin/conf/", 12) &&
1439 strncmp(con
->uri
, "/admin/log/", 11)) ||
1440 !strncmp(con
->uri
, "/printers", 9) ||
1441 !strncmp(con
->uri
, "/classes", 8) ||
1442 !strncmp(con
->uri
, "/help", 5) ||
1443 !strncmp(con
->uri
, "/jobs", 5))
1446 * Send CGI output...
1449 if (!strncmp(con
->uri
, "/admin", 6))
1451 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1454 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1456 else if (!strncmp(con
->uri
, "/printers", 9))
1458 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1461 if (con
->uri
[9] && con
->uri
[10])
1462 cupsdSetString(&con
->options
, con
->uri
+ 9);
1464 cupsdSetString(&con
->options
, NULL
);
1466 else if (!strncmp(con
->uri
, "/classes", 8))
1468 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1471 if (con
->uri
[8] && con
->uri
[9])
1472 cupsdSetString(&con
->options
, con
->uri
+ 8);
1474 cupsdSetString(&con
->options
, NULL
);
1476 else if (!strncmp(con
->uri
, "/jobs", 5))
1478 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1481 if (con
->uri
[5] && con
->uri
[6])
1482 cupsdSetString(&con
->options
, con
->uri
+ 5);
1484 cupsdSetString(&con
->options
, NULL
);
1488 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1491 if (con
->uri
[5] && con
->uri
[6])
1492 cupsdSetString(&con
->options
, con
->uri
+ 5);
1494 cupsdSetString(&con
->options
, NULL
);
1497 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1499 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1501 cupsdCloseClient(con
);
1506 cupsdLogRequest(con
, HTTP_OK
);
1508 if (con
->http
.version
<= HTTP_1_0
)
1509 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1511 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1512 (strchr(con
->uri
+ 12, '/') ||
1513 strlen(con
->uri
) == 12)) ||
1514 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1515 (strchr(con
->uri
+ 11, '/') ||
1516 strlen(con
->uri
) == 11)))
1519 * GET can only be done to configuration files directly under
1523 cupsdLogMessage(CUPSD_LOG_ERROR
,
1524 "Request for subdirectory \"%s\"!", con
->uri
);
1526 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1528 cupsdCloseClient(con
);
1540 if ((filename
= get_file(con
, &filestats
, buf
,
1541 sizeof(buf
))) == NULL
)
1543 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1545 cupsdCloseClient(con
);
1552 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1554 if (is_cgi(con
, filename
, &filestats
, type
))
1557 * Note: con->command and con->options were set by
1561 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1563 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1565 cupsdCloseClient(con
);
1570 cupsdLogRequest(con
, HTTP_OK
);
1572 if (con
->http
.version
<= HTTP_1_0
)
1573 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1577 if (!check_if_modified(con
, &filestats
))
1579 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1581 cupsdCloseClient(con
);
1588 strlcpy(line
, "text/plain", sizeof(line
));
1590 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1592 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1594 cupsdCloseClient(con
);
1601 case HTTP_STATE_POST_RECV
:
1603 * See if the POST request includes a Content-Length field, and if
1604 * so check the length against any limits that are set...
1607 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1608 MaxRequestSize
> 0 &&
1609 con
->http
.data_remaining
> MaxRequestSize
)
1612 * Request too large...
1615 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1617 cupsdCloseClient(con
);
1623 else if (con
->http
.data_remaining
< 0 ||
1624 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1625 con
->http
.data_encoding
== HTTP_ENCODING_LENGTH
))
1628 * Negative content lengths are invalid!
1631 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1633 cupsdCloseClient(con
);
1641 * See what kind of POST request this is; for IPP requests the
1642 * content-type field will be "application/ipp"...
1645 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1647 con
->request
= ippNew();
1648 else if (!WebInterface
)
1651 * Web interface is disabled. Show an appropriate message...
1654 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1656 cupsdCloseClient(con
);
1662 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1663 strncmp(con
->uri
, "/admin/conf/", 12) &&
1664 strncmp(con
->uri
, "/admin/log/", 11)) ||
1665 !strncmp(con
->uri
, "/printers", 9) ||
1666 !strncmp(con
->uri
, "/classes", 8) ||
1667 !strncmp(con
->uri
, "/help", 5) ||
1668 !strncmp(con
->uri
, "/jobs", 5))
1674 if (!strncmp(con
->uri
, "/admin", 6))
1676 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1679 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1681 else if (!strncmp(con
->uri
, "/printers", 9))
1683 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1686 if (con
->uri
[9] && con
->uri
[10])
1687 cupsdSetString(&con
->options
, con
->uri
+ 9);
1689 cupsdSetString(&con
->options
, NULL
);
1691 else if (!strncmp(con
->uri
, "/classes", 8))
1693 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1696 if (con
->uri
[8] && con
->uri
[9])
1697 cupsdSetString(&con
->options
, con
->uri
+ 8);
1699 cupsdSetString(&con
->options
, NULL
);
1701 else if (!strncmp(con
->uri
, "/jobs", 5))
1703 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1706 if (con
->uri
[5] && con
->uri
[6])
1707 cupsdSetString(&con
->options
, con
->uri
+ 5);
1709 cupsdSetString(&con
->options
, NULL
);
1713 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1716 if (con
->uri
[5] && con
->uri
[6])
1717 cupsdSetString(&con
->options
, con
->uri
+ 5);
1719 cupsdSetString(&con
->options
, NULL
);
1722 if (con
->http
.version
<= HTTP_1_0
)
1723 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1731 if ((filename
= get_file(con
, &filestats
, buf
,
1732 sizeof(buf
))) == NULL
)
1734 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1736 cupsdCloseClient(con
);
1743 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1745 if (!is_cgi(con
, filename
, &filestats
, type
))
1748 * Only POST to CGI's...
1751 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1753 cupsdCloseClient(con
);
1760 case HTTP_STATE_PUT_RECV
:
1762 * Validate the resource name...
1765 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1768 * PUT can only be done to the cupsd.conf file...
1771 cupsdLogMessage(CUPSD_LOG_ERROR
,
1772 "[Client %d] Disallowed PUT request for \"%s\".",
1773 con
->http
.fd
, con
->uri
);
1775 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1777 cupsdCloseClient(con
);
1785 * See if the PUT request includes a Content-Length field, and if
1786 * so check the length against any limits that are set...
1789 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1790 MaxRequestSize
> 0 &&
1791 con
->http
.data_remaining
> MaxRequestSize
)
1794 * Request too large...
1797 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1799 cupsdCloseClient(con
);
1805 else if (con
->http
.data_remaining
< 0)
1808 * Negative content lengths are invalid!
1811 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1813 cupsdCloseClient(con
);
1821 * Open a temporary file to hold the request...
1824 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1826 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1830 cupsdLogMessage(CUPSD_LOG_ERROR
,
1831 "[Client %d] Unable to create request file "
1832 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1835 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1837 cupsdCloseClient(con
);
1842 fchmod(con
->file
, 0640);
1843 fchown(con
->file
, RunUser
, Group
);
1844 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1847 case HTTP_STATE_DELETE
:
1848 case HTTP_STATE_TRACE
:
1849 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1850 cupsdCloseClient(con
);
1853 case HTTP_STATE_HEAD
:
1854 if (!strncmp(con
->uri
, "/printers/", 10) &&
1855 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1858 * Send PPD file - get the real printer name since printer
1859 * names are not case sensitive but filenames can be...
1862 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1864 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1865 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1868 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1870 cupsdCloseClient(con
);
1877 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1878 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1881 * Send PNG file - get the real printer name since printer
1882 * names are not case sensitive but filenames can be...
1885 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1887 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1888 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1891 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1893 cupsdCloseClient(con
);
1900 else if (!WebInterface
)
1902 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1904 cupsdCloseClient(con
);
1908 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1910 cupsdCloseClient(con
);
1914 if (cupsdFlushHeader(con
) < 0)
1916 cupsdCloseClient(con
);
1920 con
->http
.state
= HTTP_STATE_WAITING
;
1921 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1926 if ((!strncmp(con
->uri
, "/admin", 6) &&
1927 strncmp(con
->uri
, "/admin/conf/", 12) &&
1928 strncmp(con
->uri
, "/admin/log/", 11)) ||
1929 !strncmp(con
->uri
, "/printers", 9) ||
1930 !strncmp(con
->uri
, "/classes", 8) ||
1931 !strncmp(con
->uri
, "/help", 5) ||
1932 !strncmp(con
->uri
, "/jobs", 5))
1938 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1940 cupsdCloseClient(con
);
1944 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1946 cupsdCloseClient(con
);
1950 if (cupsdFlushHeader(con
) < 0)
1952 cupsdCloseClient(con
);
1956 cupsdLogRequest(con
, HTTP_OK
);
1958 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1959 (strchr(con
->uri
+ 12, '/') ||
1960 strlen(con
->uri
) == 12)) ||
1961 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1962 (strchr(con
->uri
+ 11, '/') ||
1963 strlen(con
->uri
) == 11)))
1966 * HEAD can only be done to configuration files under
1970 cupsdLogMessage(CUPSD_LOG_ERROR
,
1971 "[Client %d] Request for subdirectory \"%s\".",
1972 con
->http
.fd
, con
->uri
);
1974 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1976 cupsdCloseClient(con
);
1982 else if ((filename
= get_file(con
, &filestats
, buf
,
1983 sizeof(buf
))) == NULL
)
1985 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1988 cupsdCloseClient(con
);
1992 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1994 else if (!check_if_modified(con
, &filestats
))
1996 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1998 cupsdCloseClient(con
);
2002 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
2010 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
2012 strlcpy(line
, "text/plain", sizeof(line
));
2014 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
2016 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
2018 cupsdCloseClient(con
);
2022 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
2023 httpGetDateString(filestats
.st_mtime
)) < 0)
2025 cupsdCloseClient(con
);
2029 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2030 (unsigned long)filestats
.st_size
) < 0)
2032 cupsdCloseClient(con
);
2036 cupsdLogRequest(con
, HTTP_OK
);
2039 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2041 cupsdCloseClient(con
);
2045 if (cupsdFlushHeader(con
) < 0)
2047 cupsdCloseClient(con
);
2051 con
->http
.state
= HTTP_STATE_WAITING
;
2052 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
2057 break; /* Anti-compiler-warning-code */
2063 * Handle any incoming data...
2066 switch (con
->http
.state
)
2068 case HTTP_STATE_PUT_RECV
:
2071 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2073 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2074 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2075 "[Client %d] HTTP_STATE_PUT_RECV Closing for error "
2076 "%d (%s)", con
->http
.fd
, con
->http
.error
,
2077 strerror(con
->http
.error
));
2079 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2080 "[Client %d] HTTP_STATE_PUT_RECV Closing on EOF",
2083 cupsdCloseClient(con
);
2088 con
->bytes
+= bytes
;
2090 if (write(con
->file
, line
, bytes
) < bytes
)
2092 cupsdLogMessage(CUPSD_LOG_ERROR
,
2093 "[Client %d] Unable to write %d bytes to "
2094 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2099 unlink(con
->filename
);
2100 cupsdClearString(&con
->filename
);
2102 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2104 cupsdCloseClient(con
);
2110 while (con
->http
.state
== HTTP_STATE_PUT_RECV
&& data_ready(con
));
2112 if (con
->http
.state
== HTTP_STATE_STATUS
)
2115 * End of file, see how big it is...
2118 fstat(con
->file
, &filestats
);
2123 if (filestats
.st_size
> MaxRequestSize
&&
2127 * Request is too big; remove it and send an error...
2130 unlink(con
->filename
);
2131 cupsdClearString(&con
->filename
);
2133 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2135 cupsdCloseClient(con
);
2141 * Install the configuration file...
2144 status
= install_cupsd_conf(con
);
2147 * Return the status to the client...
2150 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2152 cupsdCloseClient(con
);
2158 case HTTP_STATE_POST_RECV
:
2161 if (con
->request
&& con
->file
< 0)
2164 * Grab any request data from the connection...
2167 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2169 cupsdLogMessage(CUPSD_LOG_ERROR
,
2170 "[Client %d] IPP read error: %s", con
->http
.fd
,
2171 cupsLastErrorString());
2173 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2174 cupsdCloseClient(con
);
2177 else if (ipp_state
!= IPP_DATA
)
2179 if (con
->http
.state
== HTTP_STATE_POST_SEND
)
2181 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2182 cupsdCloseClient(con
);
2186 if (data_ready(con
))
2192 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2193 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2194 con
->request
->request
.op
.version
[1],
2195 ippOpString(con
->request
->request
.op
.operation_id
),
2196 con
->request
->request
.op
.request_id
);
2197 con
->bytes
+= ippLength(con
->request
);
2201 if (con
->file
< 0 && con
->http
.state
!= HTTP_STATE_POST_SEND
)
2204 * Create a file as needed for the request data...
2207 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2209 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2213 cupsdLogMessage(CUPSD_LOG_ERROR
,
2214 "[Client %d] Unable to create request file "
2215 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2218 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2220 cupsdCloseClient(con
);
2225 fchmod(con
->file
, 0640);
2226 fchown(con
->file
, RunUser
, Group
);
2227 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2230 if (con
->http
.state
!= HTTP_STATE_POST_SEND
)
2232 if (!httpWait(HTTP(con
), 0))
2234 else if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2236 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2237 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2238 "[Client %d] HTTP_STATE_POST_SEND Closing for "
2239 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2240 strerror(con
->http
.error
));
2242 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2243 "[Client %d] HTTP_STATE_POST_SEND Closing on EOF",
2246 cupsdCloseClient(con
);
2251 con
->bytes
+= bytes
;
2253 if (write(con
->file
, line
, bytes
) < bytes
)
2255 cupsdLogMessage(CUPSD_LOG_ERROR
,
2256 "[Client %d] Unable to write %d bytes to "
2257 "\"%s\": %s", con
->http
.fd
, bytes
,
2258 con
->filename
, strerror(errno
));
2262 unlink(con
->filename
);
2263 cupsdClearString(&con
->filename
);
2265 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2268 cupsdCloseClient(con
);
2273 else if (con
->http
.state
== HTTP_STATE_POST_RECV
)
2275 else if (con
->http
.state
!= HTTP_STATE_POST_SEND
)
2277 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2278 "[Client %d] Closing on unexpected state %s.",
2279 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2280 cupsdCloseClient(con
);
2285 while (con
->http
.state
== HTTP_STATE_POST_RECV
&& data_ready(con
));
2287 if (con
->http
.state
== HTTP_STATE_POST_SEND
)
2291 fstat(con
->file
, &filestats
);
2296 if (filestats
.st_size
> MaxRequestSize
&&
2300 * Request is too big; remove it and send an error...
2303 unlink(con
->filename
);
2304 cupsdClearString(&con
->filename
);
2309 * Delete any IPP request data...
2312 ippDelete(con
->request
);
2313 con
->request
= NULL
;
2316 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2318 cupsdCloseClient(con
);
2322 else if (filestats
.st_size
== 0)
2325 * Don't allow empty file...
2328 unlink(con
->filename
);
2329 cupsdClearString(&con
->filename
);
2334 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2336 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2338 cupsdCloseClient(con
);
2343 cupsdLogRequest(con
, HTTP_OK
);
2349 cupsdProcessIPPRequest(con
);
2353 unlink(con
->filename
);
2354 cupsdClearString(&con
->filename
);
2363 break; /* Anti-compiler-warning-code */
2366 if (con
->http
.state
== HTTP_STATE_WAITING
)
2368 if (!con
->http
.keep_alive
)
2370 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2371 "[Client %d] Closing because Keep-Alive disabled",
2373 cupsdCloseClient(con
);
2377 cupsArrayRemove(ActiveClients
, con
);
2378 cupsdSetBusyState();
2385 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2388 int /* O - 1 on success, 0 on failure */
2390 cupsd_client_t
*con
, /* I - Client connection */
2391 char *command
, /* I - Command to run */
2392 char *options
, /* I - Command-line options */
2393 int root
) /* I - Run as root? */
2395 int fd
; /* Standard input file descriptor */
2400 fd
= open(con
->filename
, O_RDONLY
);
2404 cupsdLogMessage(CUPSD_LOG_ERROR
,
2405 "[Client %d] Unable to open \"%s\" for reading: %s",
2406 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2411 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2416 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2421 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2422 con
->http
.fd
, command
, con
->pipe_pid
);
2424 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2427 if (con
->pipe_pid
== 0)
2430 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2432 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2434 con
->sent_header
= 0;
2435 con
->file_ready
= 0;
2436 con
->got_fields
= 0;
2437 con
->header_used
= 0;
2444 * 'cupsdSendError()' - Send an error message via HTTP.
2447 int /* O - 1 if successful, 0 otherwise */
2448 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2449 http_status_t code
, /* I - Error code */
2450 int auth_type
)/* I - Authentication type */
2452 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2453 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2454 con
->http
.fd
, code
, auth_type
);
2458 * Force client to upgrade for authentication if that is how the
2459 * server is configured...
2462 if (code
== HTTP_UNAUTHORIZED
&&
2463 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2464 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2467 code
= HTTP_UPGRADE_REQUIRED
;
2469 #endif /* HAVE_SSL */
2472 * Put the request in the access_log file...
2475 cupsdLogRequest(con
, code
);
2478 * To work around bugs in some proxies, don't use Keep-Alive for some
2481 * Kerberos authentication doesn't work without Keep-Alive, so
2482 * never disable it in that case.
2485 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2486 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2489 * Send an error message back to the client. If the error code is a
2490 * 400 or 500 series, make sure the message contains some text, too!
2493 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2497 if (code
== HTTP_UPGRADE_REQUIRED
)
2498 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2501 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2503 #endif /* HAVE_SSL */
2505 if (con
->http
.version
>= HTTP_1_1
&&
2506 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2508 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2512 if (code
>= HTTP_BAD_REQUEST
)
2515 * Send a human-readable error message.
2518 char message
[4096], /* Message for user */
2519 urltext
[1024], /* URL redirection text */
2520 redirect
[1024]; /* Redirection link */
2521 const char *text
; /* Status-specific text */
2526 if (code
== HTTP_UNAUTHORIZED
)
2527 text
= _cupsLangString(con
->language
,
2528 _("Enter your username and password or the "
2529 "root username and password to access this "
2530 "page. If you are using Kerberos authentication, "
2531 "make sure you have a valid Kerberos ticket."));
2532 else if (code
== HTTP_UPGRADE_REQUIRED
)
2536 snprintf(urltext
, sizeof(urltext
),
2537 _cupsLangString(con
->language
,
2538 _("You must access this page using the URL "
2539 "<A HREF=\"https://%s:%d%s\">"
2540 "https://%s:%d%s</A>.")),
2541 con
->servername
, con
->serverport
, con
->uri
,
2542 con
->servername
, con
->serverport
, con
->uri
);
2544 snprintf(redirect
, sizeof(redirect
),
2545 "<META HTTP-EQUIV=\"Refresh\" "
2546 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2547 con
->servername
, con
->serverport
, con
->uri
);
2549 else if (code
== HTTP_WEBIF_DISABLED
)
2550 text
= _cupsLangString(con
->language
,
2551 _("The web interface is currently disabled. Run "
2552 "\"cupsctl WebInterface=yes\" to enable it."));
2556 snprintf(message
, sizeof(message
),
2557 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2558 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2561 "\t<META HTTP-EQUIV=\"Content-Type\" "
2562 "CONTENT=\"text/html; charset=utf-8\">\n"
2563 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2564 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2565 "HREF=\"/cups.css\">\n"
2573 httpStatus(code
), redirect
, httpStatus(code
), text
);
2575 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2577 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2578 (int)strlen(message
)) < 0)
2580 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2582 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2585 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2588 if (cupsdFlushHeader(con
) < 0)
2591 con
->http
.state
= HTTP_STATE_WAITING
;
2593 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2600 * 'cupsdSendHeader()' - Send an HTTP request.
2603 int /* O - 1 on success, 0 on failure */
2605 cupsd_client_t
*con
, /* I - Client to send to */
2606 http_status_t code
, /* I - HTTP status code */
2607 char *type
, /* I - MIME type of document */
2608 int auth_type
) /* I - Type of authentication */
2610 char auth_str
[1024]; /* Authorization string */
2614 * Send the HTTP status header...
2617 if (code
== HTTP_CONTINUE
)
2620 * 100-continue doesn't send any headers...
2623 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2624 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2626 else if (code
== HTTP_WEBIF_DISABLED
)
2629 * Treat our special "web interface is disabled" status as "200 OK" for web
2636 httpFlushWrite(HTTP(con
));
2638 con
->http
.data_encoding
= HTTP_ENCODING_FIELDS
;
2640 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2641 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2643 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2646 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2648 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2650 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2652 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2653 KeepAliveTimeout
) < 0)
2656 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2657 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2660 if (code
== HTTP_UNAUTHORIZED
)
2662 if (auth_type
== CUPSD_AUTH_NONE
)
2664 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2665 auth_type
= cupsdDefaultAuthType();
2667 auth_type
= con
->best
->type
;
2672 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2673 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2674 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2675 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2676 con
->http
.hostname
);
2678 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2681 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2682 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2684 # endif /* AF_LOCAL */
2685 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2687 #endif /* HAVE_GSSAPI */
2689 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2690 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2693 * Add a "trc" (try root certification) parameter for local non-Kerberos
2694 * requests when the request requires system group membership - then the
2695 * client knows the root certificate can/should be used.
2697 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2698 * parameter as needed...
2701 char *name
, /* Current user name */
2702 *auth_key
; /* Auth key buffer */
2703 size_t auth_size
; /* Size of remaining buffer */
2705 auth_key
= auth_str
+ strlen(auth_str
);
2706 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2708 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2710 name
= (char *)cupsArrayNext(con
->best
->names
))
2712 #ifdef HAVE_AUTHORIZATION_H
2713 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2715 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2716 /* end parenthesis is stripped in conf.c */
2720 #endif /* HAVE_AUTHORIZATION_H */
2721 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2723 #ifdef HAVE_AUTHORIZATION_H
2724 if (SystemGroupAuthKey
)
2725 snprintf(auth_key
, auth_size
,
2727 SystemGroupAuthKey
);
2730 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2731 #endif /* HAVE_AUTHORIZATION_H */
2739 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2740 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2743 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2748 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2750 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2751 con
->language
->language
) < 0)
2757 if (!strcmp(type
, "text/html"))
2759 if (httpPrintf(HTTP(con
),
2760 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2763 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2772 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2776 cupsdUpdateCGI(void)
2778 char *ptr
, /* Pointer to end of line in buffer */
2779 message
[1024]; /* Pointer to message text */
2780 int loglevel
; /* Log level for message */
2783 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2784 message
, sizeof(message
))) != NULL
)
2786 if (loglevel
== CUPSD_LOG_INFO
)
2787 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2789 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2793 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2796 * Fatal error on pipe - should never happen!
2799 cupsdLogMessage(CUPSD_LOG_CRIT
,
2800 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2807 * 'cupsdWriteClient()' - Write data to a client as needed.
2811 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2813 int bytes
, /* Number of bytes written */
2814 field_col
; /* Current column */
2815 char *bufptr
, /* Pointer into buffer */
2816 *bufend
; /* Pointer to end of buffer */
2817 ipp_state_t ipp_state
; /* IPP state value */
2820 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2821 "[Client %d] cupsdWriteClient "
2825 "data_encoding=HTTP_ENCODING_%s, "
2826 "data_remaining=" CUPS_LLFMT
", "
2830 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2831 http_states
[con
->http
.state
+ 1],
2832 con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
?
2833 "CHUNKED" : "LENGTH",
2834 CUPS_LLCAST con
->http
.data_remaining
,
2836 con
->response
? ipp_states
[con
->response
->state
] : "",
2837 con
->pipe_pid
, con
->file
);
2839 if (con
->http
.state
!= HTTP_STATE_GET_SEND
&&
2840 con
->http
.state
!= HTTP_STATE_POST_SEND
)
2843 * If we get called in the wrong state, then something went wrong with the
2844 * connection and we need to shut it down...
2847 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2848 "[Client %d] Closing on unexpected HTTP state %s.",
2849 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2850 cupsdCloseClient(con
);
2857 * Make sure we select on the CGI output...
2860 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2862 if (!con
->file_ready
)
2865 * Try again later when there is CGI output available...
2868 cupsdRemoveSelect(con
->http
.fd
);
2872 con
->file_ready
= 0;
2875 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2877 int wused
= con
->http
.wused
; /* Previous write buffer use */
2882 * Write a single attribute or the IPP message header...
2885 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2888 * If the write buffer has been flushed, stop buffering up attributes...
2891 if (con
->http
.wused
<= wused
)
2894 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2896 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2897 "[Client %d] Writing IPP response, ipp_state=%s, old "
2898 "wused=%d, new wused=%d", con
->http
.fd
,
2899 ipp_state
== IPP_STATE_ERROR
? "ERROR" :
2900 ipp_state
== IPP_STATE_IDLE
? "IDLE" :
2901 ipp_state
== IPP_STATE_HEADER
? "HEADER" :
2902 ipp_state
== IPP_STATE_ATTRIBUTE
? "ATTRIBUTE" : "DATA",
2903 wused
, con
->http
.wused
);
2905 if (con
->http
.wused
> 0)
2906 httpFlushWrite(HTTP(con
));
2908 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2909 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2911 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2912 "[Client %d] bytes=%d, http_state=%d, "
2913 "data_remaining=" CUPS_LLFMT
,
2914 con
->http
.fd
, (int)bytes
, con
->http
.state
,
2915 CUPS_LLCAST con
->http
.data_remaining
);
2917 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2918 sizeof(con
->header
) - con
->header_used
)) > 0)
2920 con
->header_used
+= bytes
;
2922 if (con
->pipe_pid
&& !con
->got_fields
)
2925 * Inspect the data for Content-Type and other fields.
2928 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2930 !con
->got_fields
&& bufptr
< bufend
;
2933 if (*bufptr
== '\n')
2936 * Send line to client...
2939 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2943 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2945 if (!con
->sent_header
)
2948 * Handle redirection and CGI status codes...
2951 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2953 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2955 cupsdCloseClient(con
);
2959 con
->sent_header
= 2;
2961 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2964 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2966 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2968 con
->sent_header
= 2;
2972 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2974 cupsdCloseClient(con
);
2978 con
->sent_header
= 1;
2980 if (con
->http
.version
== HTTP_1_1
)
2982 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2988 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2989 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2995 con
->header_used
-= bufptr
- con
->header
;
2997 if (con
->header_used
> 0)
2998 memmove(con
->header
, bufptr
, con
->header_used
);
3000 bufptr
= con
->header
- 1;
3003 * See if the line was empty...
3008 con
->got_fields
= 1;
3010 if (cupsdFlushHeader(con
) < 0)
3012 cupsdCloseClient(con
);
3016 if (con
->http
.version
== HTTP_1_1
)
3017 con
->http
.data_encoding
= HTTP_ENCODING_CHUNKED
;
3022 else if (*bufptr
!= '\r')
3026 if (!con
->got_fields
)
3028 con
->http
.activity
= time(NULL
);
3033 if (con
->header_used
> 0)
3035 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
3037 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3038 "[Client %d] Closing for error %d (%s)",
3039 con
->http
.fd
, con
->http
.error
,
3040 strerror(con
->http
.error
));
3041 cupsdCloseClient(con
);
3045 if (con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
)
3046 httpFlushWrite(HTTP(con
));
3048 con
->bytes
+= con
->header_used
;
3050 if (con
->http
.state
== HTTP_STATE_WAITING
)
3053 bytes
= con
->header_used
;
3055 con
->header_used
= 0;
3060 (con
->http
.state
!= HTTP_STATE_GET_SEND
&&
3061 con
->http
.state
!= HTTP_STATE_POST_SEND
))
3063 if (!con
->sent_header
&& con
->pipe_pid
)
3064 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
3067 cupsdLogRequest(con
, HTTP_OK
);
3069 httpFlushWrite(HTTP(con
));
3071 if (con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
&&
3072 con
->sent_header
== 1)
3074 if (httpWrite2(HTTP(con
), "", 0) < 0)
3076 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3077 "[Client %d] Closing for error %d (%s)",
3078 con
->http
.fd
, con
->http
.error
,
3079 strerror(con
->http
.error
));
3080 cupsdCloseClient(con
);
3086 con
->http
.state
= HTTP_STATE_WAITING
;
3088 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
3092 cupsdRemoveSelect(con
->file
);
3095 cupsdEndProcess(con
->pipe_pid
, 0);
3104 unlink(con
->filename
);
3105 cupsdClearString(&con
->filename
);
3110 ippDelete(con
->request
);
3111 con
->request
= NULL
;
3116 ippDelete(con
->response
);
3117 con
->response
= NULL
;
3120 cupsdClearString(&con
->command
);
3121 cupsdClearString(&con
->options
);
3122 cupsdClearString(&con
->query_string
);
3124 if (!con
->http
.keep_alive
)
3126 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3127 "[Client %d] Closing because Keep-Alive disabled.",
3129 cupsdCloseClient(con
);
3134 cupsArrayRemove(ActiveClients
, con
);
3135 cupsdSetBusyState();
3139 con
->http
.activity
= time(NULL
);
3144 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3147 static int /* O - 1 if modified since */
3149 cupsd_client_t
*con
, /* I - Client connection */
3150 struct stat
*filestats
) /* I - File information */
3152 char *ptr
; /* Pointer into field */
3153 time_t date
; /* Time/date value */
3154 off_t size
; /* Size/length value */
3159 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3164 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3165 "[Client %d] check_if_modified "
3166 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3167 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3168 (int)filestats
->st_mtime
, ptr
);
3170 while (*ptr
!= '\0')
3172 while (isspace(*ptr
) || *ptr
== ';')
3175 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3178 size
= strtoll(ptr
, NULL
, 10);
3180 while (isdigit(*ptr
))
3183 else if (isalpha(*ptr
))
3185 date
= httpGetDateTime(ptr
);
3186 while (*ptr
!= '\0' && *ptr
!= ';')
3193 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3194 (date
< filestats
->st_mtime
&& date
!= 0) ||
3195 (size
== 0 && date
== 0));
3200 * 'compare_clients()' - Compare two client connections.
3203 static int /* O - Result of comparison */
3204 compare_clients(cupsd_client_t
*a
, /* I - First client */
3205 cupsd_client_t
*b
, /* I - Second client */
3206 void *data
) /* I - User data (not used) */
3220 * 'data_ready()' - Check whether data is available from a client.
3223 static int /* O - 1 if data is ready, 0 otherwise */
3224 data_ready(cupsd_client_t
*con
) /* I - Client */
3226 if (con
->http
.used
> 0)
3229 else if (con
->http
.tls
)
3232 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3234 # elif defined(HAVE_GNUTLS)
3235 if (gnutls_record_check_pending(con
->http
.tls
))
3237 # elif defined(HAVE_CDSASSL)
3238 size_t bytes
; /* Bytes that are available */
3240 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3242 # endif /* HAVE_LIBSSL */
3244 #endif /* HAVE_SSL */
3251 * 'get_file()' - Get a filename and state info.
3254 static char * /* O - Real filename */
3255 get_file(cupsd_client_t
*con
, /* I - Client connection */
3256 struct stat
*filestats
, /* O - File information */
3257 char *filename
, /* IO - Filename buffer */
3258 int len
) /* I - Buffer length */
3260 int status
; /* Status of filesystem calls */
3261 char *ptr
; /* Pointer info filename */
3262 int plen
; /* Remaining length after pointer */
3263 char language
[7]; /* Language subdirectory, if any */
3267 * Figure out the real filename...
3272 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3273 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3274 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3276 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3277 if (access(filename
, F_OK
) < 0)
3278 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3280 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3281 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3282 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3283 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3284 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3286 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3287 strlcpy(filename
, AccessLog
, len
);
3288 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3289 strlcpy(filename
, ErrorLog
, len
);
3290 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3291 strlcpy(filename
, PageLog
, len
);
3295 else if (con
->language
)
3297 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3298 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3301 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3303 if ((ptr
= strchr(filename
, '?')) != NULL
)
3307 * Grab the status for this language; if there isn't a language-specific file
3308 * then fallback to the default one...
3311 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3312 strncmp(con
->uri
, "/icons/", 7) &&
3313 strncmp(con
->uri
, "/ppd/", 5) &&
3314 strncmp(con
->uri
, "/rss/", 5) &&
3315 strncmp(con
->uri
, "/admin/conf/", 12) &&
3316 strncmp(con
->uri
, "/admin/log/", 11))
3319 * Drop the country code...
3323 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3325 if ((ptr
= strchr(filename
, '?')) != NULL
)
3328 if ((status
= stat(filename
, filestats
)) != 0)
3331 * Drop the language prefix and try the root directory...
3335 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3337 if ((ptr
= strchr(filename
, '?')) != NULL
)
3340 status
= stat(filename
, filestats
);
3345 * If we're found a directory, get the index.html file instead...
3348 if (!status
&& S_ISDIR(filestats
->st_mode
))
3351 * Make sure the URI ends with a slash...
3354 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3355 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3358 * Find the directory index file, trying every language...
3363 if (status
&& language
[0])
3366 * Try a different language subset...
3370 language
[0] = '\0'; /* Strip country code */
3372 language
[0] = '\0'; /* Strip language */
3376 * Look for the index file...
3379 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3381 if ((ptr
= strchr(filename
, '?')) != NULL
)
3384 ptr
= filename
+ strlen(filename
);
3385 plen
= len
- (ptr
- filename
);
3387 strlcpy(ptr
, "index.html", plen
);
3388 status
= stat(filename
, filestats
);
3393 strlcpy(ptr
, "index.class", plen
);
3394 status
= stat(filename
, filestats
);
3396 #endif /* HAVE_JAVA */
3401 strlcpy(ptr
, "index.pl", plen
);
3402 status
= stat(filename
, filestats
);
3404 #endif /* HAVE_PERL */
3409 strlcpy(ptr
, "index.php", plen
);
3410 status
= stat(filename
, filestats
);
3412 #endif /* HAVE_PHP */
3417 strlcpy(ptr
, "index.pyc", plen
);
3418 status
= stat(filename
, filestats
);
3423 strlcpy(ptr
, "index.py", plen
);
3424 status
= stat(filename
, filestats
);
3426 #endif /* HAVE_PYTHON */
3429 while (status
&& language
[0]);
3432 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3433 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3434 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3435 status
? "(null)" : filename
);
3445 * 'install_cupsd_conf()' - Install a configuration file.
3448 static http_status_t
/* O - Status */
3449 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3451 char filename
[1024]; /* Configuration filename */
3452 cups_file_t
*in
, /* Input file */
3453 *out
; /* Output file */
3454 char buffer
[16384]; /* Copy buffer */
3455 ssize_t bytes
; /* Number of bytes */
3459 * Open the request file...
3462 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3464 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3465 con
->filename
, strerror(errno
));
3466 return (HTTP_SERVER_ERROR
);
3470 * Open the new config file...
3473 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3476 return (HTTP_SERVER_ERROR
);
3479 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3483 * Copy from the request to the new config file...
3486 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3487 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3489 cupsdLogMessage(CUPSD_LOG_ERROR
,
3490 "Unable to copy to config file \"%s\": %s",
3491 ConfigurationFile
, strerror(errno
));
3496 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3497 cupsdUnlinkOrRemoveFile(filename
);
3499 return (HTTP_SERVER_ERROR
);
3503 * Close the files...
3508 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3509 return (HTTP_SERVER_ERROR
);
3512 * Remove the request file...
3515 cupsdUnlinkOrRemoveFile(con
->filename
);
3516 cupsdClearString(&con
->filename
);
3519 * Set the NeedReload flag...
3522 NeedReload
= RELOAD_CUPSD
;
3523 ReloadTime
= time(NULL
);
3526 * Return that the file was created successfully...
3529 return (HTTP_CREATED
);
3534 * 'is_cgi()' - Is the resource a CGI script/program?
3537 static int /* O - 1 = CGI, 0 = file */
3538 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3539 const char *filename
, /* I - Real filename */
3540 struct stat
*filestats
, /* I - File information */
3541 mime_type_t
*type
) /* I - MIME type */
3543 const char *options
; /* Options on URL */
3547 * Get the options, if any...
3550 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3553 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3557 * Check for known types...
3560 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3562 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3563 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3564 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3565 filestats
, type
? type
->super
: "unknown",
3566 type
? type
->type
: "unknown");
3570 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3571 (filestats
->st_mode
& 0111))
3574 * "application/x-httpd-cgi" is a CGI script.
3577 cupsdSetString(&con
->command
, filename
);
3580 cupsdSetStringf(&con
->options
, " %s", options
);
3582 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3583 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3584 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3585 filestats
, type
->super
, type
->type
);
3589 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3592 * "application/x-httpd-java" is a Java servlet.
3595 cupsdSetString(&con
->command
, CUPS_JAVA
);
3598 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3600 cupsdSetStringf(&con
->options
, " %s", filename
);
3602 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3603 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3604 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3605 filestats
, type
->super
, type
->type
);
3608 #endif /* HAVE_JAVA */
3610 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3613 * "application/x-httpd-perl" is a Perl page.
3616 cupsdSetString(&con
->command
, CUPS_PERL
);
3619 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3621 cupsdSetStringf(&con
->options
, " %s", filename
);
3623 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3624 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3625 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3626 filestats
, type
->super
, type
->type
);
3629 #endif /* HAVE_PERL */
3631 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3634 * "application/x-httpd-php" is a PHP page.
3637 cupsdSetString(&con
->command
, CUPS_PHP
);
3640 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3642 cupsdSetStringf(&con
->options
, " %s", filename
);
3644 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3645 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3646 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3647 filestats
, type
->super
, type
->type
);
3650 #endif /* HAVE_PHP */
3652 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3655 * "application/x-httpd-python" is a Python page.
3658 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3661 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3663 cupsdSetStringf(&con
->options
, " %s", filename
);
3665 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3666 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3667 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3668 filestats
, type
->super
, type
->type
);
3671 #endif /* HAVE_PYTHON */
3673 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3674 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3675 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3676 filestats
, type
->super
, type
->type
);
3682 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3685 static int /* O - 0 if relative, 1 if absolute */
3686 is_path_absolute(const char *path
) /* I - Input path */
3689 * Check for a leading slash...
3696 * Check for "/.." in the path...
3699 while ((path
= strstr(path
, "/..")) != NULL
)
3701 if (!path
[3] || path
[3] == '/')
3708 * If we haven't found any relative paths, return 1 indicating an
3717 * 'pipe_command()' - Pipe the output of a command to the remote client.
3720 static int /* O - Process ID */
3721 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3722 int infile
, /* I - Standard input for command */
3723 int *outfile
, /* O - Standard output for command */
3724 char *command
, /* I - Command to run */
3725 char *options
, /* I - Options for command */
3726 int root
) /* I - Run as root? */
3728 int i
; /* Looping var */
3729 int pid
; /* Process ID */
3730 char *commptr
, /* Command string pointer */
3731 commch
; /* Command string character */
3732 char *uriptr
; /* URI string pointer */
3733 int fds
[2]; /* Pipe FDs */
3734 int argc
; /* Number of arguments */
3735 int envc
; /* Number of environment variables */
3736 char argbuf
[10240], /* Argument buffer */
3737 *argv
[100], /* Argument strings */
3738 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3739 char auth_type
[256], /* AUTH_TYPE environment variable */
3740 content_length
[1024], /* CONTENT_LENGTH environment variable */
3741 content_type
[1024], /* CONTENT_TYPE environment variable */
3742 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3743 http_referer
[1024], /* HTTP_REFERER environment variable */
3744 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3745 lang
[1024], /* LANG environment variable */
3746 path_info
[1024], /* PATH_INFO environment variable */
3747 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3748 remote_host
[1024], /* REMOTE_HOST environment variable */
3749 remote_user
[1024], /* REMOTE_USER environment variable */
3750 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3751 script_name
[1024], /* SCRIPT_NAME environment variable */
3752 server_name
[1024], /* SERVER_NAME environment variable */
3753 server_port
[1024]; /* SERVER_PORT environment variable */
3754 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3758 * Parse a copy of the options string, which is of the form:
3760 * argument+argument+argument
3761 * ?argument+argument+argument
3762 * param=value¶m=value
3763 * ?param=value¶m=value
3764 * /name?argument+argument+argument
3765 * /name?param=value¶m=value
3767 * If the string contains an "=" character after the initial name,
3768 * then we treat it as a HTTP GET form request and make a copy of
3769 * the remaining string for the environment variable.
3771 * The string is always parsed out as command-line arguments, to
3772 * be consistent with Apache...
3775 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3776 "[Client %d] pipe_command infile=%d, outfile=%p, "
3777 "command=\"%s\", options=\"%s\", root=%d",
3778 con
->http
.fd
, infile
, outfile
, command
,
3779 options
? options
: "(null)", root
);
3786 if (*commptr
== ' ')
3788 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3793 if (argbuf
[0] == '/')
3796 * Found some trailing path information, set PATH_INFO...
3799 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3800 commptr
= argbuf
+ strlen(argbuf
);
3804 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3810 path_info
[0] = '\0';
3812 if (*commptr
== ' ')
3816 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3819 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3826 argv
[argc
++] = commptr
;
3828 for (; *commptr
&& argc
< 99; commptr
++)
3831 * Break arguments whenever we see a + or space...
3834 if (*commptr
== ' ' || *commptr
== '+')
3836 while (*commptr
== ' ' || *commptr
== '+')
3840 * If we don't have a blank string, save it as another argument...
3845 argv
[argc
] = commptr
;
3851 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3852 isxdigit(commptr
[2] & 255))
3855 * Convert the %xx notation to the individual character.
3858 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3859 *commptr
= (commptr
[1] - '0') << 4;
3861 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3863 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3864 *commptr
|= commptr
[2] - '0';
3866 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3868 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3871 * Check for a %00 and break if that is the case...
3883 * Setup the environment variables as needed...
3886 if (con
->username
[0])
3888 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3889 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3891 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3895 auth_type
[0] = '\0';
3898 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3899 IPP_TAG_LANGUAGE
)) != NULL
)
3901 switch (strlen(attr
->values
[0].string
.text
))
3905 * This is an unknown or badly formatted language code; use
3906 * the POSIX locale...
3909 strlcpy(lang
, "LANG=C", sizeof(lang
));
3914 * Just the language code (ll)...
3917 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3918 attr
->values
[0].string
.text
);
3923 * Language and country code (ll-cc)...
3926 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3927 attr
->values
[0].string
.text
[0],
3928 attr
->values
[0].string
.text
[1],
3929 toupper(attr
->values
[0].string
.text
[3] & 255),
3930 toupper(attr
->values
[0].string
.text
[4] & 255));
3934 else if (con
->language
)
3935 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3937 strlcpy(lang
, "LANG=C", sizeof(lang
));
3939 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3940 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3941 sizeof(remote_addr
) - 12);
3943 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3944 con
->http
.hostname
);
3946 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3947 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3950 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3951 DocumentRoot
, script_name
+ 12);
3953 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3955 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3957 char *nameptr
; /* Pointer to ":port" */
3959 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3960 con
->http
.fields
[HTTP_FIELD_HOST
]);
3961 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3962 *nameptr
= '\0'; /* Strip trailing ":port" */
3965 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3968 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3971 envp
[envc
++] = auth_type
;
3973 envp
[envc
++] = lang
;
3974 envp
[envc
++] = "REDIRECT_STATUS=1";
3975 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3976 envp
[envc
++] = server_name
;
3977 envp
[envc
++] = server_port
;
3978 envp
[envc
++] = remote_addr
;
3979 envp
[envc
++] = remote_host
;
3980 envp
[envc
++] = script_name
;
3981 envp
[envc
++] = script_filename
;
3984 envp
[envc
++] = path_info
;
3986 if (con
->username
[0])
3988 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3990 envp
[envc
++] = remote_user
;
3993 if (con
->http
.version
== HTTP_1_1
)
3994 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3995 else if (con
->http
.version
== HTTP_1_0
)
3996 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3998 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4000 if (con
->http
.cookie
)
4002 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4004 envp
[envc
++] = http_cookie
;
4007 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4009 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4010 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4011 envp
[envc
++] = http_user_agent
;
4014 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4016 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4017 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4018 envp
[envc
++] = http_referer
;
4021 if (con
->operation
== HTTP_STATE_GET
)
4023 envp
[envc
++] = "REQUEST_METHOD=GET";
4025 if (con
->query_string
)
4028 * Add GET form variables after ?...
4031 envp
[envc
++] = con
->query_string
;
4034 envp
[envc
++] = "QUERY_STRING=";
4038 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4039 CUPS_LLCAST con
->bytes
);
4040 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4041 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4043 envp
[envc
++] = "REQUEST_METHOD=POST";
4044 envp
[envc
++] = content_length
;
4045 envp
[envc
++] = content_type
;
4049 * Tell the CGI if we are using encryption...
4053 envp
[envc
++] = "HTTPS=ON";
4056 * Terminate the environment array...
4061 if (LogLevel
>= CUPSD_LOG_DEBUG
)
4063 for (i
= 0; i
< argc
; i
++)
4064 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4065 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
4066 for (i
= 0; i
< envc
; i
++)
4067 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4068 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
4072 * Create a pipe for the output...
4075 if (cupsdOpenPipe(fds
))
4077 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
4078 argv
[0], strerror(errno
));
4083 * Then execute the command...
4086 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4087 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
4090 * Error - can't fork!
4093 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
4096 cupsdClosePipe(fds
);
4102 * Fork successful - return the PID...
4105 if (con
->username
[0])
4106 cupsdAddCert(pid
, con
->username
, con
->type
);
4108 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
4119 * 'valid_host()' - Is the Host: field valid?
4122 static int /* O - 1 if valid, 0 if not */
4123 valid_host(cupsd_client_t
*con
) /* I - Client connection */
4125 cupsd_alias_t
*a
; /* Current alias */
4126 cupsd_netif_t
*netif
; /* Current network interface */
4127 const char *host
, /* Host field */
4128 *end
; /* End character */
4131 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
4133 if (httpAddrLocalhost(con
->http
.hostaddr
))
4136 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4137 * addresses when accessing CUPS via the loopback interface...
4140 return (!_cups_strcasecmp(host
, "localhost") ||
4141 !_cups_strncasecmp(host
, "localhost:", 10) ||
4142 !_cups_strcasecmp(host
, "localhost.") ||
4143 !_cups_strncasecmp(host
, "localhost.:", 11) ||
4145 !_cups_strcasecmp(host
, "localhost.localdomain") ||
4146 !_cups_strncasecmp(host
, "localhost.localdomain:", 22) ||
4147 #endif /* __linux */
4148 !strcmp(host
, "127.0.0.1") ||
4149 !strncmp(host
, "127.0.0.1:", 10) ||
4150 !strcmp(host
, "[::1]") ||
4151 !strncmp(host
, "[::1]:", 6));
4154 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4156 * Check if the hostname is something.local (Bonjour); if so, allow it.
4159 if ((end
= strrchr(host
, '.')) != NULL
&& end
> host
&&
4160 (!end
[1] || end
[1] == ':'))
4163 * "." on end, work back to second-to-last "."...
4165 for (end
--; end
> host
&& *end
!= '.'; end
--);
4168 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4169 !_cups_strncasecmp(end
, ".local:", 7) ||
4170 !_cups_strcasecmp(end
, ".local.") ||
4171 !_cups_strncasecmp(end
, ".local.:", 8)))
4173 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4176 * Check if the hostname is an IP address...
4179 if (isdigit(*host
& 255) || *host
== '[')
4182 * Possible IPv4/IPv6 address...
4185 char temp
[1024], /* Temporary string */
4186 *ptr
; /* Pointer into temporary string */
4187 http_addrlist_t
*addrlist
; /* List of addresses */
4190 strlcpy(temp
, host
, sizeof(temp
));
4191 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
4192 *ptr
= '\0'; /* Strip :port from host value */
4194 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
4197 * Good IPv4/IPv6 address...
4200 httpAddrFreeList(addrlist
);
4206 * Check for (alias) name matches...
4209 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4211 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4214 * "ServerAlias *" allows all host values through...
4217 if (!strcmp(a
->name
, "*"))
4220 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4223 * Prefix matches; check the character at the end - it must be ":", ".",
4227 end
= host
+ a
->namelen
;
4229 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4234 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4235 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4237 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4240 * "ServerAlias *" allows all host values through...
4243 if (!strcmp(a
->name
, "*"))
4246 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4249 * Prefix matches; check the character at the end - it must be ":", ".",
4253 end
= host
+ a
->namelen
;
4255 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4259 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4262 * Check for interface hostname matches...
4265 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4267 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4269 if (!_cups_strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
4272 * Prefix matches; check the character at the end - it must be ":", ".",
4276 end
= host
+ netif
->hostlen
;
4278 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4288 * 'write_file()' - Send a file via HTTP.
4291 static int /* O - 0 on failure, 1 on success */
4292 write_file(cupsd_client_t
*con
, /* I - Client connection */
4293 http_status_t code
, /* I - HTTP status */
4294 char *filename
, /* I - Filename */
4295 char *type
, /* I - File type */
4296 struct stat
*filestats
) /* O - File information */
4298 con
->file
= open(filename
, O_RDONLY
);
4300 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4301 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4302 "type=\"%s\", filestats=%p", con
->http
.fd
,
4303 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4308 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4312 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4315 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4316 httpGetDateString(filestats
->st_mtime
)) < 0)
4318 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4319 CUPS_LLCAST filestats
->st_size
) < 0)
4321 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4324 if (cupsdFlushHeader(con
) < 0)
4327 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
4328 con
->http
.data_remaining
= filestats
->st_size
;
4330 if (con
->http
.data_remaining
<= INT_MAX
)
4331 con
->http
._data_remaining
= con
->http
.data_remaining
;
4333 con
->http
._data_remaining
= INT_MAX
;
4335 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4336 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4343 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4347 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4349 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4350 "[Client %d] write_pipe CGI output on fd %d",
4351 con
->http
.fd
, con
->file
);
4353 con
->file_ready
= 1;
4355 cupsdRemoveSelect(con
->file
);
4356 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);