2 * "$Id: client.c,v 1.91.2.83 2004/06/29 02:45:24 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-3142 USA
20 * Voice: (301) 373-9600
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 * UpdateCGI() - Read status messages from CGI scripts and programs.
37 * WriteClient() - Write data to a client as needed.
38 * check_if_modified() - Decode an "If-Modified-Since" line.
39 * decode_auth() - Decode an authorization string.
40 * get_file() - Get a filename and state info.
41 * install_conf_file() - Install a configuration file.
42 * pipe_command() - Pipe the output of a command to the remote client.
43 * CDSAReadFunc() - Read function for CDSA decryption code.
44 * CDSAWriteFunc() - Write function for CDSA encryption code.
48 * Include necessary headers...
51 #include <cups/http-private.h>
60 static int check_if_modified(client_t
*con
,
61 struct stat
*filestats
);
62 static void decode_auth(client_t
*con
);
63 static char *get_file(client_t
*con
, struct stat
*filestats
,
64 char *filename
, int len
);
65 static http_status_t
install_conf_file(client_t
*con
);
66 static int pipe_command(client_t
*con
, int infile
, int *outfile
,
67 char *command
, char *options
);
70 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
,
72 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
,
73 const void *data
, size_t *dataLength
);
74 #endif /* HAVE_CDSASSL */
78 * 'AcceptClient()' - Accept a new client.
82 AcceptClient(listener_t
*lis
) /* I - Listener socket */
84 int i
; /* Looping var */
85 int count
; /* Count of connections on a host */
86 int val
; /* Parameter value */
87 client_t
*con
; /* New client pointer */
88 const struct hostent
*host
; /* Host entry for address */
89 char *hostname
;/* Hostname for address */
90 http_addr_t temp
; /* Temporary address variable */
91 static time_t last_dos
= 0;
92 /* Time of last DoS attack */
95 LogMessage(L_DEBUG2
, "AcceptClient(lis=%p) %d NumClients = %d",
96 lis
, lis
->fd
, NumClients
);
99 * Make sure we don't have a full set of clients already...
102 if (NumClients
== MaxClients
)
106 * Get a pointer to the next available client...
109 con
= Clients
+ NumClients
;
111 memset(con
, 0, sizeof(client_t
));
112 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.
356 int /* O - 1 if partial close, 0 if fully closed */
357 CloseClient(client_t
*con
) /* I - Client to close */
359 int partial
; /* Do partial close for SSL? */
360 #if defined(HAVE_LIBSSL)
361 SSL_CTX
*context
; /* Context for encryption */
362 SSL
*conn
; /* Connection for encryption */
363 unsigned long error
; /* Error code */
364 #elif defined(HAVE_GNUTLS)
365 http_tls_t
*conn
; /* TLS connection information */
366 int error
; /* Error code */
367 gnutls_certificate_server_credentials
*credentials
;
368 /* TLS credentials */
369 #endif /* HAVE_GNUTLS */
372 LogMessage(L_DEBUG
, "CloseClient: %d", con
->http
.fd
);
378 * Shutdown encryption as needed...
386 conn
= (SSL
*)(con
->http
.tls
);
387 context
= SSL_get_SSL_CTX(conn
);
389 switch (SSL_shutdown(conn
))
392 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
395 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
397 while ((error
= ERR_get_error()) != 0)
398 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
402 SSL_CTX_free(context
);
405 # elif defined(HAVE_GNUTLS)
406 conn
= (http_tls_t
*)(con
->http
.tls
);
407 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
409 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
412 case GNUTLS_E_SUCCESS
:
413 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
416 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
420 gnutls_deinit(conn
->session
);
421 gnutls_certificate_free_credentials(*credentials
);
425 # elif defined(HAVE_CDSASSL)
426 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
427 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
428 # endif /* HAVE_LIBSSL */
430 con
->http
.tls
= NULL
;
432 #endif /* HAVE_SSL */
435 * Close the socket and clear the file from the input set for select()...
438 if (con
->http
.fd
> 0)
443 * Only do a partial close so that the encrypted client gets everything.
446 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from OutputSet...",
448 shutdown(con
->http
.fd
, 0);
449 FD_CLR(con
->http
.fd
, OutputSet
);
454 * Shut the socket down fully...
457 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
460 FD_CLR(con
->http
.fd
, InputSet
);
461 FD_CLR(con
->http
.fd
, OutputSet
);
466 if (con
->pipe_pid
!= 0)
469 * Stop any CGI process...
472 LogMessage(L_DEBUG2
, "CloseClient: %d Killing process ID %d...",
473 con
->http
.fd
, con
->pipe_pid
);
474 kill(con
->pipe_pid
, SIGKILL
);
479 if (FD_ISSET(con
->file
, InputSet
))
481 LogMessage(L_DEBUG2
, "CloseClient: %d Removing fd %d from InputSet...",
482 con
->http
.fd
, con
->file
);
483 FD_CLR(con
->file
, InputSet
);
486 LogMessage(L_DEBUG2
, "CloseClient: %d Closing data file %d.",
487 con
->http
.fd
, con
->file
);
499 if (con
->http
.input_set
)
500 free(con
->http
.input_set
);
502 httpClearCookie(HTTP(con
));
504 ClearString(&con
->filename
);
505 ClearString(&con
->command
);
506 ClearString(&con
->options
);
510 ippDelete(con
->request
);
516 ippDelete(con
->response
);
517 con
->response
= NULL
;
522 cupsLangFree(con
->language
);
523 con
->language
= NULL
;
527 * Re-enable new client connections if we are going back under the
531 if (NumClients
== MaxClients
)
535 * Compact the list of clients as necessary...
540 if (con
< (Clients
+ NumClients
))
541 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
549 * 'EncryptClient()' - Enable encryption for the client...
552 int /* O - 1 on success, 0 on error */
553 EncryptClient(client_t
*con
) /* I - Client to encrypt */
555 #if defined HAVE_LIBSSL
556 SSL_CTX
*context
; /* Context for encryption */
557 SSL
*conn
; /* Connection for encryption */
558 unsigned long error
; /* Error code */
562 * Create the SSL context and accept the connection...
565 context
= SSL_CTX_new(SSLv23_server_method());
567 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
568 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
570 conn
= SSL_new(context
);
572 SSL_set_fd(conn
, con
->http
.fd
);
573 if (SSL_accept(conn
) != 1)
575 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
578 while ((error
= ERR_get_error()) != 0)
579 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
581 SSL_CTX_free(context
);
586 LogMessage(L_DEBUG
, "EncryptClient: %d Connection from %s now encrypted.",
587 con
->http
.fd
, con
->http
.hostname
);
589 con
->http
.tls
= conn
;
592 #elif defined(HAVE_GNUTLS)
593 http_tls_t
*conn
; /* TLS session object */
594 int error
; /* Error code */
595 gnutls_certificate_server_credentials
*credentials
;
596 /* TLS credentials */
599 * Create the SSL object and perform the SSL handshake...
602 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
607 credentials
= (gnutls_certificate_server_credentials
*)
608 malloc(sizeof(gnutls_certificate_server_credentials
));
609 if (credentials
== NULL
)
611 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
613 LogMessage(L_ERROR
, "EncryptClient: %s", strerror(errno
));
619 gnutls_certificate_allocate_credentials(credentials
);
620 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
621 ServerKey
, GNUTLS_X509_FMT_PEM
);
623 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
624 gnutls_set_default_priority(conn
->session
);
625 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
626 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
628 error
= gnutls_handshake(conn
->session
);
630 if (error
!= GNUTLS_E_SUCCESS
)
632 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
634 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
636 gnutls_deinit(conn
->session
);
637 gnutls_certificate_free_credentials(*credentials
);
643 LogMessage(L_DEBUG
, "EncryptClient: %d Connection from %s now encrypted.",
644 con
->http
.fd
, con
->http
.hostname
);
646 conn
->credentials
= credentials
;
647 con
->http
.tls
= conn
;
650 #elif defined(HAVE_CDSASSL)
651 OSStatus error
; /* Error info */
652 SSLContextRef conn
; /* New connection */
653 SSLProtocol tryVersion
; /* Protocol version */
654 const char *hostName
; /* Local hostname */
655 int allowExpired
; /* Allow expired certificates? */
656 int allowAnyRoot
; /* Allow any root certificate? */
657 SSLProtocol
*negVersion
; /* Negotiated protocol version */
658 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
659 CFArrayRef
*peerCerts
; /* Certificates */
663 error
= SSLNewContext(true, &conn
);
668 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
671 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
674 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
678 hostName
= ServerName
; /* MRS: ??? */
679 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
682 /* have to do these options befor setting server certs */
683 if (!error
&& allowExpired
)
684 error
= SSLSetAllowsExpiredCerts(conn
, true);
686 if (!error
&& allowAnyRoot
)
687 error
= SSLSetAllowsAnyRoot(conn
, true);
689 if (!error
&& ServerCertificatesArray
!= NULL
)
690 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
693 * Perform SSL/TLS handshake
698 error
= SSLHandshake(conn
);
700 while (error
== errSSLWouldBlock
);
704 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
707 LogMessage(L_ERROR
, "EncryptClient: CDSA error code is %d", error
);
709 con
->http
.error
= error
;
710 con
->http
.status
= HTTP_ERROR
;
713 SSLDisposeContext(conn
);
718 LogMessage(L_DEBUG
, "EncryptClient: %d Connection from %s now encrypted.",
719 con
->http
.fd
, con
->http
.hostname
);
721 con
->http
.tls
= conn
;
726 #endif /* HAVE_GNUTLS */
731 * 'IsCGI()' - Is the resource a CGI script/program?
734 int /* O - 1 = CGI, 0 = file */
735 IsCGI(client_t
*con
, /* I - Client connection */
736 const char *filename
, /* I - Real filename */
737 struct stat
*filestats
, /* I - File information */
738 mime_type_t
*type
) /* I - MIME type */
740 const char *options
; /* Options on URL */
743 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
744 con
, filename
, filestats
, type
? type
->super
: "unknown",
745 type
? type
->type
: "unknown");
748 * Get the options, if any...
751 if ((options
= strchr(con
->uri
, '?')) != NULL
)
755 * Check for known types...
758 if (!type
|| strcasecmp(type
->super
, "application"))
760 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
764 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
765 (filestats
->st_mode
& 0111))
768 * "application/x-httpd-cgi" is a CGI script.
771 SetString(&con
->command
, filename
);
773 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
776 SetStringf(&con
->options
, "%s %s", filename
, options
);
778 SetStringf(&con
->options
, "%s", filename
);
780 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
781 con
->command
, con
->options
);
786 else if (!strcasecmp(type
->type
, "x-httpd-java"))
789 * "application/x-httpd-java" is a Java servlet.
792 SetString(&con
->command
, CUPS_JAVA
);
795 SetStringf(&con
->options
, "java %s %s", filename
, options
);
797 SetStringf(&con
->options
, "java %s", filename
);
799 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
800 con
->command
, con
->options
);
804 #endif /* HAVE_JAVA */
806 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
809 * "application/x-httpd-perl" is a Perl page.
812 SetString(&con
->command
, CUPS_PERL
);
815 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
817 SetStringf(&con
->options
, "perl %s", filename
);
819 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
820 con
->command
, con
->options
);
824 #endif /* HAVE_PERL */
826 else if (!strcasecmp(type
->type
, "x-httpd-php"))
829 * "application/x-httpd-php" is a PHP page.
832 SetString(&con
->command
, CUPS_PHP
);
835 SetStringf(&con
->options
, "php %s %s", filename
, options
);
837 SetStringf(&con
->options
, "php %s", filename
);
839 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
840 con
->command
, con
->options
);
844 #endif /* HAVE_PHP */
846 else if (!strcasecmp(type
->type
, "x-httpd-python"))
849 * "application/x-httpd-python" is a Python page.
852 SetString(&con
->command
, CUPS_PYTHON
);
855 SetStringf(&con
->options
, "python %s %s", filename
, options
);
857 SetStringf(&con
->options
, "python %s", filename
);
859 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
860 con
->command
, con
->options
);
864 #endif /* HAVE_PYTHON */
866 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
873 * 'ReadClient()' - Read data from a client.
876 int /* O - 1 on success, 0 on error */
877 ReadClient(client_t
*con
) /* I - Client to read from */
879 char line
[32768], /* Line from client... */
880 operation
[64], /* Operation code from socket */
881 version
[64], /* HTTP version number string */
882 locale
[64], /* Locale */
883 *ptr
; /* Pointer into strings */
884 int major
, minor
; /* HTTP version numbers */
885 http_status_t status
; /* Transfer status */
886 ipp_state_t ipp_state
; /* State of IPP transfer */
887 int bytes
; /* Number of bytes to POST */
888 char *filename
; /* Name of file for GET/HEAD */
889 char buf
[1024]; /* Buffer for real filename */
890 struct stat filestats
; /* File information */
891 mime_type_t
*type
; /* MIME type of file */
892 printer_t
*p
; /* Printer */
893 location_t
*best
; /* Best match for authentication */
894 static unsigned request_id
= 0; /* Request ID for temp files */
897 status
= HTTP_CONTINUE
;
899 LogMessage(L_DEBUG2
, "ReadClient: %d, used=%d, file=%d", con
->http
.fd
,
900 con
->http
.used
, con
->file
);
904 LogMessage(L_DEBUG2
, "ReadClient: http error seen...");
905 return (CloseClient(con
));
908 switch (con
->http
.state
)
912 * See if we've received a request line...
915 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
917 LogMessage(L_DEBUG2
, "ReadClient: httpGets returned EOF...");
918 return (CloseClient(con
));
922 * Ignore blank request lines...
929 * Clear other state variables...
932 httpClearFields(HTTP(con
));
934 con
->http
.activity
= time(NULL
);
935 con
->http
.version
= HTTP_1_0
;
936 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
937 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
938 con
->http
.data_remaining
= 0;
939 con
->operation
= HTTP_WAITING
;
944 con
->username
[0] = '\0';
945 con
->password
[0] = '\0';
948 ClearString(&con
->command
);
949 ClearString(&con
->options
);
951 if (con
->language
!= NULL
)
953 cupsLangFree(con
->language
);
954 con
->language
= NULL
;
958 * Grab the request line...
961 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
964 LogMessage(L_ERROR
, "Bad request line \"%s\" from %s!", line
,
966 SendError(con
, HTTP_BAD_REQUEST
);
967 return (CloseClient(con
));
969 con
->http
.version
= HTTP_0_9
;
972 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
974 LogMessage(L_ERROR
, "Bad request line \"%s\" from %s!", line
,
976 SendError(con
, HTTP_BAD_REQUEST
);
977 return (CloseClient(con
));
982 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
983 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
984 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
986 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
990 SendError(con
, HTTP_NOT_SUPPORTED
);
991 return (CloseClient(con
));
997 * Handle full URLs in the request line...
1000 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
1002 char method
[HTTP_MAX_URI
], /* Method/scheme */
1003 userpass
[HTTP_MAX_URI
], /* Username:password */
1004 hostname
[HTTP_MAX_URI
], /* Hostname */
1005 resource
[HTTP_MAX_URI
]; /* Resource path */
1006 int port
; /* Port number */
1010 * Separate the URI into its components...
1013 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
1016 * Only allow URIs with the servername, localhost, or an IP
1020 if (strcasecmp(hostname
, ServerName
) &&
1021 strcasecmp(hostname
, "localhost") &&
1022 !isdigit(hostname
[0]))
1025 * Nope, we don't do proxies...
1028 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
1029 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
1030 return (CloseClient(con
));
1034 * Copy the resource portion back into the URI; both resource and
1035 * con->uri are HTTP_MAX_URI bytes in size...
1038 strcpy(con
->uri
, resource
);
1042 * Process the request...
1045 if (strcmp(operation
, "GET") == 0)
1046 con
->http
.state
= HTTP_GET
;
1047 else if (strcmp(operation
, "PUT") == 0)
1048 con
->http
.state
= HTTP_PUT
;
1049 else if (strcmp(operation
, "POST") == 0)
1050 con
->http
.state
= HTTP_POST
;
1051 else if (strcmp(operation
, "DELETE") == 0)
1052 con
->http
.state
= HTTP_DELETE
;
1053 else if (strcmp(operation
, "TRACE") == 0)
1054 con
->http
.state
= HTTP_TRACE
;
1055 else if (strcmp(operation
, "OPTIONS") == 0)
1056 con
->http
.state
= HTTP_OPTIONS
;
1057 else if (strcmp(operation
, "HEAD") == 0)
1058 con
->http
.state
= HTTP_HEAD
;
1061 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1062 SendError(con
, HTTP_BAD_REQUEST
);
1063 return (CloseClient(con
));
1066 con
->start
= time(NULL
);
1067 con
->operation
= con
->http
.state
;
1069 LogMessage(L_DEBUG
, "ReadClient: %d %s %s HTTP/%d.%d", con
->http
.fd
,
1070 operation
, con
->uri
,
1071 con
->http
.version
/ 100, con
->http
.version
% 100);
1073 con
->http
.status
= HTTP_OK
;
1083 * Parse incoming parameters until the status changes...
1086 status
= httpUpdate(HTTP(con
));
1088 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1090 SendError(con
, HTTP_BAD_REQUEST
);
1091 return (CloseClient(con
));
1096 break; /* Anti-compiler-warning-code */
1100 * Handle new transfers...
1103 if (status
== HTTP_OK
)
1105 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1108 * Figure out the locale from the Accept-Language and Content-Type
1112 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1115 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1118 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1121 * Combine language and charset, and trim any extra params in the
1125 snprintf(locale
, sizeof(locale
), "%s.%s",
1126 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1128 if ((ptr
= strchr(locale
, ',')) != NULL
)
1132 snprintf(locale
, sizeof(locale
), "%s.%s",
1133 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1135 con
->language
= cupsLangGet(locale
);
1138 con
->language
= cupsLangGet(DefaultLocale
);
1142 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1144 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1146 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1147 con
->http
.version
>= HTTP_1_1
)
1150 * HTTP/1.1 and higher require the "Host:" field...
1153 if (!SendError(con
, HTTP_BAD_REQUEST
))
1154 return (CloseClient(con
));
1156 else if (con
->operation
== HTTP_OPTIONS
)
1159 * Do OPTIONS command...
1162 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1163 best
->type
!= AUTH_NONE
)
1165 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1166 return (CloseClient(con
));
1169 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1170 con
->http
.tls
== NULL
)
1174 * Do encryption stuff...
1177 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1178 return (CloseClient(con
));
1180 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1181 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1182 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1183 httpPrintf(HTTP(con
), "\r\n");
1187 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1188 return (CloseClient(con
));
1189 #endif /* HAVE_SSL */
1192 if (con
->http
.expect
)
1194 /**** TODO: send expected header ****/
1197 if (!SendHeader(con
, HTTP_OK
, NULL
))
1198 return (CloseClient(con
));
1200 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1201 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1202 httpPrintf(HTTP(con
), "\r\n");
1204 else if (strstr(con
->uri
, "..") != NULL
)
1207 * Protect against malicious users!
1210 if (!SendError(con
, HTTP_FORBIDDEN
))
1211 return (CloseClient(con
));
1215 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1216 con
->http
.tls
== NULL
)
1220 * Do encryption stuff...
1223 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1224 return (CloseClient(con
));
1226 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1227 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1228 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1229 httpPrintf(HTTP(con
), "\r\n");
1233 status
= IsAuthorized(con
);
1235 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1236 return (CloseClient(con
));
1237 #endif /* HAVE_SSL */
1240 if (status
!= HTTP_OK
)
1242 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1244 SendError(con
, status
);
1245 return (CloseClient(con
));
1248 if (con
->http
.expect
)
1250 /**** TODO: send expected header ****/
1253 switch (con
->http
.state
)
1255 case HTTP_GET_SEND
:
1256 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1257 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1260 * Send PPD file - get the real printer name since printer
1261 * names are not case sensitive but filenames can be...
1264 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1266 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1267 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1270 if (!SendError(con
, HTTP_NOT_FOUND
))
1271 return (CloseClient(con
));
1277 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1278 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1279 strncmp(con
->uri
, "/printers", 9) == 0 ||
1280 strncmp(con
->uri
, "/classes", 8) == 0 ||
1281 strncmp(con
->uri
, "/jobs", 5) == 0)
1284 * Send CGI output...
1287 if (strncmp(con
->uri
, "/admin", 6) == 0)
1289 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1290 SetString(&con
->options
, con
->uri
+ 6);
1292 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1294 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1295 SetString(&con
->options
, con
->uri
+ 9);
1297 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1299 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1300 SetString(&con
->options
, con
->uri
+ 8);
1304 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1305 SetString(&con
->options
, con
->uri
+ 5);
1308 if (con
->options
[0] == '/')
1309 cups_strcpy(con
->options
, con
->options
+ 1);
1311 if (!SendCommand(con
, con
->command
, con
->options
))
1313 if (!SendError(con
, HTTP_NOT_FOUND
))
1314 return (CloseClient(con
));
1317 LogRequest(con
, HTTP_OK
);
1319 if (con
->http
.version
<= HTTP_1_0
)
1320 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1322 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1323 (strchr(con
->uri
+ 12, '/') != NULL
||
1324 strlen(con
->uri
) == 12))
1327 * GET can only be done to configuration files under
1331 if (!SendError(con
, HTTP_FORBIDDEN
))
1332 return (CloseClient(con
));
1342 if ((filename
= get_file(con
, &filestats
, buf
,
1343 sizeof(buf
))) == NULL
)
1345 if (!SendError(con
, HTTP_NOT_FOUND
))
1346 return (CloseClient(con
));
1351 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1353 if (IsCGI(con
, filename
, &filestats
, type
))
1355 if (!SendCommand(con
, con
->command
, con
->options
))
1357 if (!SendError(con
, HTTP_NOT_FOUND
))
1358 return (CloseClient(con
));
1361 LogRequest(con
, HTTP_OK
);
1363 if (con
->http
.version
<= HTTP_1_0
)
1364 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1368 if (!check_if_modified(con
, &filestats
))
1370 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1371 return (CloseClient(con
));
1376 strcpy(line
, "text/plain");
1378 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1380 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1381 return (CloseClient(con
));
1386 case HTTP_POST_RECV
:
1388 * See if the POST request includes a Content-Length field, and if
1389 * so check the length against any limits that are set...
1392 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1393 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1395 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1396 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1400 * Request too large...
1403 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1404 return (CloseClient(con
));
1408 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1411 * Negative content lengths are invalid!
1414 if (!SendError(con
, HTTP_BAD_REQUEST
))
1415 return (CloseClient(con
));
1421 * See what kind of POST request this is; for IPP requests the
1422 * content-type field will be "application/ipp"...
1425 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1426 con
->request
= ippNew();
1427 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1428 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1429 strncmp(con
->uri
, "/printers", 9) == 0 ||
1430 strncmp(con
->uri
, "/classes", 8) == 0 ||
1431 strncmp(con
->uri
, "/jobs", 5) == 0)
1437 if (strncmp(con
->uri
, "/admin", 6) == 0)
1439 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1440 SetString(&con
->options
, con
->uri
+ 6);
1442 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1444 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1445 SetString(&con
->options
, con
->uri
+ 9);
1447 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1449 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1450 SetString(&con
->options
, con
->uri
+ 8);
1454 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1455 SetString(&con
->options
, con
->uri
+ 5);
1458 if (con
->options
[0] == '/')
1459 cups_strcpy(con
->options
, con
->options
+ 1);
1461 LogMessage(L_DEBUG2
, "ReadClient: %d command=\"%s\", options = \"%s\"",
1462 con
->http
.fd
, con
->command
, con
->options
);
1464 if (con
->http
.version
<= HTTP_1_0
)
1465 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1473 if ((filename
= get_file(con
, &filestats
, buf
,
1474 sizeof(buf
))) == NULL
)
1476 if (!SendError(con
, HTTP_NOT_FOUND
))
1477 return (CloseClient(con
));
1482 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1484 if (!IsCGI(con
, filename
, &filestats
, type
))
1487 * Only POST to CGI's...
1490 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1491 return (CloseClient(con
));
1496 case HTTP_PUT_RECV
:
1498 * Validate the resource name...
1501 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1502 strchr(con
->uri
+ 12, '/') != NULL
||
1503 strlen(con
->uri
) == 12)
1506 * PUT can only be done to configuration files under
1510 if (!SendError(con
, HTTP_FORBIDDEN
))
1511 return (CloseClient(con
));
1517 * See if the PUT request includes a Content-Length field, and if
1518 * so check the length against any limits that are set...
1521 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1522 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1524 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1525 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1529 * Request too large...
1532 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1533 return (CloseClient(con
));
1537 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1540 * Negative content lengths are invalid!
1543 if (!SendError(con
, HTTP_BAD_REQUEST
))
1544 return (CloseClient(con
));
1550 * Open a temporary file to hold the request...
1553 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1554 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1555 fchmod(con
->file
, 0640);
1556 fchown(con
->file
, RunUser
, Group
);
1558 LogMessage(L_DEBUG2
, "ReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1559 con
->filename
, con
->file
);
1563 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1564 return (CloseClient(con
));
1570 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1571 return (CloseClient(con
));
1574 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1575 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1578 * Send PPD file - get the real printer name since printer
1579 * names are not case sensitive but filenames can be...
1582 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1584 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1585 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1588 if (!SendError(con
, HTTP_NOT_FOUND
))
1589 return (CloseClient(con
));
1595 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1596 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1597 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1598 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1599 strncmp(con
->uri
, "/jobs/", 6) == 0)
1605 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1606 return (CloseClient(con
));
1608 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1609 return (CloseClient(con
));
1611 LogRequest(con
, HTTP_OK
);
1613 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1614 (strchr(con
->uri
+ 12, '/') != NULL
||
1615 strlen(con
->uri
) == 12))
1618 * HEAD can only be done to configuration files under
1622 if (!SendError(con
, HTTP_FORBIDDEN
))
1623 return (CloseClient(con
));
1627 else if ((filename
= get_file(con
, &filestats
, buf
,
1628 sizeof(buf
))) == NULL
)
1630 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1631 return (CloseClient(con
));
1633 LogRequest(con
, HTTP_NOT_FOUND
);
1635 else if (!check_if_modified(con
, &filestats
))
1637 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1638 return (CloseClient(con
));
1640 LogRequest(con
, HTTP_NOT_MODIFIED
);
1648 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1650 strcpy(line
, "text/plain");
1652 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1654 if (!SendHeader(con
, HTTP_OK
, line
))
1655 return (CloseClient(con
));
1657 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1658 httpGetDateString(filestats
.st_mtime
)) < 0)
1659 return (CloseClient(con
));
1661 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1662 (unsigned long)filestats
.st_size
) < 0)
1663 return (CloseClient(con
));
1665 LogRequest(con
, HTTP_OK
);
1668 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1669 return (CloseClient(con
));
1671 con
->http
.state
= HTTP_WAITING
;
1675 break; /* Anti-compiler-warning-code */
1681 * Handle any incoming data...
1684 switch (con
->http
.state
)
1686 case HTTP_PUT_RECV
:
1687 LogMessage(L_DEBUG2
, "ReadClient: %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1689 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1690 con
->http
.data_remaining
, con
->file
);
1692 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1693 return (CloseClient(con
));
1696 con
->bytes
+= bytes
;
1698 LogMessage(L_DEBUG2
, "ReadClient: %d writing %d bytes to %d",
1699 con
->http
.fd
, bytes
, con
->file
);
1701 if (write(con
->file
, line
, bytes
) < bytes
)
1703 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1704 bytes
, con
->filename
, strerror(errno
));
1706 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1711 unlink(con
->filename
);
1712 ClearString(&con
->filename
);
1714 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1715 return (CloseClient(con
));
1719 if (con
->http
.state
== HTTP_WAITING
)
1722 * End of file, see how big it is...
1725 fstat(con
->file
, &filestats
);
1727 LogMessage(L_DEBUG2
, "ReadClient: %d Closing data file %d, size = %d.",
1728 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1733 if (filestats
.st_size
> MaxRequestSize
&&
1737 * Request is too big; remove it and send an error...
1740 LogMessage(L_DEBUG2
, "ReadClient: %d Removing temp file %s",
1741 con
->http
.fd
, con
->filename
);
1742 unlink(con
->filename
);
1743 ClearString(&con
->filename
);
1745 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1746 return (CloseClient(con
));
1750 * Install the configuration file...
1753 status
= install_conf_file(con
);
1756 * Return the status to the client...
1759 if (!SendError(con
, status
))
1760 return (CloseClient(con
));
1764 case HTTP_POST_RECV
:
1765 LogMessage(L_DEBUG2
, "ReadClient: %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1767 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1768 con
->http
.data_remaining
, con
->file
);
1770 if (con
->request
!= NULL
)
1773 * Grab any request data from the connection...
1776 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1778 LogMessage(L_ERROR
, "ReadClient: %d IPP Read Error!",
1781 SendError(con
, HTTP_BAD_REQUEST
);
1782 return (CloseClient(con
));
1784 else if (ipp_state
!= IPP_DATA
)
1787 con
->bytes
+= ippLength(con
->request
);
1790 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1793 * Create a file as needed for the request data...
1796 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1797 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1798 fchmod(con
->file
, 0640);
1799 fchown(con
->file
, RunUser
, Group
);
1801 LogMessage(L_DEBUG2
, "ReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1802 con
->filename
, con
->file
);
1806 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1807 return (CloseClient(con
));
1811 if (con
->http
.state
!= HTTP_POST_SEND
)
1813 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1814 return (CloseClient(con
));
1817 con
->bytes
+= bytes
;
1819 LogMessage(L_DEBUG2
, "ReadClient: %d writing %d bytes to %d",
1820 con
->http
.fd
, bytes
, con
->file
);
1822 if (write(con
->file
, line
, bytes
) < bytes
)
1824 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1825 bytes
, con
->filename
, strerror(errno
));
1827 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1832 unlink(con
->filename
);
1833 ClearString(&con
->filename
);
1835 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1836 return (CloseClient(con
));
1839 else if (con
->http
.state
== HTTP_POST_RECV
)
1840 return (1); /* ??? */
1841 else if (con
->http
.state
!= HTTP_POST_SEND
)
1842 return (CloseClient(con
));
1845 if (con
->http
.state
== HTTP_POST_SEND
)
1849 fstat(con
->file
, &filestats
);
1851 LogMessage(L_DEBUG2
, "ReadClient: %d Closing data file %d, size = %d.",
1852 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1857 if (filestats
.st_size
> MaxRequestSize
&&
1861 * Request is too big; remove it and send an error...
1864 LogMessage(L_DEBUG2
, "ReadClient: %d Removing temp file %s",
1865 con
->http
.fd
, con
->filename
);
1866 unlink(con
->filename
);
1867 ClearString(&con
->filename
);
1872 * Delete any IPP request data...
1875 ippDelete(con
->request
);
1876 con
->request
= NULL
;
1879 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1880 return (CloseClient(con
));
1885 if (!SendCommand(con
, con
->command
, con
->options
))
1887 if (!SendError(con
, HTTP_NOT_FOUND
))
1888 return (CloseClient(con
));
1891 LogRequest(con
, HTTP_OK
);
1896 return (ProcessIPPRequest(con
));
1901 break; /* Anti-compiler-warning-code */
1904 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1905 return (CloseClient(con
));
1912 * 'SendCommand()' - Send output from a command via HTTP.
1916 SendCommand(client_t
*con
,
1924 fd
= open(con
->filename
, O_RDONLY
);
1926 fd
= open("/dev/null", O_RDONLY
);
1928 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
1932 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
1934 LogMessage(L_DEBUG
, "SendCommand: %d file=%d", con
->http
.fd
, con
->file
);
1936 if (con
->pipe_pid
== 0)
1939 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1941 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
1942 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
1945 FD_SET(con
->file
, InputSet
);
1946 FD_SET(con
->http
.fd
, OutputSet
);
1948 if (!SendHeader(con
, HTTP_OK
, NULL
))
1951 if (con
->http
.version
== HTTP_1_1
)
1953 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
1955 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
1959 con
->file_ready
= 0;
1960 con
->got_fields
= 0;
1968 * 'SendError()' - Send an error message via HTTP.
1971 int /* O - 1 if successful, 0 otherwise */
1972 SendError(client_t
*con
, /* I - Connection */
1973 http_status_t code
) /* I - Error code */
1975 char message
[1024]; /* Message for user */
1979 * Put the request in the access_log file...
1982 LogRequest(con
, code
);
1984 LogMessage(L_DEBUG
, "SendError: %d code=%d (%s)", con
->http
.fd
, code
,
1988 * To work around bugs in some proxies, don't use Keep-Alive for some
1992 if (code
>= HTTP_BAD_REQUEST
)
1993 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1996 * Send an error message back to the client. If the error code is a
1997 * 400 or 500 series, make sure the message contains some text, too!
2000 if (!SendHeader(con
, code
, NULL
))
2004 if (code
== HTTP_UPGRADE_REQUIRED
)
2005 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2008 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2010 #endif /* HAVE_SSL */
2012 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2013 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2015 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2019 if (code
>= HTTP_BAD_REQUEST
)
2022 * Send a human-readable error message.
2025 snprintf(message
, sizeof(message
),
2026 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2027 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2028 code
, httpStatus(code
), httpStatus(code
),
2029 con
->language
? con
->language
->messages
[code
] :
2032 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
2034 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2035 (int)strlen(message
)) < 0)
2037 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2039 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2042 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2045 con
->http
.state
= HTTP_WAITING
;
2052 * 'SendFile()' - Send a file via HTTP.
2056 SendFile(client_t
*con
,
2060 struct stat
*filestats
)
2062 con
->file
= open(filename
, O_RDONLY
);
2064 LogMessage(L_DEBUG
, "SendFile: %d file=%d", con
->http
.fd
, con
->file
);
2069 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2073 if (!SendHeader(con
, code
, type
))
2076 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2078 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2079 (unsigned long)filestats
->st_size
) < 0)
2081 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2084 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2086 FD_SET(con
->http
.fd
, OutputSet
);
2093 * 'SendHeader()' - Send an HTTP request.
2096 int /* O - 1 on success, 0 on failure */
2097 SendHeader(client_t
*con
, /* I - Client to send to */
2098 http_status_t code
, /* I - HTTP status code */
2099 char *type
) /* I - MIME type of document */
2101 location_t
*loc
; /* Authentication location */
2104 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2105 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2107 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2109 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
2111 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2113 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2115 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2118 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2119 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2122 if (code
== HTTP_UNAUTHORIZED
)
2125 * This already succeeded in IsAuthorized...
2128 loc
= FindBest(con
->uri
, con
->http
.state
);
2130 if (loc
->type
!= AUTH_DIGEST
)
2132 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2137 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
2138 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2142 if (con
->language
!= NULL
)
2144 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2145 con
->language
->language
) < 0)
2149 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
2150 cupsLangEncoding(con
->language
)) < 0)
2153 else if (type
!= NULL
)
2154 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2162 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2168 int bytes
; /* Number of bytes read */
2169 char *lineptr
, /* Pointer to end of line in buffer */
2170 *message
; /* Pointer to message text */
2171 int loglevel
; /* Log level for message */
2172 static int bufused
= 0; /* Number of bytes used in buffer */
2173 static char buffer
[1024]; /* Status buffer */
2176 if ((bytes
= read(CGIPipes
[0], buffer
+ bufused
,
2177 sizeof(buffer
) - bufused
- 1)) > 0)
2180 buffer
[bufused
] = '\0';
2181 lineptr
= strchr(buffer
, '\n');
2183 else if (bytes
< 0 && errno
== EINTR
)
2187 lineptr
= buffer
+ bufused
;
2191 if (bytes
== 0 && bufused
== 0)
2194 while (lineptr
!= NULL
)
2197 * Terminate each line and process it...
2203 * Figure out the logging level...
2206 if (strncmp(buffer
, "EMERG:", 6) == 0)
2209 message
= buffer
+ 6;
2211 else if (strncmp(buffer
, "ALERT:", 6) == 0)
2214 message
= buffer
+ 6;
2216 else if (strncmp(buffer
, "CRIT:", 5) == 0)
2219 message
= buffer
+ 5;
2221 else if (strncmp(buffer
, "ERROR:", 6) == 0)
2224 message
= buffer
+ 6;
2226 else if (strncmp(buffer
, "WARNING:", 8) == 0)
2229 message
= buffer
+ 8;
2231 else if (strncmp(buffer
, "NOTICE:", 6) == 0)
2233 loglevel
= L_NOTICE
;
2234 message
= buffer
+ 6;
2236 else if (strncmp(buffer
, "INFO:", 5) == 0)
2239 message
= buffer
+ 5;
2241 else if (strncmp(buffer
, "DEBUG:", 6) == 0)
2244 message
= buffer
+ 6;
2246 else if (strncmp(buffer
, "DEBUG2:", 7) == 0)
2248 loglevel
= L_DEBUG2
;
2249 message
= buffer
+ 7;
2251 else if (strncmp(buffer
, "PAGE:", 5) == 0)
2254 message
= buffer
+ 5;
2263 * Skip leading whitespace in the message...
2266 while (isspace(*message
))
2269 LogMessage(loglevel
, "[CGI] %s", message
);
2272 * Copy over the buffer data we've used up...
2275 strcpy(buffer
, lineptr
);
2276 bufused
-= lineptr
- buffer
;
2281 lineptr
= strchr(buffer
, '\n');
2287 * Fatal error on pipe - should never happen!
2290 LogMessage(L_ERROR
, "UpdateCGI: error reading from CGI error pipe - %s",
2297 * 'WriteClient()' - Write data to a client as needed.
2300 int /* O - 1 if success, 0 if fail */
2301 WriteClient(client_t
*con
) /* I - Client connection */
2303 int bytes
; /* Number of bytes written */
2304 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
2305 char *bufptr
; /* Pointer into buffer */
2306 ipp_state_t ipp_state
; /* IPP state value */
2310 LogMessage(L_DEBUG2
, "WriteClient(con=%p) %d response=%p, file=%d pipe_pid=%d",
2311 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
);
2314 if (con
->http
.state
!= HTTP_GET_SEND
&&
2315 con
->http
.state
!= HTTP_POST_SEND
)
2318 if (con
->response
!= NULL
)
2320 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2321 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2323 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
2326 LogMessage(L_DEBUG2
, "WriteClient: Read %d bytes from file %d...",
2330 if (con
->pipe_pid
&& !con
->got_fields
)
2333 * Inspect the data for Content-Type and other fields.
2338 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2339 if (*bufptr
== '\n')
2342 * Send line to client...
2345 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2349 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2350 LogMessage(L_DEBUG2
, "WriteClient: %d %s", con
->http
.fd
, buf
);
2356 bytes
-= (bufptr
- buf
);
2357 memmove(buf
, bufptr
, bytes
+ 1);
2361 * See if the line was empty...
2364 if (con
->field_col
== 0)
2365 con
->got_fields
= 1;
2369 else if (*bufptr
!= '\r')
2372 if (bytes
> 0 && !con
->got_fields
)
2375 * Remaining text needs to go out...
2378 httpPrintf(HTTP(con
), "%s", buf
);
2380 con
->http
.activity
= time(NULL
);
2383 else if (bytes
== 0)
2385 con
->http
.activity
= time(NULL
);
2390 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2396 con
->bytes
+= bytes
;
2401 LogRequest(con
, HTTP_OK
);
2403 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2405 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2412 con
->http
.state
= HTTP_WAITING
;
2414 LogMessage(L_DEBUG2
, "WriteClient: Removing fd %d from OutputSet...",
2417 FD_CLR(con
->http
.fd
, OutputSet
);
2421 if (FD_ISSET(con
->file
, InputSet
))
2423 LogMessage(L_DEBUG2
, "WriteClient: Removing fd %d from InputSet...",
2425 FD_CLR(con
->file
, InputSet
);
2429 kill(con
->pipe_pid
, SIGTERM
);
2431 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
2432 con
->http
.fd
, con
->file
);
2441 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
2442 con
->http
.fd
, con
->filename
);
2443 unlink(con
->filename
);
2444 ClearString(&con
->filename
);
2447 if (con
->request
!= NULL
)
2449 ippDelete(con
->request
);
2450 con
->request
= NULL
;
2453 if (con
->response
!= NULL
)
2455 ippDelete(con
->response
);
2456 con
->response
= NULL
;
2459 ClearString(&con
->command
);
2460 ClearString(&con
->options
);
2462 if (!con
->http
.keep_alive
)
2470 con
->file_ready
= 0;
2472 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2474 LogMessage(L_DEBUG2
, "WriteClient: Adding fd %d to InputSet...", con
->file
);
2475 FD_SET(con
->file
, InputSet
);
2480 LogMessage(L_DEBUG2
, "WriteClient: %d %d bytes", con
->http
.fd
, bytes
);
2482 con
->http
.activity
= time(NULL
);
2489 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2492 static int /* O - 1 if modified since */
2493 check_if_modified(client_t
*con
, /* I - Client connection */
2494 struct stat
*filestats
) /* I - File information */
2496 char *ptr
; /* Pointer into field */
2497 time_t date
; /* Time/date value */
2498 int size
; /* Size/length value */
2503 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2508 LogMessage(L_DEBUG2
, "check_if_modified: %d If-Modified-Since=\"%s\"",
2511 while (*ptr
!= '\0')
2513 while (isspace(*ptr
) || *ptr
== ';')
2516 if (strncasecmp(ptr
, "length=", 7) == 0)
2521 while (isdigit(*ptr
))
2524 else if (isalpha(*ptr
))
2526 date
= httpGetDateTime(ptr
);
2527 while (*ptr
!= '\0' && *ptr
!= ';')
2532 LogMessage(L_DEBUG2
, "check_if_modified: %d sizes=%d,%d dates=%d,%d",
2533 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2534 (int)filestats
->st_mtime
);
2536 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2537 (date
< filestats
->st_mtime
&& date
!= 0) ||
2538 (size
== 0 && date
== 0));
2543 * 'decode_auth()' - Decode an authorization string.
2547 decode_auth(client_t
*con
) /* I - Client to decode to */
2549 char *s
, /* Authorization string */
2550 value
[1024]; /* Value string */
2551 const char *username
; /* Certificate username */
2555 * Decode the string...
2558 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2560 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2563 if (strncmp(s
, "Basic", 5) == 0)
2569 httpDecode64(value
, s
);
2572 * Pull the username and password out...
2575 if ((s
= strchr(value
, ':')) == NULL
)
2577 LogMessage(L_DEBUG
, "decode_auth: %d no colon in auth string \"%s\"",
2578 con
->http
.fd
, value
);
2584 strlcpy(con
->username
, value
, sizeof(con
->username
));
2585 strlcpy(con
->password
, s
, sizeof(con
->password
));
2587 else if (strncmp(s
, "Local", 5) == 0)
2593 if ((username
= FindCert(s
)) != NULL
)
2594 strlcpy(con
->username
, username
, sizeof(con
->username
));
2596 else if (strncmp(s
, "Digest", 5) == 0)
2599 * Get the username and password from the Digest attributes...
2602 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2604 strlcpy(con
->username
, value
, sizeof(con
->username
));
2606 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2608 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2611 LogMessage(L_DEBUG2
, "decode_auth: %d username=\"%s\"",
2612 con
->http
.fd
, con
->username
);
2616 static char * /* O - Real filename */
2617 get_file(client_t
*con
, /* I - Client connection */
2618 struct stat
*filestats
, /* O - File information */
2619 char *filename
, /* IO - Filename buffer */
2620 int len
) /* I - Buffer length */
2622 int status
; /* Status of filesystem calls */
2623 char *ptr
; /* Pointer info filename */
2624 int plen
; /* Remaining length after pointer */
2628 * Need to add DocumentRoot global...
2631 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2632 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2633 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2634 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2635 else if (con
->language
!= NULL
)
2636 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2639 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2641 if ((ptr
= strchr(filename
, '?')) != NULL
)
2645 * Grab the status for this language; if there isn't a language-specific file
2646 * then fallback to the default one...
2649 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2652 * Drop the language prefix and try the current directory...
2655 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2656 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2658 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2660 if ((ptr
= strchr(filename
, '?')) != NULL
)
2663 status
= stat(filename
, filestats
);
2668 * If we're found a directory, get the index.html file instead...
2671 if (!status
&& S_ISDIR(filestats
->st_mode
))
2673 if (filename
[strlen(filename
) - 1] != '/')
2674 strlcat(filename
, "/", len
);
2676 ptr
= filename
+ strlen(filename
);
2677 plen
= len
- (ptr
- filename
);
2679 strlcpy(ptr
, "index.html", plen
);
2680 status
= stat(filename
, filestats
);
2685 strlcpy(ptr
, "index.class", plen
);
2686 status
= stat(filename
, filestats
);
2688 #endif /* HAVE_JAVA */
2693 strlcpy(ptr
, "index.pl", plen
);
2694 status
= stat(filename
, filestats
);
2696 #endif /* HAVE_PERL */
2701 strlcpy(ptr
, "index.php", plen
);
2702 status
= stat(filename
, filestats
);
2704 #endif /* HAVE_PHP */
2709 strlcpy(ptr
, "index.pyc", plen
);
2710 status
= stat(filename
, filestats
);
2715 strlcpy(ptr
, "index.py", plen
);
2716 status
= stat(filename
, filestats
);
2718 #endif /* HAVE_PYTHON */
2721 LogMessage(L_DEBUG2
, "get_file: %d filename=%s size=%d",
2722 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2732 * 'install_conf_file()' - Install a configuration file.
2735 static http_status_t
/* O - Status */
2736 install_conf_file(client_t
*con
) /* I - Connection */
2738 cups_file_t
*in
, /* Input file */
2739 *out
; /* Output file */
2740 char buffer
[1024]; /* Copy buffer */
2741 int bytes
; /* Number of bytes */
2742 char conffile
[1024], /* Configuration filename */
2743 newfile
[1024], /* New config filename */
2744 oldfile
[1024]; /* Old config filename */
2745 struct stat confinfo
; /* Config file info */
2749 * First construct the filenames...
2752 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2753 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2754 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2756 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2759 * Get the owner, group, and permissions of the configuration file.
2760 * If it doesn't exist, assign it to the User and Group in the
2761 * cupsd.conf file with mode 0640 permissions.
2764 if (stat(conffile
, &confinfo
))
2766 confinfo
.st_uid
= User
;
2767 confinfo
.st_gid
= Group
;
2768 confinfo
.st_mode
= ConfigFilePerm
;
2772 * Open the request file and new config file...
2775 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2777 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2778 con
->filename
, strerror(errno
));
2779 return (HTTP_SERVER_ERROR
);
2782 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2785 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2786 newfile
, strerror(errno
));
2787 return (HTTP_SERVER_ERROR
);
2790 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2791 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2794 * Copy from the request to the new config file...
2797 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2798 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2800 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2801 newfile
, strerror(errno
));
2807 return (HTTP_SERVER_ERROR
);
2811 * Close the files...
2815 if (cupsFileClose(out
))
2817 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2818 newfile
, strerror(errno
));
2822 return (HTTP_SERVER_ERROR
);
2826 * Remove the request file...
2829 unlink(con
->filename
);
2830 ClearString(&con
->filename
);
2833 * Unlink the old backup, rename the current config file to the backup
2834 * filename, and rename the new config file to the config file name...
2837 if (unlink(oldfile
))
2838 if (errno
!= ENOENT
)
2840 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2841 oldfile
, strerror(errno
));
2845 return (HTTP_SERVER_ERROR
);
2848 if (rename(conffile
, oldfile
))
2849 if (errno
!= ENOENT
)
2851 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2852 conffile
, strerror(errno
));
2856 return (HTTP_SERVER_ERROR
);
2859 if (rename(newfile
, conffile
))
2861 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2862 newfile
, strerror(errno
));
2864 rename(oldfile
, conffile
);
2867 return (HTTP_SERVER_ERROR
);
2871 * If the cupsd.conf file was updated, set the NeedReload flag...
2874 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2875 NeedReload
= RELOAD_CUPSD
;
2877 NeedReload
= RELOAD_ALL
;
2879 ReloadTime
= time(NULL
);
2882 * Return that the file was created successfully...
2885 return (HTTP_CREATED
);
2890 * 'pipe_command()' - Pipe the output of a command to the remote client.
2893 static int /* O - Process ID */
2894 pipe_command(client_t
*con
, /* I - Client connection */
2895 int infile
, /* I - Standard input for command */
2896 int *outfile
, /* O - Standard output for command */
2897 char *command
, /* I - Command to run */
2898 char *options
) /* I - Options for command */
2900 int i
; /* Looping var */
2901 int pid
; /* Process ID */
2902 char *commptr
; /* Command string pointer */
2903 char *uriptr
; /* URI string pointer */
2904 int fd
; /* Looping var */
2905 int fds
[2]; /* Pipe FDs */
2906 int argc
; /* Number of arguments */
2907 int envc
; /* Number of environment variables */
2908 char argbuf
[10240], /* Argument buffer */
2909 *argv
[100], /* Argument strings */
2910 *envp
[100]; /* Environment variables */
2911 char content_length
[1024], /* CONTENT_LENGTH environment variable */
2912 content_type
[1024], /* CONTENT_TYPE environment variable */
2913 cups_datadir
[1024], /* CUPS_DATADIR environment variable */
2914 cups_serverroot
[1024], /* CUPS_SERVERROOT environment variable */
2915 http_cookie
[1024], /* HTTP_COOKIE environment variable */
2916 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
2917 ipp_port
[1024], /* IPP_PORT environment variable */
2918 lang
[1024], /* LANG environment variable */
2919 ld_library_path
[1024], /* LD_LIBRARY_PATH environment variable */
2920 ld_preload
[1024], /* LD_PRELOAD environment variable */
2921 dyld_library_path
[1024],/* DYLD_LIBRARY_PATH environment variable */
2922 shlib_path
[1024], /* SHLIB_PATH environment variable */
2923 nlspath
[1024], /* NLSPATH environment variable */
2924 query_string
[10240], /* QUERY_STRING env variable */
2925 remote_addr
[1024], /* REMOTE_ADDR environment variable */
2926 remote_host
[1024], /* REMOTE_HOST environment variable */
2927 remote_user
[1024], /* REMOTE_USER environment variable */
2928 script_name
[1024], /* SCRIPT_NAME environment variable */
2929 server_name
[1024], /* SERVER_NAME environment variable */
2930 server_port
[1024], /* SERVER_PORT environment variable */
2931 tmpdir
[1024], /* TMPDIR environment variable */
2932 vg_args
[1024], /* VG_ARGS environment variable */
2933 ld_assume_kernel
[1024]; /* LD_ASSUME_KERNEL environment variable */
2934 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
2935 struct sigaction action
; /* POSIX signal handler */
2936 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
2937 static const char * const locale_encodings
[] =
2938 { /* Locale charset names */
2939 "ASCII", "ISO8859-1", "ISO8859-2", "ISO8859-3",
2940 "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7",
2941 "ISO8859-8", "ISO8859-9", "ISO8859-10", "UTF-8",
2942 "ISO8859-13", "ISO8859-14", "ISO8859-15", "CP874",
2943 "CP1250", "CP1251", "CP1252", "CP1253",
2944 "CP1254", "CP1255", "CP1256", "CP1257",
2945 "CP1258", "KOI8R", "KOI8U", "ISO8859-11",
2946 "ISO8859-16", "", "", "",
2957 "CP932", "CP936", "CP949", "CP950",
2958 "CP1361", "", "", "",
2975 "EUC-CN", "EUC-JP", "EUC-KR", "EUC-TW"
2977 static const char * const encryptions
[] =
2979 "CUPS_ENCRYPTION=IfRequested",
2980 "CUPS_ENCRYPTION=Never",
2981 "CUPS_ENCRYPTION=Required",
2982 "CUPS_ENCRYPTION=Always"
2987 * Copy the command string...
2990 strlcpy(argbuf
, options
, sizeof(argbuf
));
2993 * Parse the string; arguments can be separated by + and are terminated
2999 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
3000 if (*commptr
== ' ' || *commptr
== '+')
3004 while (*commptr
== ' ')
3007 if (*commptr
!= '\0')
3009 argv
[argc
] = commptr
;
3015 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3016 isxdigit(commptr
[2] & 255))
3018 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3019 *commptr
= (commptr
[1] - '0') << 4;
3021 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3023 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3024 *commptr
|= commptr
[2] - '0';
3026 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3028 cups_strcpy(commptr
+ 1, commptr
+ 3);
3030 else if (*commptr
== '?')
3035 if (argv
[0][0] == '\0')
3036 argv
[0] = strrchr(command
, '/') + 1;
3039 * Setup the environment variables as needed...
3043 snprintf(lang
, sizeof(lang
), "LANG=%s.%s", con
->language
->language
,
3044 locale_encodings
[con
->language
->encoding
]);
3046 strcpy(lang
, "LANG=C");
3048 sprintf(ipp_port
, "IPP_PORT=%d", LocalPort
);
3050 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
3051 sprintf(server_port
, "SERVER_PORT=%d",
3052 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3054 #endif /* AF_INET6 */
3055 sprintf(server_port
, "SERVER_PORT=%d",
3056 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3058 if (strcmp(con
->http
.hostname
, "localhost") == 0)
3059 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
3061 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
3062 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
3063 strcpy(remote_addr
, "REMOTE_ADDR=");
3064 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3065 sizeof(remote_addr
) - 12);
3066 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3067 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
3068 snprintf(cups_datadir
, sizeof(cups_datadir
), "CUPS_DATADIR=%s", DataDir
);
3069 snprintf(cups_serverroot
, sizeof(cups_serverroot
), "CUPS_SERVERROOT=%s", ServerRoot
);
3073 envp
[envc
++] = "PATH=/bin:/usr/bin";
3074 envp
[envc
++] = "SERVER_SOFTWARE=CUPS/1.1";
3075 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3076 if (con
->http
.version
== HTTP_1_1
)
3077 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3078 else if (con
->http
.version
== HTTP_1_0
)
3079 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3081 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3082 envp
[envc
++] = "REDIRECT_STATUS=1";
3083 envp
[envc
++] = "CUPS_SERVER=localhost";
3084 envp
[envc
++] = ipp_port
;
3085 envp
[envc
++] = server_name
;
3086 envp
[envc
++] = server_port
;
3087 envp
[envc
++] = remote_addr
;
3088 envp
[envc
++] = remote_host
;
3089 envp
[envc
++] = remote_user
;
3090 envp
[envc
++] = lang
;
3092 envp
[envc
++] = tmpdir
;
3093 envp
[envc
++] = cups_datadir
;
3094 envp
[envc
++] = cups_serverroot
;
3096 if (getenv("VG_ARGS") != NULL
)
3098 snprintf(vg_args
, sizeof(vg_args
), "VG_ARGS=%s", getenv("VG_ARGS"));
3099 envp
[envc
++] = vg_args
;
3102 if (getenv("LD_ASSUME_KERNEL") != NULL
)
3104 snprintf(ld_assume_kernel
, sizeof(ld_assume_kernel
), "LD_ASSUME_KERNEL=%s",
3105 getenv("LD_ASSUME_KERNEL"));
3106 envp
[envc
++] = ld_assume_kernel
;
3109 if (getenv("LD_LIBRARY_PATH") != NULL
)
3111 snprintf(ld_library_path
, sizeof(ld_library_path
), "LD_LIBRARY_PATH=%s",
3112 getenv("LD_LIBRARY_PATH"));
3113 envp
[envc
++] = ld_library_path
;
3116 if (getenv("LD_PRELOAD") != NULL
)
3118 snprintf(ld_preload
, sizeof(ld_preload
), "LD_PRELOAD=%s",
3119 getenv("LD_PRELOAD"));
3120 envp
[envc
++] = ld_preload
;
3123 if (getenv("DYLD_LIBRARY_PATH") != NULL
)
3125 snprintf(dyld_library_path
, sizeof(dyld_library_path
), "DYLD_LIBRARY_PATH=%s",
3126 getenv("DYLD_LIBRARY_PATH"));
3127 envp
[envc
++] = dyld_library_path
;
3130 if (getenv("SHLIB_PATH") != NULL
)
3132 snprintf(shlib_path
, sizeof(shlib_path
), "SHLIB_PATH=%s",
3133 getenv("SHLIB_PATH"));
3134 envp
[envc
++] = shlib_path
;
3137 if (getenv("NLSPATH") != NULL
)
3139 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
3140 envp
[envc
++] = nlspath
;
3143 if (con
->http
.cookie
)
3145 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3147 envp
[envc
++] = http_cookie
;
3150 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3152 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3153 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3154 envp
[envc
++] = http_user_agent
;
3157 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3158 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3160 envp
[envc
++] = script_name
;
3162 if (con
->operation
== HTTP_GET
)
3164 for (i
= 0; i
< argc
; i
++)
3165 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3166 envp
[envc
++] = "REQUEST_METHOD=GET";
3171 * Add GET form variables after ?...
3176 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
3177 envp
[envc
++] = query_string
;
3182 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3183 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3184 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3186 envp
[envc
++] = "REQUEST_METHOD=POST";
3187 envp
[envc
++] = content_length
;
3188 envp
[envc
++] = content_type
;
3192 * Tell the CGI if we are using encryption...
3195 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3196 envp
[envc
++] = "HTTPS=ON";
3198 envp
[envc
++] = (char *)encryptions
[LocalEncryption
];
3201 * Terminate the environment array...
3206 if (LogLevel
== L_DEBUG2
)
3208 for (i
= 0; i
< argc
; i
++)
3209 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3210 for (i
= 0; i
< envc
; i
++)
3211 LogMessage(L_DEBUG2
, "envp[%d] = \"%s\"", i
, envp
[i
]);
3215 * Create a pipe for the output...
3220 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3221 argv
[0], strerror(errno
));
3226 * Block signals before forking...
3232 * Then execute the command...
3235 if ((pid
= fork()) == 0)
3238 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
3244 * Running as root, so change to a non-priviledged user...
3250 if (setgroups(1, &Group
))
3259 * Reset group membership to just the main one we belong to.
3262 setgroups(1, &Group
);
3266 * Update stdin/stdout/stderr...
3272 if (dup(infile
) < 0)
3277 if (dup(fds
[1]) < 0)
3284 * Close extra file descriptors...
3287 for (fd
= 3; fd
< MaxFDs
; fd
++)
3291 * Change umask to restrict permissions on created files...
3297 * Unblock signals before doing the exec...
3301 sigset(SIGTERM
, SIG_DFL
);
3302 sigset(SIGCHLD
, SIG_DFL
);
3303 #elif defined(HAVE_SIGACTION)
3304 memset(&action
, 0, sizeof(action
));
3306 sigemptyset(&action
.sa_mask
);
3307 action
.sa_handler
= SIG_DFL
;
3309 sigaction(SIGTERM
, &action
, NULL
);
3310 sigaction(SIGCHLD
, &action
, NULL
);
3312 signal(SIGTERM
, SIG_DFL
);
3313 signal(SIGCHLD
, SIG_DFL
);
3314 #endif /* HAVE_SIGSET */
3319 * Execute the pipe program; if an error occurs, exit with status 1...
3322 execve(command
, argv
, envp
);
3329 * Error - can't fork!
3332 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3342 * Fork successful - return the PID...
3345 AddCert(pid
, con
->username
);
3347 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3359 #if defined(HAVE_CDSASSL)
3361 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3364 static OSStatus
/* O - -1 on error, 0 on success */
3365 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3366 void *data
, /* I - Data buffer */
3367 size_t *dataLength
) /* IO - Number of bytes */
3369 ssize_t bytes
; /* Number of bytes read */
3372 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3375 *dataLength
= bytes
;
3384 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3387 static OSStatus
/* O - -1 on error, 0 on success */
3388 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3389 const void *data
, /* I - Data buffer */
3390 size_t *dataLength
) /* IO - Number of bytes */
3395 bytes
= write((int)connection
, data
, *dataLength
);
3398 *dataLength
= bytes
;
3404 #endif /* HAVE_CDSASSL */
3408 * End of "$Id: client.c,v 1.91.2.83 2004/06/29 02:45:24 mike Exp $".