2 * "$Id: client.c,v 1.91.2.72 2003/09/17 19:24:09 mike Exp $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2003 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * AcceptClient() - Accept a new client.
27 * CloseAllClients() - Close all remote clients immediately.
28 * CloseClient() - Close a remote client.
29 * EncryptClient() - Enable encryption for the client...
30 * IsCGI() - Is the resource a CGI script/program?
31 * ReadClient() - Read data from a client.
32 * SendCommand() - Send output from a command via HTTP.
33 * SendError() - Send an error message via HTTP.
34 * SendFile() - Send a file via HTTP.
35 * SendHeader() - Send an HTTP request.
36 * ShutdownClient() - Shutdown the receiving end of a connection.
37 * UpdateCGI() - Read status messages from CGI scripts and programs.
38 * WriteClient() - Write data to a client as needed.
39 * check_if_modified() - Decode an "If-Modified-Since" line.
40 * decode_auth() - Decode an authorization string.
41 * get_file() - Get a filename and state info.
42 * install_conf_file() - Install a configuration file.
43 * pipe_command() - Pipe the output of a command to the remote client.
44 * CDSAReadFunc() - Read function for CDSA decryption code.
45 * CDSAWriteFunc() - Write function for CDSA encryption code.
49 * Include necessary headers...
52 #include <cups/http-private.h>
61 static int check_if_modified(client_t
*con
,
62 struct stat
*filestats
);
63 static void decode_auth(client_t
*con
);
64 static char *get_file(client_t
*con
, struct stat
*filestats
,
65 char *filename
, int len
);
66 static http_status_t
install_conf_file(client_t
*con
);
67 static int pipe_command(client_t
*con
, int infile
, int *outfile
,
68 char *command
, char *options
);
71 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
,
73 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
,
74 const void *data
, size_t *dataLength
);
75 #endif /* HAVE_CDSASSL */
79 * 'AcceptClient()' - Accept a new client.
83 AcceptClient(listener_t
*lis
) /* I - Listener socket */
85 int i
; /* Looping var */
86 int count
; /* Count of connections on a host */
87 int val
; /* Parameter value */
88 client_t
*con
; /* New client pointer */
89 const struct hostent
*host
; /* Host entry for address */
90 char *hostname
;/* Hostname for address */
91 http_addr_t temp
; /* Temporary address variable */
92 static time_t last_dos
= 0;
93 /* Time of last DoS attack */
96 LogMessage(L_DEBUG2
, "AcceptClient(%p) %d NumClients = %d",
97 lis
, lis
->fd
, NumClients
);
100 * Make sure we don't have a full set of clients already...
103 if (NumClients
== MaxClients
)
107 * Get a pointer to the next available client...
110 con
= Clients
+ NumClients
;
112 memset(con
, 0, sizeof(client_t
));
113 con
->http
.activity
= time(NULL
);
116 * Accept the client and get the remote address...
119 val
= sizeof(struct sockaddr_in
);
121 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
124 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
130 if (lis
->address
.addr
.sa_family
== AF_INET6
)
131 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
133 #endif /* AF_INET6 */
134 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
137 * Check the number of clients on the same address...
140 for (i
= 0, count
= 0; i
< NumClients
; i
++)
141 if (memcmp(&(Clients
[i
].http
.hostaddr
), &(con
->http
.hostaddr
),
142 sizeof(con
->http
.hostaddr
)) == 0)
145 if (count
>= MaxClientsPerHost
)
149 if (count
>= MaxClientsPerHost
)
151 if ((time(NULL
) - last_dos
) >= 60)
153 last_dos
= time(NULL
);
154 LogMessage(L_WARN
, "Possible DoS attack - more than %d clients connecting from %s!",
155 MaxClientsPerHost
, Clients
[i
].http
.hostname
);
159 closesocket(con
->http
.fd
);
168 * Get the hostname or format the IP address as needed...
172 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
173 sizeof(con
->http
.hostname
));
177 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
178 sizeof(con
->http
.hostname
));
181 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
184 * Map accesses from the loopback interface to "localhost"...
187 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
189 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
192 * Map accesses from the same host to the server name.
195 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
198 if (hostname
== NULL
&& HostNameLookups
== 2)
201 * Can't have an unresolved IP address with double-lookups enabled...
204 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
208 closesocket(con
->http
.fd
);
213 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
218 if (HostNameLookups
== 2)
221 * Do double lookups as needed...
224 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
227 * See if the hostname maps to the same IP address...
230 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
233 * Not the right type of address...
241 * Compare all of the addresses against this one...
244 for (i
= 0; host
->h_addr_list
[i
]; i
++)
246 httpAddrLoad(host
, 0, i
, &temp
);
248 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
252 if (!host
->h_addr_list
[i
])
260 * Can't have a hostname that doesn't resolve to the same IP address
261 * with double-lookups enabled...
264 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
268 closesocket(con
->http
.fd
);
273 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
280 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
281 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
282 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
284 #endif /* AF_INET6 */
285 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
286 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
289 * Using TCP_NODELAY improves responsiveness, especially on systems
290 * with a slow loopback interface... Since we write large buffers
291 * when sending print files and requests, there shouldn't be any
292 * performance penalty for this...
296 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
299 * Close this file on all execs...
302 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
305 * Add the socket to the select() input mask.
308 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
310 FD_SET(con
->http
.fd
, InputSet
);
315 * Temporarily suspend accept()'s until we lose a client...
318 if (NumClients
== MaxClients
)
323 * See if we are connecting on a secure port...
326 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
329 * https connection; go secure...
332 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
336 #endif /* HAVE_SSL */
341 * 'CloseAllClients()' - Close all remote clients immediately.
345 CloseAllClients(void)
347 while (NumClients
> 0)
348 CloseClient(Clients
);
353 * 'CloseClient()' - Close a remote client.
357 CloseClient(client_t
*con
) /* I - Client to close */
359 #if defined(HAVE_LIBSSL)
360 SSL_CTX
*context
; /* Context for encryption */
361 SSL
*conn
; /* Connection for encryption */
362 unsigned long error
; /* Error code */
363 #elif defined(HAVE_GNUTLS)
364 http_tls_t
*conn
; /* TLS connection information */
365 int error
; /* Error code */
366 gnutls_certificate_server_credentials
*credentials
;
367 /* TLS credentials */
368 #endif /* HAVE_GNUTLS */
371 LogMessage(L_DEBUG
, "CloseClient() %d", con
->http
.fd
);
373 if (con
->http
.input_set
)
374 free(con
->http
.input_set
);
376 httpClearCookie(HTTP(con
));
378 ClearString(&con
->filename
);
379 ClearString(&con
->command
);
380 ClearString(&con
->options
);
384 * Shutdown encryption as needed...
390 conn
= (SSL
*)(con
->http
.tls
);
391 context
= SSL_get_SSL_CTX(conn
);
393 switch (SSL_shutdown(conn
))
396 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
399 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
401 while ((error
= ERR_get_error()) != 0)
402 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
406 SSL_CTX_free(context
);
409 # elif defined(HAVE_GNUTLS)
410 conn
= (http_tls_t
*)(con
->http
.tls
);
411 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
413 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
416 case GNUTLS_E_SUCCESS
:
417 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
420 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
424 gnutls_deinit(conn
->session
);
425 gnutls_certificate_free_credentials(*credentials
);
429 # elif defined(HAVE_CDSASSL)
430 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
431 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
432 # endif /* HAVE_LIBSSL */
434 con
->http
.tls
= NULL
;
436 #endif /* HAVE_SSL */
439 * Close the socket and clear the file from the input set for select()...
442 if (con
->http
.fd
>= 0)
444 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
447 FD_CLR(con
->http
.fd
, InputSet
);
448 FD_CLR(con
->http
.fd
, OutputSet
);
452 if (con
->pipe_pid
!= 0)
454 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet...",
456 FD_CLR(con
->file
, InputSet
);
462 * Close the open data file...
466 kill(con
->pipe_pid
, SIGKILL
);
468 LogMessage(L_DEBUG2
, "CloseClient() %d Closing data file %d.",
469 con
->http
.fd
, con
->file
);
470 LogMessage(L_DEBUG2
, "CloseClient() %d Removing fd %d from InputSet.",
471 con
->http
.fd
, con
->file
);
473 FD_CLR(con
->file
, InputSet
);
480 ippDelete(con
->request
);
486 ippDelete(con
->response
);
487 con
->response
= NULL
;
492 cupsLangFree(con
->language
);
493 con
->language
= NULL
;
497 * Re-enable new client connections if we are going back under the
501 if (NumClients
== MaxClients
)
505 * Compact the list of clients as necessary...
510 if (con
< (Clients
+ NumClients
))
511 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
516 * 'EncryptClient()' - Enable encryption for the client...
519 int /* O - 1 on success, 0 on error */
520 EncryptClient(client_t
*con
) /* I - Client to encrypt */
522 #if defined HAVE_LIBSSL
523 SSL_CTX
*context
; /* Context for encryption */
524 SSL
*conn
; /* Connection for encryption */
525 unsigned long error
; /* Error code */
529 * Create the SSL context and accept the connection...
532 context
= SSL_CTX_new(SSLv23_server_method());
534 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
535 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
537 conn
= SSL_new(context
);
539 SSL_set_fd(conn
, con
->http
.fd
);
540 if (SSL_accept(conn
) != 1)
542 while ((error
= ERR_get_error()) != 0)
543 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
545 SSL_CTX_free(context
);
550 con
->http
.tls
= conn
;
553 #elif defined(HAVE_GNUTLS)
554 http_tls_t
*conn
; /* TLS session object */
555 int error
; /* Error code */
556 gnutls_certificate_server_credentials
*credentials
;
557 /* TLS credentials */
560 * Create the SSL object and perform the SSL handshake...
563 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
568 credentials
= (gnutls_certificate_server_credentials
*)
569 malloc(sizeof(gnutls_certificate_server_credentials
));
570 if (credentials
== NULL
)
576 gnutls_certificate_allocate_credentials(credentials
);
577 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
578 ServerKey
, GNUTLS_X509_FMT_PEM
);
580 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
581 gnutls_set_default_priority(conn
->session
);
582 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
583 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
585 error
= gnutls_handshake(conn
->session
);
587 if (error
!= GNUTLS_E_SUCCESS
)
589 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
590 gnutls_deinit(conn
->session
);
591 gnutls_certificate_free_credentials(*credentials
);
597 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
600 conn
->credentials
= credentials
;
601 con
->http
.tls
= conn
;
604 #elif defined(HAVE_CDSASSL)
605 OSStatus error
; /* Error info */
606 SSLContextRef conn
; /* New connection */
607 SSLProtocol tryVersion
; /* Protocol version */
608 const char *hostName
; /* Local hostname */
609 int allowExpired
; /* Allow expired certificates? */
610 int allowAnyRoot
; /* Allow any root certificate? */
611 SSLProtocol
*negVersion
; /* Negotiated protocol version */
612 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
613 CFArrayRef
*peerCerts
; /* Certificates */
617 error
= SSLNewContext(true, &conn
);
622 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
625 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
628 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
632 hostName
= ServerName
; /* MRS: ??? */
633 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
636 /* have to do these options befor setting server certs */
637 if (!error
&& allowExpired
)
638 error
= SSLSetAllowsExpiredCerts(conn
, true);
640 if (!error
&& allowAnyRoot
)
641 error
= SSLSetAllowsAnyRoot(conn
, true);
643 if (!error
&& ServerCertificatesArray
!= NULL
)
644 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
647 * Perform SSL/TLS handshake
652 error
= SSLHandshake(conn
);
654 while (error
== errSSLWouldBlock
);
658 LogMessage(L_ERROR
, "EncryptClient: %d", error
);
660 con
->http
.error
= error
;
661 con
->http
.status
= HTTP_ERROR
;
664 SSLDisposeContext(conn
);
669 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
671 con
->http
.tls
= conn
;
676 #endif /* HAVE_GNUTLS */
681 * 'IsCGI()' - Is the resource a CGI script/program?
684 int /* O - 1 = CGI, 0 = file */
685 IsCGI(client_t
*con
, /* I - Client connection */
686 const char *filename
, /* I - Real filename */
687 struct stat
*filestats
, /* I - File information */
688 mime_type_t
*type
) /* I - MIME type */
690 const char *options
; /* Options on URL */
693 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
694 con
, filename
, filestats
, type
? type
->super
: "unknown",
695 type
? type
->type
: "unknown");
698 * Get the options, if any...
701 if ((options
= strchr(con
->uri
, '?')) != NULL
)
705 * Check for known types...
708 if (strcasecmp(type
->super
, "application"))
710 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
714 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
715 (filestats
->st_mode
& 0111))
718 * "application/x-httpd-cgi" is a CGI script.
721 SetString(&con
->command
, filename
);
723 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
726 SetStringf(&con
->options
, "%s %s", filename
, options
);
728 SetStringf(&con
->options
, "%s", filename
);
730 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
731 con
->command
, con
->options
);
736 else if (!strcasecmp(type
->type
, "x-httpd-java"))
739 * "application/x-httpd-java" is a Java servlet.
742 SetString(&con
->command
, CUPS_JAVA
);
745 SetStringf(&con
->options
, "java %s %s", filename
, options
);
747 SetStringf(&con
->options
, "java %s", filename
);
749 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
750 con
->command
, con
->options
);
754 #endif /* HAVE_JAVA */
756 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
759 * "application/x-httpd-perl" is a Perl page.
762 SetString(&con
->command
, CUPS_PERL
);
765 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
767 SetStringf(&con
->options
, "perl %s", filename
);
769 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
770 con
->command
, con
->options
);
774 #endif /* HAVE_PERL */
776 else if (!strcasecmp(type
->type
, "x-httpd-php"))
779 * "application/x-httpd-php" is a PHP page.
782 SetString(&con
->command
, CUPS_PHP
);
785 SetStringf(&con
->options
, "php %s %s", filename
, options
);
787 SetStringf(&con
->options
, "php %s", filename
);
789 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
790 con
->command
, con
->options
);
794 #endif /* HAVE_PHP */
796 else if (!strcasecmp(type
->type
, "x-httpd-python"))
799 * "application/x-httpd-python" is a Python page.
802 SetString(&con
->command
, CUPS_PYTHON
);
805 SetStringf(&con
->options
, "python %s %s", filename
, options
);
807 SetStringf(&con
->options
, "python %s", filename
);
809 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
810 con
->command
, con
->options
);
814 #endif /* HAVE_PYTHON */
816 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
823 * 'ReadClient()' - Read data from a client.
826 int /* O - 1 on success, 0 on error */
827 ReadClient(client_t
*con
) /* I - Client to read from */
829 char line
[32768], /* Line from client... */
830 operation
[64], /* Operation code from socket */
831 version
[64], /* HTTP version number string */
832 locale
[64], /* Locale */
833 *ptr
; /* Pointer into strings */
834 int major
, minor
; /* HTTP version numbers */
835 http_status_t status
; /* Transfer status */
836 ipp_state_t ipp_state
; /* State of IPP transfer */
837 int bytes
; /* Number of bytes to POST */
838 char *filename
; /* Name of file for GET/HEAD */
839 char buf
[1024]; /* Buffer for real filename */
840 struct stat filestats
; /* File information */
841 mime_type_t
*type
; /* MIME type of file */
842 printer_t
*p
; /* Printer */
843 location_t
*best
; /* Best match for authentication */
844 static unsigned request_id
= 0; /* Request ID for temp files */
847 status
= HTTP_CONTINUE
;
849 LogMessage(L_DEBUG2
, "ReadClient() %d, used=%d", con
->http
.fd
,
858 switch (con
->http
.state
)
862 * See if we've received a request line...
865 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
872 * Ignore blank request lines...
879 * Clear other state variables...
882 httpClearFields(HTTP(con
));
884 con
->http
.activity
= time(NULL
);
885 con
->http
.version
= HTTP_1_0
;
886 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
887 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
888 con
->http
.data_remaining
= 0;
889 con
->operation
= HTTP_WAITING
;
893 con
->username
[0] = '\0';
894 con
->password
[0] = '\0';
897 ClearString(&con
->command
);
898 ClearString(&con
->options
);
900 if (con
->language
!= NULL
)
902 cupsLangFree(con
->language
);
903 con
->language
= NULL
;
907 * Grab the request line...
910 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
913 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
914 SendError(con
, HTTP_BAD_REQUEST
);
918 con
->http
.version
= HTTP_0_9
;
921 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
923 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
924 SendError(con
, HTTP_BAD_REQUEST
);
931 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
932 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
933 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
935 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
939 SendError(con
, HTTP_NOT_SUPPORTED
);
947 * Handle full URLs in the request line...
950 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
952 char method
[HTTP_MAX_URI
], /* Method/scheme */
953 userpass
[HTTP_MAX_URI
], /* Username:password */
954 hostname
[HTTP_MAX_URI
], /* Hostname */
955 resource
[HTTP_MAX_URI
]; /* Resource path */
956 int port
; /* Port number */
960 * Separate the URI into its components...
963 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
966 * Only allow URIs with the servername, localhost, or an IP
970 if (strcasecmp(hostname
, ServerName
) &&
971 strcasecmp(hostname
, "localhost") &&
972 !isdigit(hostname
[0]))
975 * Nope, we don't do proxies...
978 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
979 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
985 * Copy the resource portion back into the URI; both resource and
986 * con->uri are HTTP_MAX_URI bytes in size...
989 strcpy(con
->uri
, resource
);
993 * Process the request...
996 if (strcmp(operation
, "GET") == 0)
997 con
->http
.state
= HTTP_GET
;
998 else if (strcmp(operation
, "PUT") == 0)
999 con
->http
.state
= HTTP_PUT
;
1000 else if (strcmp(operation
, "POST") == 0)
1001 con
->http
.state
= HTTP_POST
;
1002 else if (strcmp(operation
, "DELETE") == 0)
1003 con
->http
.state
= HTTP_DELETE
;
1004 else if (strcmp(operation
, "TRACE") == 0)
1005 con
->http
.state
= HTTP_TRACE
;
1006 else if (strcmp(operation
, "OPTIONS") == 0)
1007 con
->http
.state
= HTTP_OPTIONS
;
1008 else if (strcmp(operation
, "HEAD") == 0)
1009 con
->http
.state
= HTTP_HEAD
;
1012 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1013 SendError(con
, HTTP_BAD_REQUEST
);
1014 ShutdownClient(con
);
1018 con
->start
= time(NULL
);
1019 con
->operation
= con
->http
.state
;
1021 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
1022 operation
, con
->uri
,
1023 con
->http
.version
/ 100, con
->http
.version
% 100);
1025 con
->http
.status
= HTTP_OK
;
1035 * Parse incoming parameters until the status changes...
1038 status
= httpUpdate(HTTP(con
));
1040 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1042 SendError(con
, HTTP_BAD_REQUEST
);
1043 ShutdownClient(con
);
1049 break; /* Anti-compiler-warning-code */
1053 * Handle new transfers...
1056 if (status
== HTTP_OK
)
1058 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1061 * Figure out the locale from the Accept-Language and Content-Type
1065 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1068 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1071 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1074 * Combine language and charset, and trim any extra params in the
1078 snprintf(locale
, sizeof(locale
), "%s.%s",
1079 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1081 if ((ptr
= strchr(locale
, ',')) != NULL
)
1085 snprintf(locale
, sizeof(locale
), "%s.%s",
1086 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1088 con
->language
= cupsLangGet(locale
);
1091 con
->language
= cupsLangGet(DefaultLocale
);
1095 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1097 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1099 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1100 con
->http
.version
>= HTTP_1_1
)
1103 * HTTP/1.1 and higher require the "Host:" field...
1106 if (!SendError(con
, HTTP_BAD_REQUEST
))
1112 else if (con
->operation
== HTTP_OPTIONS
)
1115 * Do OPTIONS command...
1118 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1119 best
->type
!= AUTH_NONE
)
1121 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1128 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1129 con
->http
.tls
== NULL
)
1133 * Do encryption stuff...
1136 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1142 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1143 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1144 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1145 httpPrintf(HTTP(con
), "\r\n");
1149 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1154 #endif /* HAVE_SSL */
1157 if (con
->http
.expect
)
1159 /**** TODO: send expected header ****/
1162 if (!SendHeader(con
, HTTP_OK
, NULL
))
1168 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1169 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1170 httpPrintf(HTTP(con
), "\r\n");
1172 else if (strstr(con
->uri
, "..") != NULL
)
1175 * Protect against malicious users!
1178 if (!SendError(con
, HTTP_FORBIDDEN
))
1186 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1187 con
->http
.tls
== NULL
)
1191 * Do encryption stuff...
1194 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1200 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1201 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1202 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1203 httpPrintf(HTTP(con
), "\r\n");
1207 status
= IsAuthorized(con
);
1209 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1214 #endif /* HAVE_SSL */
1217 if (status
!= HTTP_OK
)
1219 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1221 SendError(con
, status
);
1222 ShutdownClient(con
);
1226 if (con
->http
.expect
)
1228 /**** TODO: send expected header ****/
1231 switch (con
->http
.state
)
1233 case HTTP_GET_SEND
:
1234 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1235 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1238 * Send PPD file - get the real printer name since printer
1239 * names are not case sensitive but filenames can be...
1242 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1244 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1245 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1248 if (!SendError(con
, HTTP_NOT_FOUND
))
1258 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1259 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1260 strncmp(con
->uri
, "/printers", 9) == 0 ||
1261 strncmp(con
->uri
, "/classes", 8) == 0 ||
1262 strncmp(con
->uri
, "/jobs", 5) == 0)
1265 * Send CGI output...
1268 if (strncmp(con
->uri
, "/admin", 6) == 0)
1270 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1271 SetString(&con
->options
, con
->uri
+ 6);
1273 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1275 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1276 SetString(&con
->options
, con
->uri
+ 9);
1278 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1280 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1281 SetString(&con
->options
, con
->uri
+ 8);
1285 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1286 SetString(&con
->options
, con
->uri
+ 5);
1289 if (con
->options
[0] == '/')
1290 cups_strcpy(con
->options
, con
->options
+ 1);
1292 if (!SendCommand(con
, con
->command
, con
->options
))
1294 if (!SendError(con
, HTTP_NOT_FOUND
))
1301 LogRequest(con
, HTTP_OK
);
1303 if (con
->http
.version
<= HTTP_1_0
)
1304 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1306 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1307 (strchr(con
->uri
+ 12, '/') != NULL
||
1308 strlen(con
->uri
) == 12))
1311 * GET can only be done to configuration files under
1315 if (!SendError(con
, HTTP_FORBIDDEN
))
1329 if ((filename
= get_file(con
, &filestats
, buf
,
1330 sizeof(buf
))) == NULL
)
1332 if (!SendError(con
, HTTP_NOT_FOUND
))
1341 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1343 if (IsCGI(con
, filename
, &filestats
, type
))
1345 if (!SendCommand(con
, con
->command
, con
->options
))
1347 if (!SendError(con
, HTTP_NOT_FOUND
))
1354 LogRequest(con
, HTTP_OK
);
1356 if (con
->http
.version
<= HTTP_1_0
)
1357 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1361 if (!check_if_modified(con
, &filestats
))
1363 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1372 strcpy(line
, "text/plain");
1374 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1376 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1385 case HTTP_POST_RECV
:
1387 * See if the POST request includes a Content-Length field, and if
1388 * so check the length against any limits that are set...
1391 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1392 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1394 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1395 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1399 * Request too large...
1402 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1410 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1413 * Negative content lengths are invalid!
1416 if (!SendError(con
, HTTP_BAD_REQUEST
))
1426 * See what kind of POST request this is; for IPP requests the
1427 * content-type field will be "application/ipp"...
1430 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1431 con
->request
= ippNew();
1432 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1433 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1434 strncmp(con
->uri
, "/printers", 9) == 0 ||
1435 strncmp(con
->uri
, "/classes", 8) == 0 ||
1436 strncmp(con
->uri
, "/jobs", 5) == 0)
1442 if (strncmp(con
->uri
, "/admin", 6) == 0)
1444 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1445 SetString(&con
->options
, con
->uri
+ 6);
1447 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1449 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1450 SetString(&con
->options
, con
->uri
+ 9);
1452 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1454 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1455 SetString(&con
->options
, con
->uri
+ 8);
1459 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1460 SetString(&con
->options
, con
->uri
+ 5);
1463 if (con
->options
[0] == '/')
1464 cups_strcpy(con
->options
, con
->options
+ 1);
1466 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
1467 con
->http
.fd
, con
->command
, con
->options
);
1469 if (con
->http
.version
<= HTTP_1_0
)
1470 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1478 if ((filename
= get_file(con
, &filestats
, buf
,
1479 sizeof(buf
))) == NULL
)
1481 if (!SendError(con
, HTTP_NOT_FOUND
))
1490 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1492 if (!IsCGI(con
, filename
, &filestats
, type
))
1495 * Only POST to CGI's...
1498 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1507 case HTTP_PUT_RECV
:
1509 * Validate the resource name...
1512 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1513 strchr(con
->uri
+ 12, '/') != NULL
||
1514 strlen(con
->uri
) == 12)
1517 * PUT can only be done to configuration files under
1521 if (!SendError(con
, HTTP_FORBIDDEN
))
1531 * See if the PUT request includes a Content-Length field, and if
1532 * so check the length against any limits that are set...
1535 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1536 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1538 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1539 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1543 * Request too large...
1546 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1554 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1557 * Negative content lengths are invalid!
1560 if (!SendError(con
, HTTP_BAD_REQUEST
))
1570 * Open a temporary file to hold the request...
1573 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1574 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1575 fchmod(con
->file
, 0640);
1576 fchown(con
->file
, getuid(), Group
);
1578 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1579 con
->filename
, con
->file
);
1583 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1593 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1594 ShutdownClient(con
);
1598 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1599 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1602 * Send PPD file - get the real printer name since printer
1603 * names are not case sensitive but filenames can be...
1606 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1608 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1609 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1612 if (!SendError(con
, HTTP_NOT_FOUND
))
1622 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1623 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1624 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1625 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1626 strncmp(con
->uri
, "/jobs/", 6) == 0)
1632 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1638 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1644 LogRequest(con
, HTTP_OK
);
1646 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1647 (strchr(con
->uri
+ 12, '/') != NULL
||
1648 strlen(con
->uri
) == 12))
1651 * HEAD can only be done to configuration files under
1655 if (!SendError(con
, HTTP_FORBIDDEN
))
1663 else if ((filename
= get_file(con
, &filestats
, buf
,
1664 sizeof(buf
))) == NULL
)
1666 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1672 LogRequest(con
, HTTP_NOT_FOUND
);
1674 else if (!check_if_modified(con
, &filestats
))
1676 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1682 LogRequest(con
, HTTP_NOT_MODIFIED
);
1690 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1692 strcpy(line
, "text/plain");
1694 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1696 if (!SendHeader(con
, HTTP_OK
, line
))
1702 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1703 httpGetDateString(filestats
.st_mtime
)) < 0)
1709 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1710 (unsigned long)filestats
.st_size
) < 0)
1716 LogRequest(con
, HTTP_OK
);
1719 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1725 con
->http
.state
= HTTP_WAITING
;
1729 break; /* Anti-compiler-warning-code */
1735 * Handle any incoming data...
1738 switch (con
->http
.state
)
1740 case HTTP_PUT_RECV
:
1741 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1743 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1744 con
->http
.data_remaining
, con
->file
);
1746 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1753 con
->bytes
+= bytes
;
1755 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1756 con
->http
.fd
, bytes
, con
->file
);
1758 if (write(con
->file
, line
, bytes
) < bytes
)
1760 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1761 bytes
, con
->filename
, strerror(errno
));
1763 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1768 unlink(con
->filename
);
1769 ClearString(&con
->filename
);
1771 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1779 if (con
->http
.state
== HTTP_WAITING
)
1782 * End of file, see how big it is...
1785 fstat(con
->file
, &filestats
);
1787 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1788 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1793 if (filestats
.st_size
> MaxRequestSize
&&
1797 * Request is too big; remove it and send an error...
1800 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1801 con
->http
.fd
, con
->filename
);
1802 unlink(con
->filename
);
1803 ClearString(&con
->filename
);
1805 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1813 * Install the configuration file...
1816 status
= install_conf_file(con
);
1819 * Return the status to the client...
1822 if (!SendError(con
, status
))
1830 case HTTP_POST_RECV
:
1831 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1833 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1834 con
->http
.data_remaining
, con
->file
);
1836 if (con
->request
!= NULL
)
1839 * Grab any request data from the connection...
1842 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1844 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1847 if (!SendError(con
, HTTP_BAD_REQUEST
))
1853 ShutdownClient(con
);
1856 else if (ipp_state
!= IPP_DATA
)
1859 con
->bytes
+= ippLength(con
->request
);
1862 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
1865 * Create a file as needed for the request data...
1868 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1869 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1870 fchmod(con
->file
, 0640);
1871 fchown(con
->file
, getuid(), Group
);
1873 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1874 con
->filename
, con
->file
);
1878 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1886 if (con
->http
.state
!= HTTP_POST_SEND
)
1888 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1895 con
->bytes
+= bytes
;
1897 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1898 con
->http
.fd
, bytes
, con
->file
);
1900 if (write(con
->file
, line
, bytes
) < bytes
)
1902 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1903 bytes
, con
->filename
, strerror(errno
));
1905 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1910 unlink(con
->filename
);
1911 ClearString(&con
->filename
);
1913 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1920 else if (con
->http
.state
== HTTP_POST_RECV
)
1924 else if (con
->http
.state
!= HTTP_POST_SEND
)
1931 if (con
->http
.state
== HTTP_POST_SEND
)
1935 fstat(con
->file
, &filestats
);
1937 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1938 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1943 if (filestats
.st_size
> MaxRequestSize
&&
1947 * Request is too big; remove it and send an error...
1950 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1951 con
->http
.fd
, con
->filename
);
1952 unlink(con
->filename
);
1953 ClearString(&con
->filename
);
1958 * Delete any IPP request data...
1961 ippDelete(con
->request
);
1962 con
->request
= NULL
;
1965 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1974 if (!SendCommand(con
, con
->command
, con
->options
))
1976 if (!SendError(con
, HTTP_NOT_FOUND
))
1983 LogRequest(con
, HTTP_OK
);
1988 return (ProcessIPPRequest(con
));
1993 break; /* Anti-compiler-warning-code */
1996 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2007 * 'SendCommand()' - Send output from a command via HTTP.
2011 SendCommand(client_t
*con
,
2019 fd
= open(con
->filename
, O_RDONLY
);
2021 fd
= open("/dev/null", O_RDONLY
);
2023 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
2027 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
2029 LogMessage(L_DEBUG
, "SendCommand() %d file=%d", con
->http
.fd
, con
->file
);
2031 if (con
->pipe_pid
== 0)
2034 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2036 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
2037 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
2040 FD_SET(con
->file
, InputSet
);
2041 FD_SET(con
->http
.fd
, OutputSet
);
2043 if (!SendHeader(con
, HTTP_OK
, NULL
))
2046 if (con
->http
.version
== HTTP_1_1
)
2048 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2050 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2054 con
->got_fields
= 0;
2062 * 'SendError()' - Send an error message via HTTP.
2065 int /* O - 1 if successful, 0 otherwise */
2066 SendError(client_t
*con
, /* I - Connection */
2067 http_status_t code
) /* I - Error code */
2069 char message
[1024]; /* Message for user */
2073 * Put the request in the access_log file...
2076 if (con
->operation
> HTTP_WAITING
)
2077 LogRequest(con
, code
);
2079 LogMessage(L_DEBUG
, "SendError() %d code=%d", con
->http
.fd
, code
);
2082 * To work around bugs in some proxies, don't use Keep-Alive for some
2086 if (code
>= HTTP_BAD_REQUEST
)
2087 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2090 * Send an error message back to the client. If the error code is a
2091 * 400 or 500 series, make sure the message contains some text, too!
2094 if (!SendHeader(con
, code
, NULL
))
2098 if (code
== HTTP_UPGRADE_REQUIRED
)
2099 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2102 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2104 #endif /* HAVE_SSL */
2106 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2107 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2109 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2113 if (code
>= HTTP_BAD_REQUEST
)
2116 * Send a human-readable error message.
2119 snprintf(message
, sizeof(message
),
2120 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2121 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2122 code
, httpStatus(code
), httpStatus(code
),
2123 con
->language
? con
->language
->messages
[code
] :
2126 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
2128 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2129 (int)strlen(message
)) < 0)
2131 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2133 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2136 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2139 con
->http
.state
= HTTP_WAITING
;
2146 * 'SendFile()' - Send a file via HTTP.
2150 SendFile(client_t
*con
,
2154 struct stat
*filestats
)
2156 con
->file
= open(filename
, O_RDONLY
);
2158 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
2163 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2167 if (!SendHeader(con
, code
, type
))
2170 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2172 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2173 (unsigned long)filestats
->st_size
) < 0)
2175 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2178 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2180 FD_SET(con
->http
.fd
, OutputSet
);
2187 * 'SendHeader()' - Send an HTTP request.
2190 int /* O - 1 on success, 0 on failure */
2191 SendHeader(client_t
*con
, /* I - Client to send to */
2192 http_status_t code
, /* I - HTTP status code */
2193 char *type
) /* I - MIME type of document */
2195 location_t
*loc
; /* Authentication location */
2198 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2199 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2201 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2203 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
2205 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2207 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2209 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2212 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2213 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2216 if (code
== HTTP_UNAUTHORIZED
)
2219 * This already succeeded in IsAuthorized...
2222 loc
= FindBest(con
->uri
, con
->http
.state
);
2224 if (loc
->type
!= AUTH_DIGEST
)
2226 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2231 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
2232 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2236 if (con
->language
!= NULL
)
2238 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2239 con
->language
->language
) < 0)
2243 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
2244 cupsLangEncoding(con
->language
)) < 0)
2247 else if (type
!= NULL
)
2248 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2256 * 'ShutdownClient()' - Shutdown the receiving end of a connection.
2260 ShutdownClient(client_t
*con
) /* I - Client connection */
2263 * Shutdown the receiving end of the socket, since the client
2264 * still needs to read the error message...
2267 shutdown(con
->http
.fd
, 0);
2271 * Update the activity time so that we timeout after 30 seconds rather
2272 * then the current Timeout setting (300 by default). This prevents
2273 * some DoS situations...
2276 con
->http
.activity
= time(NULL
) - Timeout
+ 30;
2278 LogMessage(L_DEBUG2
, "ShutdownClient: Removing fd %d from InputSet...",
2281 FD_CLR(con
->http
.fd
, InputSet
);
2286 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2292 int bytes
; /* Number of bytes read */
2293 char *lineptr
, /* Pointer to end of line in buffer */
2294 *message
; /* Pointer to message text */
2295 int loglevel
; /* Log level for message */
2296 static int bufused
= 0; /* Number of bytes used in buffer */
2297 static char buffer
[1024]; /* Status buffer */
2300 if ((bytes
= read(CGIPipes
[0], buffer
+ bufused
,
2301 sizeof(buffer
) - bufused
- 1)) > 0)
2304 buffer
[bufused
] = '\0';
2305 lineptr
= strchr(buffer
, '\n');
2307 else if (bytes
< 0 && errno
== EINTR
)
2311 lineptr
= buffer
+ bufused
;
2315 if (bytes
== 0 && bufused
== 0)
2318 while (lineptr
!= NULL
)
2321 * Terminate each line and process it...
2327 * Figure out the logging level...
2330 if (strncmp(buffer
, "EMERG:", 6) == 0)
2333 message
= buffer
+ 6;
2335 else if (strncmp(buffer
, "ALERT:", 6) == 0)
2338 message
= buffer
+ 6;
2340 else if (strncmp(buffer
, "CRIT:", 5) == 0)
2343 message
= buffer
+ 5;
2345 else if (strncmp(buffer
, "ERROR:", 6) == 0)
2348 message
= buffer
+ 6;
2350 else if (strncmp(buffer
, "WARNING:", 8) == 0)
2353 message
= buffer
+ 8;
2355 else if (strncmp(buffer
, "NOTICE:", 6) == 0)
2357 loglevel
= L_NOTICE
;
2358 message
= buffer
+ 6;
2360 else if (strncmp(buffer
, "INFO:", 5) == 0)
2363 message
= buffer
+ 5;
2365 else if (strncmp(buffer
, "DEBUG:", 6) == 0)
2368 message
= buffer
+ 6;
2370 else if (strncmp(buffer
, "DEBUG2:", 7) == 0)
2372 loglevel
= L_DEBUG2
;
2373 message
= buffer
+ 7;
2375 else if (strncmp(buffer
, "PAGE:", 5) == 0)
2378 message
= buffer
+ 5;
2387 * Skip leading whitespace in the message...
2390 while (isspace(*message
))
2393 LogMessage(loglevel
, "[CGI] %s", message
);
2396 * Copy over the buffer data we've used up...
2399 strcpy(buffer
, lineptr
);
2400 bufused
-= lineptr
- buffer
;
2405 lineptr
= strchr(buffer
, '\n');
2411 * Fatal error on pipe - should never happen!
2414 LogMessage(L_ERROR
, "UpdateCGI: error reading from CGI error pipe - %s",
2421 * 'WriteClient()' - Write data to a client as needed.
2424 int /* O - 1 if success, 0 if fail */
2425 WriteClient(client_t
*con
) /* I - Client connection */
2427 int bytes
; /* Number of bytes written */
2428 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
2429 char *bufptr
; /* Pointer into buffer */
2430 ipp_state_t ipp_state
; /* IPP state value */
2433 if (con
->http
.state
!= HTTP_GET_SEND
&&
2434 con
->http
.state
!= HTTP_POST_SEND
)
2437 if (con
->response
!= NULL
)
2439 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2440 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2442 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
2444 if (con
->pipe_pid
&& !con
->got_fields
)
2447 * Inspect the data for Content-Type and other fields.
2452 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2453 if (*bufptr
== '\n')
2456 * Send line to client...
2459 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2463 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2464 LogMessage(L_DEBUG2
, "WriteClient() %d %s", con
->http
.fd
, buf
);
2470 bytes
-= (bufptr
- buf
);
2471 memcpy(buf
, bufptr
, bytes
+ 1);
2475 * See if the line was empty...
2478 if (con
->field_col
== 0)
2479 con
->got_fields
= 1;
2483 else if (*bufptr
!= '\r')
2486 if (bytes
> 0 && !con
->got_fields
)
2489 * Remaining text needs to go out...
2492 httpPrintf(HTTP(con
), "%s", buf
);
2494 con
->http
.activity
= time(NULL
);
2497 else if (bytes
== 0)
2499 con
->http
.activity
= time(NULL
);
2504 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2510 con
->bytes
+= bytes
;
2515 LogRequest(con
, HTTP_OK
);
2517 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2519 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2526 con
->http
.state
= HTTP_WAITING
;
2528 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from OutputSet...",
2531 FD_CLR(con
->http
.fd
, OutputSet
);
2535 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from InputSet...",
2537 FD_CLR(con
->file
, InputSet
);
2540 kill(con
->pipe_pid
, SIGTERM
);
2542 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
2543 con
->http
.fd
, con
->file
);
2552 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
2553 con
->http
.fd
, con
->filename
);
2554 unlink(con
->filename
);
2555 ClearString(&con
->filename
);
2558 if (con
->request
!= NULL
)
2560 ippDelete(con
->request
);
2561 con
->request
= NULL
;
2564 if (con
->response
!= NULL
)
2566 ippDelete(con
->response
);
2567 con
->response
= NULL
;
2570 ClearString(&con
->command
);
2571 ClearString(&con
->options
);
2573 if (!con
->http
.keep_alive
)
2581 LogMessage(L_DEBUG2
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
2583 con
->http
.activity
= time(NULL
);
2590 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2593 static int /* O - 1 if modified since */
2594 check_if_modified(client_t
*con
, /* I - Client connection */
2595 struct stat
*filestats
) /* I - File information */
2597 char *ptr
; /* Pointer into field */
2598 time_t date
; /* Time/date value */
2599 int size
; /* Size/length value */
2604 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2609 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
2612 while (*ptr
!= '\0')
2614 while (isspace(*ptr
) || *ptr
== ';')
2617 if (strncasecmp(ptr
, "length=", 7) == 0)
2622 while (isdigit(*ptr
))
2625 else if (isalpha(*ptr
))
2627 date
= httpGetDateTime(ptr
);
2628 while (*ptr
!= '\0' && *ptr
!= ';')
2633 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
2634 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2635 (int)filestats
->st_mtime
);
2637 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2638 (date
< filestats
->st_mtime
&& date
!= 0) ||
2639 (size
== 0 && date
== 0));
2644 * 'decode_auth()' - Decode an authorization string.
2648 decode_auth(client_t
*con
) /* I - Client to decode to */
2650 char *s
, /* Authorization string */
2651 value
[1024]; /* Value string */
2652 const char *username
; /* Certificate username */
2656 * Decode the string...
2659 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2661 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2664 if (strncmp(s
, "Basic", 5) == 0)
2670 httpDecode64(value
, s
);
2673 * Pull the username and password out...
2676 if ((s
= strchr(value
, ':')) == NULL
)
2678 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2679 con
->http
.fd
, value
);
2685 strlcpy(con
->username
, value
, sizeof(con
->username
));
2686 strlcpy(con
->password
, s
, sizeof(con
->password
));
2688 else if (strncmp(s
, "Local", 5) == 0)
2694 if ((username
= FindCert(s
)) != NULL
)
2695 strlcpy(con
->username
, username
, sizeof(con
->username
));
2697 else if (strncmp(s
, "Digest", 5) == 0)
2700 * Get the username and password from the Digest attributes...
2703 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2705 strlcpy(con
->username
, value
, sizeof(con
->username
));
2707 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2709 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2712 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2713 con
->http
.fd
, con
->username
);
2717 static char * /* O - Real filename */
2718 get_file(client_t
*con
, /* I - Client connection */
2719 struct stat
*filestats
, /* O - File information */
2720 char *filename
, /* IO - Filename buffer */
2721 int len
) /* I - Buffer length */
2723 int status
; /* Status of filesystem calls */
2724 char *ptr
; /* Pointer info filename */
2725 int plen
; /* Remaining length after pointer */
2729 * Need to add DocumentRoot global...
2732 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2733 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2734 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2735 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2736 else if (con
->language
!= NULL
)
2737 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2740 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2742 if ((ptr
= strchr(filename
, '?')) != NULL
)
2746 * Grab the status for this language; if there isn't a language-specific file
2747 * then fallback to the default one...
2750 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2753 * Drop the language prefix and try the current directory...
2756 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2757 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2759 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2761 if ((ptr
= strchr(filename
, '?')) != NULL
)
2764 status
= stat(filename
, filestats
);
2769 * If we're found a directory, get the index.html file instead...
2772 if (!status
&& S_ISDIR(filestats
->st_mode
))
2774 if (filename
[strlen(filename
) - 1] != '/')
2775 strlcat(filename
, "/", len
);
2777 ptr
= filename
+ strlen(filename
);
2778 plen
= len
- (ptr
- filename
);
2780 strlcpy(ptr
, "index.html", plen
);
2781 status
= stat(filename
, filestats
);
2786 strlcpy(ptr
, "index.class", plen
);
2787 status
= stat(filename
, filestats
);
2789 #endif /* HAVE_JAVA */
2794 strlcpy(ptr
, "index.pl", plen
);
2795 status
= stat(filename
, filestats
);
2797 #endif /* HAVE_PERL */
2802 strlcpy(ptr
, "index.php", plen
);
2803 status
= stat(filename
, filestats
);
2805 #endif /* HAVE_PHP */
2810 strlcpy(ptr
, "index.pyc", plen
);
2811 status
= stat(filename
, filestats
);
2816 strlcpy(ptr
, "index.py", plen
);
2817 status
= stat(filename
, filestats
);
2819 #endif /* HAVE_PYTHON */
2822 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2823 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2833 * 'install_conf_file()' - Install a configuration file.
2836 static http_status_t
/* O - Status */
2837 install_conf_file(client_t
*con
) /* I - Connection */
2839 cups_file_t
*in
, /* Input file */
2840 *out
; /* Output file */
2841 char buffer
[1024]; /* Copy buffer */
2842 int bytes
; /* Number of bytes */
2843 char conffile
[1024], /* Configuration filename */
2844 newfile
[1024], /* New config filename */
2845 oldfile
[1024]; /* Old config filename */
2846 struct stat confinfo
; /* Config file info */
2850 * First construct the filenames...
2853 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2854 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2855 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2857 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2860 * Get the owner, group, and permissions of the configuration file.
2861 * If it doesn't exist, assign it to the User and Group in the
2862 * cupsd.conf file with mode 0640 permissions.
2865 if (stat(conffile
, &confinfo
))
2867 confinfo
.st_uid
= User
;
2868 confinfo
.st_gid
= Group
;
2869 confinfo
.st_mode
= ConfigFilePerm
;
2873 * Open the request file and new config file...
2876 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2878 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2879 con
->filename
, strerror(errno
));
2880 return (HTTP_SERVER_ERROR
);
2883 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2886 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2887 newfile
, strerror(errno
));
2888 return (HTTP_SERVER_ERROR
);
2891 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2892 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2895 * Copy from the request to the new config file...
2898 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2899 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2901 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2902 newfile
, strerror(errno
));
2908 return (HTTP_SERVER_ERROR
);
2912 * Close the files...
2916 if (cupsFileClose(out
))
2918 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2919 newfile
, strerror(errno
));
2923 return (HTTP_SERVER_ERROR
);
2927 * Remove the request file...
2930 unlink(con
->filename
);
2931 ClearString(&con
->filename
);
2934 * Unlink the old backup, rename the current config file to the backup
2935 * filename, and rename the new config file to the config file name...
2938 if (unlink(oldfile
))
2939 if (errno
!= ENOENT
)
2941 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2942 oldfile
, strerror(errno
));
2946 return (HTTP_SERVER_ERROR
);
2949 if (rename(conffile
, oldfile
))
2950 if (errno
!= ENOENT
)
2952 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2953 conffile
, strerror(errno
));
2957 return (HTTP_SERVER_ERROR
);
2960 if (rename(newfile
, conffile
))
2962 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2963 newfile
, strerror(errno
));
2965 rename(oldfile
, conffile
);
2968 return (HTTP_SERVER_ERROR
);
2972 * If the cupsd.conf file was updated, set the NeedReload flag...
2975 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2976 NeedReload
= RELOAD_CUPSD
;
2978 NeedReload
= RELOAD_ALL
;
2980 ReloadTime
= time(NULL
);
2983 * Return that the file was created successfully...
2986 return (HTTP_CREATED
);
2991 * 'pipe_command()' - Pipe the output of a command to the remote client.
2994 static int /* O - Process ID */
2995 pipe_command(client_t
*con
, /* I - Client connection */
2996 int infile
, /* I - Standard input for command */
2997 int *outfile
, /* O - Standard output for command */
2998 char *command
, /* I - Command to run */
2999 char *options
) /* I - Options for command */
3001 int i
; /* Looping var */
3002 int pid
; /* Process ID */
3003 char *commptr
; /* Command string pointer */
3004 char *uriptr
; /* URI string pointer */
3005 int fd
; /* Looping var */
3006 int fds
[2]; /* Pipe FDs */
3007 int argc
; /* Number of arguments */
3008 int envc
; /* Number of environment variables */
3009 char argbuf
[10240], /* Argument buffer */
3010 *argv
[100], /* Argument strings */
3011 *envp
[100]; /* Environment variables */
3012 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3013 content_type
[1024], /* CONTENT_TYPE environment variable */
3014 cups_datadir
[1024], /* CUPS_DATADIR environment variable */
3015 cups_serverroot
[1024], /* CUPS_SERVERROOT environment variable */
3016 http_cookie
[1024], /* HTTP_COOKIE environment variable */
3017 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3018 ipp_port
[1024], /* IPP_PORT environment variable */
3019 lang
[1024], /* LANG environment variable */
3020 ld_library_path
[1024], /* LD_LIBRARY_PATH environment variable */
3021 ld_preload
[1024], /* LD_PRELOAD environment variable */
3022 dyld_library_path
[1024],/* DYLD_LIBRARY_PATH environment variable */
3023 shlib_path
[1024], /* SHLIB_PATH environment variable */
3024 nlspath
[1024], /* NLSPATH environment variable */
3025 query_string
[10240], /* QUERY_STRING env variable */
3026 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3027 remote_host
[1024], /* REMOTE_HOST environment variable */
3028 remote_user
[1024], /* REMOTE_USER environment variable */
3029 script_name
[1024], /* SCRIPT_NAME environment variable */
3030 server_name
[1024], /* SERVER_NAME environment variable */
3031 server_port
[1024], /* SERVER_PORT environment variable */
3032 tmpdir
[1024], /* TMPDIR environment variable */
3033 vg_args
[1024], /* VG_ARGS environment variable */
3034 ld_assume_kernel
[1024]; /* LD_ASSUME_KERNEL environment variable */
3035 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
3036 struct sigaction action
; /* POSIX signal handler */
3037 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
3038 static const char * const locale_encodings
[] =
3039 { /* Locale charset names */
3040 "ASCII", "ISO8859-1", "ISO8859-2", "ISO8859-3",
3041 "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7",
3042 "ISO8859-8", "ISO8859-9", "ISO8859-10", "UTF-8",
3043 "ISO8859-13", "ISO8859-14", "ISO8859-15", "CP874",
3044 "CP1250", "CP1251", "CP1252", "CP1253",
3045 "CP1254", "CP1255", "CP1256", "CP1257",
3046 "CP1258", "KOI8R", "KOI8U", "ISO8859-11",
3047 "ISO8859-16", "", "", "",
3058 "CP932", "CP936", "CP949", "CP950",
3059 "CP1361", "", "", "",
3076 "EUC-CN", "EUC-JP", "EUC-KR", "EUC-TW"
3081 * Copy the command string...
3084 strlcpy(argbuf
, options
, sizeof(argbuf
));
3087 * Parse the string; arguments can be separated by + and are terminated
3093 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
3094 if (*commptr
== ' ' || *commptr
== '+')
3098 while (*commptr
== ' ')
3101 if (*commptr
!= '\0')
3103 argv
[argc
] = commptr
;
3109 else if (*commptr
== '%')
3111 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3112 *commptr
= (commptr
[1] - '0') << 4;
3114 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3116 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3117 *commptr
|= commptr
[2] - '0';
3119 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3121 cups_strcpy(commptr
+ 1, commptr
+ 3);
3123 else if (*commptr
== '?')
3128 if (argv
[0][0] == '\0')
3129 argv
[0] = strrchr(command
, '/') + 1;
3132 * Setup the environment variables as needed...
3136 snprintf(lang
, sizeof(lang
), "LANG=%s.%s", con
->language
->language
,
3137 locale_encodings
[con
->language
->encoding
]);
3139 strcpy(lang
, "LANG=C");
3141 sprintf(ipp_port
, "IPP_PORT=%d", LocalPort
);
3143 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
3144 sprintf(server_port
, "SERVER_PORT=%d",
3145 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3147 #endif /* AF_INET6 */
3148 sprintf(server_port
, "SERVER_PORT=%d",
3149 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3151 if (strcmp(con
->http
.hostname
, "localhost") == 0)
3152 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
3154 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
3155 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
3156 strcpy(remote_addr
, "REMOTE_ADDR=");
3157 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3158 sizeof(remote_addr
) - 12);
3159 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3160 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
3161 snprintf(cups_datadir
, sizeof(cups_datadir
), "CUPS_DATADIR=%s", DataDir
);
3162 snprintf(cups_serverroot
, sizeof(cups_serverroot
), "CUPS_SERVERROOT=%s", ServerRoot
);
3166 envp
[envc
++] = "PATH=/bin:/usr/bin";
3167 envp
[envc
++] = "SERVER_SOFTWARE=CUPS/1.1";
3168 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3169 if (con
->http
.version
== HTTP_1_1
)
3170 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3171 else if (con
->http
.version
== HTTP_1_0
)
3172 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3174 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3175 envp
[envc
++] = "REDIRECT_STATUS=1";
3176 envp
[envc
++] = "CUPS_SERVER=localhost";
3177 envp
[envc
++] = ipp_port
;
3178 envp
[envc
++] = server_name
;
3179 envp
[envc
++] = server_port
;
3180 envp
[envc
++] = remote_addr
;
3181 envp
[envc
++] = remote_host
;
3182 envp
[envc
++] = remote_user
;
3183 envp
[envc
++] = lang
;
3185 envp
[envc
++] = tmpdir
;
3186 envp
[envc
++] = cups_datadir
;
3187 envp
[envc
++] = cups_serverroot
;
3189 if (getenv("VG_ARGS") != NULL
)
3191 snprintf(vg_args
, sizeof(vg_args
), "VG_ARGS=%s", getenv("VG_ARGS"));
3192 envp
[envc
++] = vg_args
;
3195 if (getenv("LD_ASSUME_KERNEL") != NULL
)
3197 snprintf(ld_assume_kernel
, sizeof(ld_assume_kernel
), "LD_ASSUME_KERNEL=%s",
3198 getenv("LD_ASSUME_KERNEL"));
3199 envp
[envc
++] = ld_assume_kernel
;
3202 if (getenv("LD_LIBRARY_PATH") != NULL
)
3204 snprintf(ld_library_path
, sizeof(ld_library_path
), "LD_LIBRARY_PATH=%s",
3205 getenv("LD_LIBRARY_PATH"));
3206 envp
[envc
++] = ld_library_path
;
3209 if (getenv("LD_PRELOAD") != NULL
)
3211 snprintf(ld_preload
, sizeof(ld_preload
), "LD_PRELOAD=%s",
3212 getenv("LD_PRELOAD"));
3213 envp
[envc
++] = ld_preload
;
3216 if (getenv("DYLD_LIBRARY_PATH") != NULL
)
3218 snprintf(dyld_library_path
, sizeof(dyld_library_path
), "DYLD_LIBRARY_PATH=%s",
3219 getenv("DYLD_LIBRARY_PATH"));
3220 envp
[envc
++] = dyld_library_path
;
3223 if (getenv("SHLIB_PATH") != NULL
)
3225 snprintf(shlib_path
, sizeof(shlib_path
), "SHLIB_PATH=%s",
3226 getenv("SHLIB_PATH"));
3227 envp
[envc
++] = shlib_path
;
3230 if (getenv("NLSPATH") != NULL
)
3232 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
3233 envp
[envc
++] = nlspath
;
3236 if (con
->http
.cookie
)
3238 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3240 envp
[envc
++] = http_cookie
;
3243 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3245 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3246 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3247 envp
[envc
++] = http_user_agent
;
3250 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3251 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3253 envp
[envc
++] = script_name
;
3255 if (con
->operation
== HTTP_GET
)
3257 for (i
= 0; i
< argc
; i
++)
3258 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3259 envp
[envc
++] = "REQUEST_METHOD=GET";
3264 * Add GET form variables after ?...
3269 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
3270 envp
[envc
++] = query_string
;
3275 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3276 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3277 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3279 envp
[envc
++] = "REQUEST_METHOD=POST";
3280 envp
[envc
++] = content_length
;
3281 envp
[envc
++] = content_type
;
3285 * Tell the CGI if we are using encryption...
3288 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3290 envp
[envc
++] = "HTTPS=ON";
3291 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
3296 if (LogLevel
== L_DEBUG2
)
3298 for (i
= 0; i
< argc
; i
++)
3299 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3300 for (i
= 0; i
< envc
; i
++)
3301 LogMessage(L_DEBUG2
, "envp[%d] = \"%s\"", i
, envp
[i
]);
3305 * Create a pipe for the output...
3310 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3311 argv
[0], strerror(errno
));
3316 * Block signals before forking...
3322 * Then execute the command...
3325 if ((pid
= fork()) == 0)
3328 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
3334 * Running as root, so change to a non-priviledged user...
3340 if (setgroups(1, &Group
))
3349 * Reset group membership to just the main one we belong to.
3352 setgroups(1, &Group
);
3356 * Update stdin/stdout/stderr...
3362 if (dup(infile
) < 0)
3367 if (dup(fds
[1]) < 0)
3374 * Close extra file descriptors...
3377 for (fd
= 3; fd
< MaxFDs
; fd
++)
3381 * Change umask to restrict permissions on created files...
3387 * Unblock signals before doing the exec...
3391 sigset(SIGTERM
, SIG_DFL
);
3392 sigset(SIGCHLD
, SIG_DFL
);
3393 #elif defined(HAVE_SIGACTION)
3394 memset(&action
, 0, sizeof(action
));
3396 sigemptyset(&action
.sa_mask
);
3397 action
.sa_handler
= SIG_DFL
;
3399 sigaction(SIGTERM
, &action
, NULL
);
3400 sigaction(SIGCHLD
, &action
, NULL
);
3402 signal(SIGTERM
, SIG_DFL
);
3403 signal(SIGCHLD
, SIG_DFL
);
3404 #endif /* HAVE_SIGSET */
3409 * Execute the pipe program; if an error occurs, exit with status 1...
3412 execve(command
, argv
, envp
);
3419 * Error - can't fork!
3422 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3432 * Fork successful - return the PID...
3435 AddCert(pid
, con
->username
);
3437 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3449 #if defined(HAVE_CDSASSL)
3451 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3454 static OSStatus
/* O - -1 on error, 0 on success */
3455 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3456 void *data
, /* I - Data buffer */
3457 size_t *dataLength
) /* IO - Number of bytes */
3459 ssize_t bytes
; /* Number of bytes read */
3462 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3465 *dataLength
= bytes
;
3474 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3477 static OSStatus
/* O - -1 on error, 0 on success */
3478 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3479 const void *data
, /* I - Data buffer */
3480 size_t *dataLength
) /* IO - Number of bytes */
3485 bytes
= write((int)connection
, data
, *dataLength
);
3488 *dataLength
= bytes
;
3494 #endif /* HAVE_CDSASSL */
3498 * End of "$Id: client.c,v 1.91.2.72 2003/09/17 19:24:09 mike Exp $".