2 * "$Id: client.c,v 1.91.2.76 2004/02/25 16:22:01 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 * 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
);
115 * Accept the client and get the remote address...
118 val
= sizeof(struct sockaddr_in
);
120 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
123 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
129 if (lis
->address
.addr
.sa_family
== AF_INET6
)
130 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
132 #endif /* AF_INET6 */
133 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
136 * Check the number of clients on the same address...
139 for (i
= 0, count
= 0; i
< NumClients
; i
++)
140 if (memcmp(&(Clients
[i
].http
.hostaddr
), &(con
->http
.hostaddr
),
141 sizeof(con
->http
.hostaddr
)) == 0)
144 if (count
>= MaxClientsPerHost
)
148 if (count
>= MaxClientsPerHost
)
150 if ((time(NULL
) - last_dos
) >= 60)
152 last_dos
= time(NULL
);
153 LogMessage(L_WARN
, "Possible DoS attack - more than %d clients connecting from %s!",
154 MaxClientsPerHost
, Clients
[i
].http
.hostname
);
158 closesocket(con
->http
.fd
);
167 * Get the hostname or format the IP address as needed...
171 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
172 sizeof(con
->http
.hostname
));
176 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
177 sizeof(con
->http
.hostname
));
180 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
183 * Map accesses from the loopback interface to "localhost"...
186 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
188 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
191 * Map accesses from the same host to the server name.
194 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
197 if (hostname
== NULL
&& HostNameLookups
== 2)
200 * Can't have an unresolved IP address with double-lookups enabled...
203 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
207 closesocket(con
->http
.fd
);
212 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
217 if (HostNameLookups
== 2)
220 * Do double lookups as needed...
223 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
226 * See if the hostname maps to the same IP address...
229 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
232 * Not the right type of address...
240 * Compare all of the addresses against this one...
243 for (i
= 0; host
->h_addr_list
[i
]; i
++)
245 httpAddrLoad(host
, 0, i
, &temp
);
247 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
251 if (!host
->h_addr_list
[i
])
259 * Can't have a hostname that doesn't resolve to the same IP address
260 * with double-lookups enabled...
263 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
267 closesocket(con
->http
.fd
);
272 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
279 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
280 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
281 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
283 #endif /* AF_INET6 */
284 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
285 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
288 * Using TCP_NODELAY improves responsiveness, especially on systems
289 * with a slow loopback interface... Since we write large buffers
290 * when sending print files and requests, there shouldn't be any
291 * performance penalty for this...
295 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
298 * Close this file on all execs...
301 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
304 * Add the socket to the select() input mask.
307 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
309 FD_SET(con
->http
.fd
, InputSet
);
314 * Temporarily suspend accept()'s until we lose a client...
317 if (NumClients
== MaxClients
)
322 * See if we are connecting on a secure port...
325 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
328 * https connection; go secure...
331 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
335 #endif /* HAVE_SSL */
340 * 'CloseAllClients()' - Close all remote clients immediately.
344 CloseAllClients(void)
346 while (NumClients
> 0)
347 CloseClient(Clients
);
352 * 'CloseClient()' - Close a remote client.
356 CloseClient(client_t
*con
) /* I - Client to close */
358 int partial
; /* Do partial close for SSL? */
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
);
377 * Shutdown encryption as needed...
385 conn
= (SSL
*)(con
->http
.tls
);
386 context
= SSL_get_SSL_CTX(conn
);
388 switch (SSL_shutdown(conn
))
391 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
394 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
396 while ((error
= ERR_get_error()) != 0)
397 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
401 SSL_CTX_free(context
);
404 # elif defined(HAVE_GNUTLS)
405 conn
= (http_tls_t
*)(con
->http
.tls
);
406 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
408 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
411 case GNUTLS_E_SUCCESS
:
412 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
415 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
419 gnutls_deinit(conn
->session
);
420 gnutls_certificate_free_credentials(*credentials
);
424 # elif defined(HAVE_CDSASSL)
425 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
426 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
427 # endif /* HAVE_LIBSSL */
429 con
->http
.tls
= NULL
;
431 #endif /* HAVE_SSL */
434 * Close the socket and clear the file from the input set for select()...
437 if (con
->http
.fd
> 0)
442 * Only do a partial close so that the encrypted client gets everything.
445 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from OutputSet...",
447 shutdown(con
->http
.fd
, 0);
448 FD_CLR(con
->http
.fd
, OutputSet
);
453 * Shut the socket down fully...
456 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
459 FD_CLR(con
->http
.fd
, InputSet
);
460 FD_CLR(con
->http
.fd
, OutputSet
);
465 if (con
->pipe_pid
!= 0)
468 * Stop any CGI process...
471 LogMessage(L_DEBUG2
, "CloseClient: %d Killing process ID %d...",
472 con
->http
.fd
, con
->pipe_pid
);
473 kill(con
->pipe_pid
, SIGKILL
);
478 if (FD_ISSET(con
->file
, InputSet
))
480 LogMessage(L_DEBUG2
, "CloseClient: %d Removing fd %d from InputSet...",
481 con
->http
.fd
, con
->file
);
482 FD_CLR(con
->file
, InputSet
);
485 LogMessage(L_DEBUG2
, "CloseClient: %d Closing data file %d.",
486 con
->http
.fd
, con
->file
);
498 if (con
->http
.input_set
)
499 free(con
->http
.input_set
);
501 httpClearCookie(HTTP(con
));
503 ClearString(&con
->filename
);
504 ClearString(&con
->command
);
505 ClearString(&con
->options
);
509 ippDelete(con
->request
);
515 ippDelete(con
->response
);
516 con
->response
= NULL
;
521 cupsLangFree(con
->language
);
522 con
->language
= NULL
;
526 * Re-enable new client connections if we are going back under the
530 if (NumClients
== MaxClients
)
534 * Compact the list of clients as necessary...
539 if (con
< (Clients
+ NumClients
))
540 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
546 * 'EncryptClient()' - Enable encryption for the client...
549 int /* O - 1 on success, 0 on error */
550 EncryptClient(client_t
*con
) /* I - Client to encrypt */
552 #if defined HAVE_LIBSSL
553 SSL_CTX
*context
; /* Context for encryption */
554 SSL
*conn
; /* Connection for encryption */
555 unsigned long error
; /* Error code */
559 * Create the SSL context and accept the connection...
562 context
= SSL_CTX_new(SSLv23_server_method());
564 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
565 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
567 conn
= SSL_new(context
);
569 SSL_set_fd(conn
, con
->http
.fd
);
570 if (SSL_accept(conn
) != 1)
572 while ((error
= ERR_get_error()) != 0)
573 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
575 SSL_CTX_free(context
);
580 con
->http
.tls
= conn
;
583 #elif defined(HAVE_GNUTLS)
584 http_tls_t
*conn
; /* TLS session object */
585 int error
; /* Error code */
586 gnutls_certificate_server_credentials
*credentials
;
587 /* TLS credentials */
590 * Create the SSL object and perform the SSL handshake...
593 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
598 credentials
= (gnutls_certificate_server_credentials
*)
599 malloc(sizeof(gnutls_certificate_server_credentials
));
600 if (credentials
== NULL
)
606 gnutls_certificate_allocate_credentials(credentials
);
607 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
608 ServerKey
, GNUTLS_X509_FMT_PEM
);
610 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
611 gnutls_set_default_priority(conn
->session
);
612 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
613 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
615 error
= gnutls_handshake(conn
->session
);
617 if (error
!= GNUTLS_E_SUCCESS
)
619 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
620 gnutls_deinit(conn
->session
);
621 gnutls_certificate_free_credentials(*credentials
);
627 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
630 conn
->credentials
= credentials
;
631 con
->http
.tls
= conn
;
634 #elif defined(HAVE_CDSASSL)
635 OSStatus error
; /* Error info */
636 SSLContextRef conn
; /* New connection */
637 SSLProtocol tryVersion
; /* Protocol version */
638 const char *hostName
; /* Local hostname */
639 int allowExpired
; /* Allow expired certificates? */
640 int allowAnyRoot
; /* Allow any root certificate? */
641 SSLProtocol
*negVersion
; /* Negotiated protocol version */
642 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
643 CFArrayRef
*peerCerts
; /* Certificates */
647 error
= SSLNewContext(true, &conn
);
652 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
655 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
658 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
662 hostName
= ServerName
; /* MRS: ??? */
663 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
666 /* have to do these options befor setting server certs */
667 if (!error
&& allowExpired
)
668 error
= SSLSetAllowsExpiredCerts(conn
, true);
670 if (!error
&& allowAnyRoot
)
671 error
= SSLSetAllowsAnyRoot(conn
, true);
673 if (!error
&& ServerCertificatesArray
!= NULL
)
674 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
677 * Perform SSL/TLS handshake
682 error
= SSLHandshake(conn
);
684 while (error
== errSSLWouldBlock
);
688 LogMessage(L_ERROR
, "EncryptClient: %d", error
);
690 con
->http
.error
= error
;
691 con
->http
.status
= HTTP_ERROR
;
694 SSLDisposeContext(conn
);
699 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
701 con
->http
.tls
= conn
;
706 #endif /* HAVE_GNUTLS */
711 * 'IsCGI()' - Is the resource a CGI script/program?
714 int /* O - 1 = CGI, 0 = file */
715 IsCGI(client_t
*con
, /* I - Client connection */
716 const char *filename
, /* I - Real filename */
717 struct stat
*filestats
, /* I - File information */
718 mime_type_t
*type
) /* I - MIME type */
720 const char *options
; /* Options on URL */
723 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
724 con
, filename
, filestats
, type
? type
->super
: "unknown",
725 type
? type
->type
: "unknown");
728 * Get the options, if any...
731 if ((options
= strchr(con
->uri
, '?')) != NULL
)
735 * Check for known types...
738 if (strcasecmp(type
->super
, "application"))
740 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
744 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
745 (filestats
->st_mode
& 0111))
748 * "application/x-httpd-cgi" is a CGI script.
751 SetString(&con
->command
, filename
);
753 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
756 SetStringf(&con
->options
, "%s %s", filename
, options
);
758 SetStringf(&con
->options
, "%s", filename
);
760 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
761 con
->command
, con
->options
);
766 else if (!strcasecmp(type
->type
, "x-httpd-java"))
769 * "application/x-httpd-java" is a Java servlet.
772 SetString(&con
->command
, CUPS_JAVA
);
775 SetStringf(&con
->options
, "java %s %s", filename
, options
);
777 SetStringf(&con
->options
, "java %s", filename
);
779 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
780 con
->command
, con
->options
);
784 #endif /* HAVE_JAVA */
786 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
789 * "application/x-httpd-perl" is a Perl page.
792 SetString(&con
->command
, CUPS_PERL
);
795 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
797 SetStringf(&con
->options
, "perl %s", filename
);
799 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
800 con
->command
, con
->options
);
804 #endif /* HAVE_PERL */
806 else if (!strcasecmp(type
->type
, "x-httpd-php"))
809 * "application/x-httpd-php" is a PHP page.
812 SetString(&con
->command
, CUPS_PHP
);
815 SetStringf(&con
->options
, "php %s %s", filename
, options
);
817 SetStringf(&con
->options
, "php %s", filename
);
819 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
820 con
->command
, con
->options
);
824 #endif /* HAVE_PHP */
826 else if (!strcasecmp(type
->type
, "x-httpd-python"))
829 * "application/x-httpd-python" is a Python page.
832 SetString(&con
->command
, CUPS_PYTHON
);
835 SetStringf(&con
->options
, "python %s %s", filename
, options
);
837 SetStringf(&con
->options
, "python %s", filename
);
839 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
840 con
->command
, con
->options
);
844 #endif /* HAVE_PYTHON */
846 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
853 * 'ReadClient()' - Read data from a client.
856 int /* O - 1 on success, 0 on error */
857 ReadClient(client_t
*con
) /* I - Client to read from */
859 char line
[32768], /* Line from client... */
860 operation
[64], /* Operation code from socket */
861 version
[64], /* HTTP version number string */
862 locale
[64], /* Locale */
863 *ptr
; /* Pointer into strings */
864 int major
, minor
; /* HTTP version numbers */
865 http_status_t status
; /* Transfer status */
866 ipp_state_t ipp_state
; /* State of IPP transfer */
867 int bytes
; /* Number of bytes to POST */
868 char *filename
; /* Name of file for GET/HEAD */
869 char buf
[1024]; /* Buffer for real filename */
870 struct stat filestats
; /* File information */
871 mime_type_t
*type
; /* MIME type of file */
872 printer_t
*p
; /* Printer */
873 location_t
*best
; /* Best match for authentication */
874 static unsigned request_id
= 0; /* Request ID for temp files */
877 status
= HTTP_CONTINUE
;
879 LogMessage(L_DEBUG2
, "ReadClient() %d, used=%d", con
->http
.fd
,
888 switch (con
->http
.state
)
892 * See if we've received a request line...
895 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
902 * Ignore blank request lines...
909 * Clear other state variables...
912 httpClearFields(HTTP(con
));
914 con
->http
.activity
= time(NULL
);
915 con
->http
.version
= HTTP_1_0
;
916 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
917 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
918 con
->http
.data_remaining
= 0;
919 con
->operation
= HTTP_WAITING
;
924 con
->username
[0] = '\0';
925 con
->password
[0] = '\0';
928 ClearString(&con
->command
);
929 ClearString(&con
->options
);
931 if (con
->language
!= NULL
)
933 cupsLangFree(con
->language
);
934 con
->language
= NULL
;
938 * Grab the request line...
941 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
944 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
945 SendError(con
, HTTP_BAD_REQUEST
);
949 con
->http
.version
= HTTP_0_9
;
952 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
954 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
955 SendError(con
, HTTP_BAD_REQUEST
);
962 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
963 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
964 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
966 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
970 SendError(con
, HTTP_NOT_SUPPORTED
);
978 * Handle full URLs in the request line...
981 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
983 char method
[HTTP_MAX_URI
], /* Method/scheme */
984 userpass
[HTTP_MAX_URI
], /* Username:password */
985 hostname
[HTTP_MAX_URI
], /* Hostname */
986 resource
[HTTP_MAX_URI
]; /* Resource path */
987 int port
; /* Port number */
991 * Separate the URI into its components...
994 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
997 * Only allow URIs with the servername, localhost, or an IP
1001 if (strcasecmp(hostname
, ServerName
) &&
1002 strcasecmp(hostname
, "localhost") &&
1003 !isdigit(hostname
[0]))
1006 * Nope, we don't do proxies...
1009 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
1010 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
1016 * Copy the resource portion back into the URI; both resource and
1017 * con->uri are HTTP_MAX_URI bytes in size...
1020 strcpy(con
->uri
, resource
);
1024 * Process the request...
1027 if (strcmp(operation
, "GET") == 0)
1028 con
->http
.state
= HTTP_GET
;
1029 else if (strcmp(operation
, "PUT") == 0)
1030 con
->http
.state
= HTTP_PUT
;
1031 else if (strcmp(operation
, "POST") == 0)
1032 con
->http
.state
= HTTP_POST
;
1033 else if (strcmp(operation
, "DELETE") == 0)
1034 con
->http
.state
= HTTP_DELETE
;
1035 else if (strcmp(operation
, "TRACE") == 0)
1036 con
->http
.state
= HTTP_TRACE
;
1037 else if (strcmp(operation
, "OPTIONS") == 0)
1038 con
->http
.state
= HTTP_OPTIONS
;
1039 else if (strcmp(operation
, "HEAD") == 0)
1040 con
->http
.state
= HTTP_HEAD
;
1043 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1044 SendError(con
, HTTP_BAD_REQUEST
);
1049 con
->start
= time(NULL
);
1050 con
->operation
= con
->http
.state
;
1052 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
1053 operation
, con
->uri
,
1054 con
->http
.version
/ 100, con
->http
.version
% 100);
1056 con
->http
.status
= HTTP_OK
;
1066 * Parse incoming parameters until the status changes...
1069 status
= httpUpdate(HTTP(con
));
1071 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1073 SendError(con
, HTTP_BAD_REQUEST
);
1080 break; /* Anti-compiler-warning-code */
1084 * Handle new transfers...
1087 if (status
== HTTP_OK
)
1089 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1092 * Figure out the locale from the Accept-Language and Content-Type
1096 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1099 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1102 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1105 * Combine language and charset, and trim any extra params in the
1109 snprintf(locale
, sizeof(locale
), "%s.%s",
1110 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1112 if ((ptr
= strchr(locale
, ',')) != NULL
)
1116 snprintf(locale
, sizeof(locale
), "%s.%s",
1117 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1119 con
->language
= cupsLangGet(locale
);
1122 con
->language
= cupsLangGet(DefaultLocale
);
1126 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1128 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1130 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1131 con
->http
.version
>= HTTP_1_1
)
1134 * HTTP/1.1 and higher require the "Host:" field...
1137 if (!SendError(con
, HTTP_BAD_REQUEST
))
1143 else if (con
->operation
== HTTP_OPTIONS
)
1146 * Do OPTIONS command...
1149 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1150 best
->type
!= AUTH_NONE
)
1152 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1159 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1160 con
->http
.tls
== NULL
)
1164 * Do encryption stuff...
1167 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1173 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1174 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1175 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1176 httpPrintf(HTTP(con
), "\r\n");
1180 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1185 #endif /* HAVE_SSL */
1188 if (con
->http
.expect
)
1190 /**** TODO: send expected header ****/
1193 if (!SendHeader(con
, HTTP_OK
, NULL
))
1199 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1200 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1201 httpPrintf(HTTP(con
), "\r\n");
1203 else if (strstr(con
->uri
, "..") != NULL
)
1206 * Protect against malicious users!
1209 if (!SendError(con
, HTTP_FORBIDDEN
))
1217 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1218 con
->http
.tls
== NULL
)
1222 * Do encryption stuff...
1225 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1231 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1232 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1233 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1234 httpPrintf(HTTP(con
), "\r\n");
1238 status
= IsAuthorized(con
);
1240 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1245 #endif /* HAVE_SSL */
1248 if (status
!= HTTP_OK
)
1250 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1252 SendError(con
, status
);
1257 if (con
->http
.expect
)
1259 /**** TODO: send expected header ****/
1262 switch (con
->http
.state
)
1264 case HTTP_GET_SEND
:
1265 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1266 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1269 * Send PPD file - get the real printer name since printer
1270 * names are not case sensitive but filenames can be...
1273 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1275 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1276 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1279 if (!SendError(con
, HTTP_NOT_FOUND
))
1289 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1290 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1291 strncmp(con
->uri
, "/printers", 9) == 0 ||
1292 strncmp(con
->uri
, "/classes", 8) == 0 ||
1293 strncmp(con
->uri
, "/jobs", 5) == 0)
1296 * Send CGI output...
1299 if (strncmp(con
->uri
, "/admin", 6) == 0)
1301 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1302 SetString(&con
->options
, con
->uri
+ 6);
1304 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1306 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1307 SetString(&con
->options
, con
->uri
+ 9);
1309 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1311 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1312 SetString(&con
->options
, con
->uri
+ 8);
1316 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1317 SetString(&con
->options
, con
->uri
+ 5);
1320 if (con
->options
[0] == '/')
1321 cups_strcpy(con
->options
, con
->options
+ 1);
1323 if (!SendCommand(con
, con
->command
, con
->options
))
1325 if (!SendError(con
, HTTP_NOT_FOUND
))
1332 LogRequest(con
, HTTP_OK
);
1334 if (con
->http
.version
<= HTTP_1_0
)
1335 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1337 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1338 (strchr(con
->uri
+ 12, '/') != NULL
||
1339 strlen(con
->uri
) == 12))
1342 * GET can only be done to configuration files under
1346 if (!SendError(con
, HTTP_FORBIDDEN
))
1360 if ((filename
= get_file(con
, &filestats
, buf
,
1361 sizeof(buf
))) == NULL
)
1363 if (!SendError(con
, HTTP_NOT_FOUND
))
1372 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1374 if (IsCGI(con
, filename
, &filestats
, type
))
1376 if (!SendCommand(con
, con
->command
, con
->options
))
1378 if (!SendError(con
, HTTP_NOT_FOUND
))
1385 LogRequest(con
, HTTP_OK
);
1387 if (con
->http
.version
<= HTTP_1_0
)
1388 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1392 if (!check_if_modified(con
, &filestats
))
1394 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1403 strcpy(line
, "text/plain");
1405 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1407 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1416 case HTTP_POST_RECV
:
1418 * See if the POST request includes a Content-Length field, and if
1419 * so check the length against any limits that are set...
1422 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1423 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1425 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1426 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1430 * Request too large...
1433 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1441 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1444 * Negative content lengths are invalid!
1447 if (!SendError(con
, HTTP_BAD_REQUEST
))
1457 * See what kind of POST request this is; for IPP requests the
1458 * content-type field will be "application/ipp"...
1461 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1462 con
->request
= ippNew();
1463 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1464 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1465 strncmp(con
->uri
, "/printers", 9) == 0 ||
1466 strncmp(con
->uri
, "/classes", 8) == 0 ||
1467 strncmp(con
->uri
, "/jobs", 5) == 0)
1473 if (strncmp(con
->uri
, "/admin", 6) == 0)
1475 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1476 SetString(&con
->options
, con
->uri
+ 6);
1478 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1480 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1481 SetString(&con
->options
, con
->uri
+ 9);
1483 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1485 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1486 SetString(&con
->options
, con
->uri
+ 8);
1490 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1491 SetString(&con
->options
, con
->uri
+ 5);
1494 if (con
->options
[0] == '/')
1495 cups_strcpy(con
->options
, con
->options
+ 1);
1497 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
1498 con
->http
.fd
, con
->command
, con
->options
);
1500 if (con
->http
.version
<= HTTP_1_0
)
1501 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1509 if ((filename
= get_file(con
, &filestats
, buf
,
1510 sizeof(buf
))) == NULL
)
1512 if (!SendError(con
, HTTP_NOT_FOUND
))
1521 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1523 if (!IsCGI(con
, filename
, &filestats
, type
))
1526 * Only POST to CGI's...
1529 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1538 case HTTP_PUT_RECV
:
1540 * Validate the resource name...
1543 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1544 strchr(con
->uri
+ 12, '/') != NULL
||
1545 strlen(con
->uri
) == 12)
1548 * PUT can only be done to configuration files under
1552 if (!SendError(con
, HTTP_FORBIDDEN
))
1562 * See if the PUT request includes a Content-Length field, and if
1563 * so check the length against any limits that are set...
1566 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1567 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1569 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1570 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1574 * Request too large...
1577 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1585 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1588 * Negative content lengths are invalid!
1591 if (!SendError(con
, HTTP_BAD_REQUEST
))
1601 * Open a temporary file to hold the request...
1604 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1605 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1606 fchmod(con
->file
, 0640);
1607 fchown(con
->file
, getuid(), Group
);
1609 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1610 con
->filename
, con
->file
);
1614 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1624 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1629 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1630 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1633 * Send PPD file - get the real printer name since printer
1634 * names are not case sensitive but filenames can be...
1637 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1639 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1640 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1643 if (!SendError(con
, HTTP_NOT_FOUND
))
1653 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1654 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1655 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1656 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1657 strncmp(con
->uri
, "/jobs/", 6) == 0)
1663 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1669 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1675 LogRequest(con
, HTTP_OK
);
1677 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1678 (strchr(con
->uri
+ 12, '/') != NULL
||
1679 strlen(con
->uri
) == 12))
1682 * HEAD can only be done to configuration files under
1686 if (!SendError(con
, HTTP_FORBIDDEN
))
1694 else if ((filename
= get_file(con
, &filestats
, buf
,
1695 sizeof(buf
))) == NULL
)
1697 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1703 LogRequest(con
, HTTP_NOT_FOUND
);
1705 else if (!check_if_modified(con
, &filestats
))
1707 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1713 LogRequest(con
, HTTP_NOT_MODIFIED
);
1721 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1723 strcpy(line
, "text/plain");
1725 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1727 if (!SendHeader(con
, HTTP_OK
, line
))
1733 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1734 httpGetDateString(filestats
.st_mtime
)) < 0)
1740 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1741 (unsigned long)filestats
.st_size
) < 0)
1747 LogRequest(con
, HTTP_OK
);
1750 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1756 con
->http
.state
= HTTP_WAITING
;
1760 break; /* Anti-compiler-warning-code */
1766 * Handle any incoming data...
1769 switch (con
->http
.state
)
1771 case HTTP_PUT_RECV
:
1772 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1774 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1775 con
->http
.data_remaining
, con
->file
);
1777 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1784 con
->bytes
+= bytes
;
1786 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1787 con
->http
.fd
, bytes
, con
->file
);
1789 if (write(con
->file
, line
, bytes
) < bytes
)
1791 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1792 bytes
, con
->filename
, strerror(errno
));
1794 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1799 unlink(con
->filename
);
1800 ClearString(&con
->filename
);
1802 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1810 if (con
->http
.state
== HTTP_WAITING
)
1813 * End of file, see how big it is...
1816 fstat(con
->file
, &filestats
);
1818 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1819 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1824 if (filestats
.st_size
> MaxRequestSize
&&
1828 * Request is too big; remove it and send an error...
1831 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1832 con
->http
.fd
, con
->filename
);
1833 unlink(con
->filename
);
1834 ClearString(&con
->filename
);
1836 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1844 * Install the configuration file...
1847 status
= install_conf_file(con
);
1850 * Return the status to the client...
1853 if (!SendError(con
, status
))
1861 case HTTP_POST_RECV
:
1862 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1864 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1865 con
->http
.data_remaining
, con
->file
);
1867 if (con
->request
!= NULL
)
1870 * Grab any request data from the connection...
1873 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1875 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1878 if (!SendError(con
, HTTP_BAD_REQUEST
))
1887 else if (ipp_state
!= IPP_DATA
)
1890 con
->bytes
+= ippLength(con
->request
);
1893 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1896 * Create a file as needed for the request data...
1899 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1900 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1901 fchmod(con
->file
, 0640);
1902 fchown(con
->file
, getuid(), Group
);
1904 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1905 con
->filename
, con
->file
);
1909 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1917 if (con
->http
.state
!= HTTP_POST_SEND
)
1919 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1926 con
->bytes
+= bytes
;
1928 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1929 con
->http
.fd
, bytes
, con
->file
);
1931 if (write(con
->file
, line
, bytes
) < bytes
)
1933 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1934 bytes
, con
->filename
, strerror(errno
));
1936 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1941 unlink(con
->filename
);
1942 ClearString(&con
->filename
);
1944 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1951 else if (con
->http
.state
== HTTP_POST_RECV
)
1955 else if (con
->http
.state
!= HTTP_POST_SEND
)
1962 if (con
->http
.state
== HTTP_POST_SEND
)
1966 fstat(con
->file
, &filestats
);
1968 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1969 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1974 if (filestats
.st_size
> MaxRequestSize
&&
1978 * Request is too big; remove it and send an error...
1981 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1982 con
->http
.fd
, con
->filename
);
1983 unlink(con
->filename
);
1984 ClearString(&con
->filename
);
1989 * Delete any IPP request data...
1992 ippDelete(con
->request
);
1993 con
->request
= NULL
;
1996 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
2005 if (!SendCommand(con
, con
->command
, con
->options
))
2007 if (!SendError(con
, HTTP_NOT_FOUND
))
2014 LogRequest(con
, HTTP_OK
);
2019 return (ProcessIPPRequest(con
));
2024 break; /* Anti-compiler-warning-code */
2027 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2038 * 'SendCommand()' - Send output from a command via HTTP.
2042 SendCommand(client_t
*con
,
2050 fd
= open(con
->filename
, O_RDONLY
);
2052 fd
= open("/dev/null", O_RDONLY
);
2054 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
2058 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
2060 LogMessage(L_DEBUG
, "SendCommand: %d file=%d", con
->http
.fd
, con
->file
);
2062 if (con
->pipe_pid
== 0)
2065 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2067 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
2068 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
2071 FD_SET(con
->file
, InputSet
);
2072 FD_SET(con
->http
.fd
, OutputSet
);
2074 if (!SendHeader(con
, HTTP_OK
, NULL
))
2077 if (con
->http
.version
== HTTP_1_1
)
2079 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2081 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2085 con
->file_ready
= 0;
2086 con
->got_fields
= 0;
2094 * 'SendError()' - Send an error message via HTTP.
2097 int /* O - 1 if successful, 0 otherwise */
2098 SendError(client_t
*con
, /* I - Connection */
2099 http_status_t code
) /* I - Error code */
2101 char message
[1024]; /* Message for user */
2105 * Put the request in the access_log file...
2108 if (con
->operation
> HTTP_WAITING
)
2109 LogRequest(con
, code
);
2111 LogMessage(L_DEBUG
, "SendError() %d code=%d (%s)", con
->http
.fd
, code
,
2115 * To work around bugs in some proxies, don't use Keep-Alive for some
2119 if (code
>= HTTP_BAD_REQUEST
)
2120 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2123 * Send an error message back to the client. If the error code is a
2124 * 400 or 500 series, make sure the message contains some text, too!
2127 if (!SendHeader(con
, code
, NULL
))
2131 if (code
== HTTP_UPGRADE_REQUIRED
)
2132 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2135 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2137 #endif /* HAVE_SSL */
2139 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2140 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2142 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2146 if (code
>= HTTP_BAD_REQUEST
)
2149 * Send a human-readable error message.
2152 snprintf(message
, sizeof(message
),
2153 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2154 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2155 code
, httpStatus(code
), httpStatus(code
),
2156 con
->language
? con
->language
->messages
[code
] :
2159 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
2161 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2162 (int)strlen(message
)) < 0)
2164 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2166 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2169 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2172 con
->http
.state
= HTTP_WAITING
;
2179 * 'SendFile()' - Send a file via HTTP.
2183 SendFile(client_t
*con
,
2187 struct stat
*filestats
)
2189 con
->file
= open(filename
, O_RDONLY
);
2191 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
2196 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2200 if (!SendHeader(con
, code
, type
))
2203 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2205 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2206 (unsigned long)filestats
->st_size
) < 0)
2208 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2211 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2213 FD_SET(con
->http
.fd
, OutputSet
);
2220 * 'SendHeader()' - Send an HTTP request.
2223 int /* O - 1 on success, 0 on failure */
2224 SendHeader(client_t
*con
, /* I - Client to send to */
2225 http_status_t code
, /* I - HTTP status code */
2226 char *type
) /* I - MIME type of document */
2228 location_t
*loc
; /* Authentication location */
2231 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2232 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2234 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2236 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
2238 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2240 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2242 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2245 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2246 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2249 if (code
== HTTP_UNAUTHORIZED
)
2252 * This already succeeded in IsAuthorized...
2255 loc
= FindBest(con
->uri
, con
->http
.state
);
2257 if (loc
->type
!= AUTH_DIGEST
)
2259 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2264 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
2265 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2269 if (con
->language
!= NULL
)
2271 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2272 con
->language
->language
) < 0)
2276 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
2277 cupsLangEncoding(con
->language
)) < 0)
2280 else if (type
!= NULL
)
2281 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2289 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2295 int bytes
; /* Number of bytes read */
2296 char *lineptr
, /* Pointer to end of line in buffer */
2297 *message
; /* Pointer to message text */
2298 int loglevel
; /* Log level for message */
2299 static int bufused
= 0; /* Number of bytes used in buffer */
2300 static char buffer
[1024]; /* Status buffer */
2303 if ((bytes
= read(CGIPipes
[0], buffer
+ bufused
,
2304 sizeof(buffer
) - bufused
- 1)) > 0)
2307 buffer
[bufused
] = '\0';
2308 lineptr
= strchr(buffer
, '\n');
2310 else if (bytes
< 0 && errno
== EINTR
)
2314 lineptr
= buffer
+ bufused
;
2318 if (bytes
== 0 && bufused
== 0)
2321 while (lineptr
!= NULL
)
2324 * Terminate each line and process it...
2330 * Figure out the logging level...
2333 if (strncmp(buffer
, "EMERG:", 6) == 0)
2336 message
= buffer
+ 6;
2338 else if (strncmp(buffer
, "ALERT:", 6) == 0)
2341 message
= buffer
+ 6;
2343 else if (strncmp(buffer
, "CRIT:", 5) == 0)
2346 message
= buffer
+ 5;
2348 else if (strncmp(buffer
, "ERROR:", 6) == 0)
2351 message
= buffer
+ 6;
2353 else if (strncmp(buffer
, "WARNING:", 8) == 0)
2356 message
= buffer
+ 8;
2358 else if (strncmp(buffer
, "NOTICE:", 6) == 0)
2360 loglevel
= L_NOTICE
;
2361 message
= buffer
+ 6;
2363 else if (strncmp(buffer
, "INFO:", 5) == 0)
2366 message
= buffer
+ 5;
2368 else if (strncmp(buffer
, "DEBUG:", 6) == 0)
2371 message
= buffer
+ 6;
2373 else if (strncmp(buffer
, "DEBUG2:", 7) == 0)
2375 loglevel
= L_DEBUG2
;
2376 message
= buffer
+ 7;
2378 else if (strncmp(buffer
, "PAGE:", 5) == 0)
2381 message
= buffer
+ 5;
2390 * Skip leading whitespace in the message...
2393 while (isspace(*message
))
2396 LogMessage(loglevel
, "[CGI] %s", message
);
2399 * Copy over the buffer data we've used up...
2402 strcpy(buffer
, lineptr
);
2403 bufused
-= lineptr
- buffer
;
2408 lineptr
= strchr(buffer
, '\n');
2414 * Fatal error on pipe - should never happen!
2417 LogMessage(L_ERROR
, "UpdateCGI: error reading from CGI error pipe - %s",
2424 * 'WriteClient()' - Write data to a client as needed.
2427 int /* O - 1 if success, 0 if fail */
2428 WriteClient(client_t
*con
) /* I - Client connection */
2430 int bytes
; /* Number of bytes written */
2431 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
2432 char *bufptr
; /* Pointer into buffer */
2433 ipp_state_t ipp_state
; /* IPP state value */
2437 LogMessage(L_DEBUG2
, "WriteClient(con=%p) %d response=%p, file=%d pipe_pid=%d",
2438 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
);
2441 if (con
->http
.state
!= HTTP_GET_SEND
&&
2442 con
->http
.state
!= HTTP_POST_SEND
)
2445 if (con
->response
!= NULL
)
2447 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2448 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2450 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
2453 LogMessage(L_DEBUG2
, "WriteClient: Read %d bytes from file %d...",
2457 if (con
->pipe_pid
&& !con
->got_fields
)
2460 * Inspect the data for Content-Type and other fields.
2465 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2466 if (*bufptr
== '\n')
2469 * Send line to client...
2472 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2476 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2477 LogMessage(L_DEBUG2
, "WriteClient: %d %s", con
->http
.fd
, buf
);
2483 bytes
-= (bufptr
- buf
);
2484 memmove(buf
, bufptr
, bytes
+ 1);
2488 * See if the line was empty...
2491 if (con
->field_col
== 0)
2492 con
->got_fields
= 1;
2496 else if (*bufptr
!= '\r')
2499 if (bytes
> 0 && !con
->got_fields
)
2502 * Remaining text needs to go out...
2505 httpPrintf(HTTP(con
), "%s", buf
);
2507 con
->http
.activity
= time(NULL
);
2510 else if (bytes
== 0)
2512 con
->http
.activity
= time(NULL
);
2517 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2523 con
->bytes
+= bytes
;
2528 LogRequest(con
, HTTP_OK
);
2530 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2532 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2539 con
->http
.state
= HTTP_WAITING
;
2541 LogMessage(L_DEBUG2
, "WriteClient: Removing fd %d from OutputSet...",
2544 FD_CLR(con
->http
.fd
, OutputSet
);
2548 if (FD_ISSET(con
->file
, InputSet
))
2550 LogMessage(L_DEBUG2
, "WriteClient: Removing fd %d from InputSet...",
2552 FD_CLR(con
->file
, InputSet
);
2556 kill(con
->pipe_pid
, SIGTERM
);
2558 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
2559 con
->http
.fd
, con
->file
);
2568 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
2569 con
->http
.fd
, con
->filename
);
2570 unlink(con
->filename
);
2571 ClearString(&con
->filename
);
2574 if (con
->request
!= NULL
)
2576 ippDelete(con
->request
);
2577 con
->request
= NULL
;
2580 if (con
->response
!= NULL
)
2582 ippDelete(con
->response
);
2583 con
->response
= NULL
;
2586 ClearString(&con
->command
);
2587 ClearString(&con
->options
);
2589 if (!con
->http
.keep_alive
)
2597 con
->file_ready
= 0;
2599 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2601 LogMessage(L_DEBUG2
, "WriteClient: Adding fd %d to InputSet...", con
->file
);
2602 FD_SET(con
->file
, InputSet
);
2607 LogMessage(L_DEBUG2
, "WriteClient: %d %d bytes", con
->http
.fd
, bytes
);
2609 con
->http
.activity
= time(NULL
);
2616 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2619 static int /* O - 1 if modified since */
2620 check_if_modified(client_t
*con
, /* I - Client connection */
2621 struct stat
*filestats
) /* I - File information */
2623 char *ptr
; /* Pointer into field */
2624 time_t date
; /* Time/date value */
2625 int size
; /* Size/length value */
2630 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2635 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
2638 while (*ptr
!= '\0')
2640 while (isspace(*ptr
) || *ptr
== ';')
2643 if (strncasecmp(ptr
, "length=", 7) == 0)
2648 while (isdigit(*ptr
))
2651 else if (isalpha(*ptr
))
2653 date
= httpGetDateTime(ptr
);
2654 while (*ptr
!= '\0' && *ptr
!= ';')
2659 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
2660 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2661 (int)filestats
->st_mtime
);
2663 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2664 (date
< filestats
->st_mtime
&& date
!= 0) ||
2665 (size
== 0 && date
== 0));
2670 * 'decode_auth()' - Decode an authorization string.
2674 decode_auth(client_t
*con
) /* I - Client to decode to */
2676 char *s
, /* Authorization string */
2677 value
[1024]; /* Value string */
2678 const char *username
; /* Certificate username */
2682 * Decode the string...
2685 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2687 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2690 if (strncmp(s
, "Basic", 5) == 0)
2696 httpDecode64(value
, s
);
2699 * Pull the username and password out...
2702 if ((s
= strchr(value
, ':')) == NULL
)
2704 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2705 con
->http
.fd
, value
);
2711 strlcpy(con
->username
, value
, sizeof(con
->username
));
2712 strlcpy(con
->password
, s
, sizeof(con
->password
));
2714 else if (strncmp(s
, "Local", 5) == 0)
2720 if ((username
= FindCert(s
)) != NULL
)
2721 strlcpy(con
->username
, username
, sizeof(con
->username
));
2723 else if (strncmp(s
, "Digest", 5) == 0)
2726 * Get the username and password from the Digest attributes...
2729 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2731 strlcpy(con
->username
, value
, sizeof(con
->username
));
2733 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2735 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2738 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2739 con
->http
.fd
, con
->username
);
2743 static char * /* O - Real filename */
2744 get_file(client_t
*con
, /* I - Client connection */
2745 struct stat
*filestats
, /* O - File information */
2746 char *filename
, /* IO - Filename buffer */
2747 int len
) /* I - Buffer length */
2749 int status
; /* Status of filesystem calls */
2750 char *ptr
; /* Pointer info filename */
2751 int plen
; /* Remaining length after pointer */
2755 * Need to add DocumentRoot global...
2758 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2759 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2760 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2761 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2762 else if (con
->language
!= NULL
)
2763 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2766 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2768 if ((ptr
= strchr(filename
, '?')) != NULL
)
2772 * Grab the status for this language; if there isn't a language-specific file
2773 * then fallback to the default one...
2776 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2779 * Drop the language prefix and try the current directory...
2782 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2783 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2785 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2787 if ((ptr
= strchr(filename
, '?')) != NULL
)
2790 status
= stat(filename
, filestats
);
2795 * If we're found a directory, get the index.html file instead...
2798 if (!status
&& S_ISDIR(filestats
->st_mode
))
2800 if (filename
[strlen(filename
) - 1] != '/')
2801 strlcat(filename
, "/", len
);
2803 ptr
= filename
+ strlen(filename
);
2804 plen
= len
- (ptr
- filename
);
2806 strlcpy(ptr
, "index.html", plen
);
2807 status
= stat(filename
, filestats
);
2812 strlcpy(ptr
, "index.class", plen
);
2813 status
= stat(filename
, filestats
);
2815 #endif /* HAVE_JAVA */
2820 strlcpy(ptr
, "index.pl", plen
);
2821 status
= stat(filename
, filestats
);
2823 #endif /* HAVE_PERL */
2828 strlcpy(ptr
, "index.php", plen
);
2829 status
= stat(filename
, filestats
);
2831 #endif /* HAVE_PHP */
2836 strlcpy(ptr
, "index.pyc", plen
);
2837 status
= stat(filename
, filestats
);
2842 strlcpy(ptr
, "index.py", plen
);
2843 status
= stat(filename
, filestats
);
2845 #endif /* HAVE_PYTHON */
2848 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2849 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2859 * 'install_conf_file()' - Install a configuration file.
2862 static http_status_t
/* O - Status */
2863 install_conf_file(client_t
*con
) /* I - Connection */
2865 cups_file_t
*in
, /* Input file */
2866 *out
; /* Output file */
2867 char buffer
[1024]; /* Copy buffer */
2868 int bytes
; /* Number of bytes */
2869 char conffile
[1024], /* Configuration filename */
2870 newfile
[1024], /* New config filename */
2871 oldfile
[1024]; /* Old config filename */
2872 struct stat confinfo
; /* Config file info */
2876 * First construct the filenames...
2879 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2880 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2881 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2883 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2886 * Get the owner, group, and permissions of the configuration file.
2887 * If it doesn't exist, assign it to the User and Group in the
2888 * cupsd.conf file with mode 0640 permissions.
2891 if (stat(conffile
, &confinfo
))
2893 confinfo
.st_uid
= User
;
2894 confinfo
.st_gid
= Group
;
2895 confinfo
.st_mode
= ConfigFilePerm
;
2899 * Open the request file and new config file...
2902 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2904 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2905 con
->filename
, strerror(errno
));
2906 return (HTTP_SERVER_ERROR
);
2909 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2912 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2913 newfile
, strerror(errno
));
2914 return (HTTP_SERVER_ERROR
);
2917 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2918 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2921 * Copy from the request to the new config file...
2924 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2925 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2927 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2928 newfile
, strerror(errno
));
2934 return (HTTP_SERVER_ERROR
);
2938 * Close the files...
2942 if (cupsFileClose(out
))
2944 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2945 newfile
, strerror(errno
));
2949 return (HTTP_SERVER_ERROR
);
2953 * Remove the request file...
2956 unlink(con
->filename
);
2957 ClearString(&con
->filename
);
2960 * Unlink the old backup, rename the current config file to the backup
2961 * filename, and rename the new config file to the config file name...
2964 if (unlink(oldfile
))
2965 if (errno
!= ENOENT
)
2967 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2968 oldfile
, strerror(errno
));
2972 return (HTTP_SERVER_ERROR
);
2975 if (rename(conffile
, oldfile
))
2976 if (errno
!= ENOENT
)
2978 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2979 conffile
, strerror(errno
));
2983 return (HTTP_SERVER_ERROR
);
2986 if (rename(newfile
, conffile
))
2988 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2989 newfile
, strerror(errno
));
2991 rename(oldfile
, conffile
);
2994 return (HTTP_SERVER_ERROR
);
2998 * If the cupsd.conf file was updated, set the NeedReload flag...
3001 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
3002 NeedReload
= RELOAD_CUPSD
;
3004 NeedReload
= RELOAD_ALL
;
3006 ReloadTime
= time(NULL
);
3009 * Return that the file was created successfully...
3012 return (HTTP_CREATED
);
3017 * 'pipe_command()' - Pipe the output of a command to the remote client.
3020 static int /* O - Process ID */
3021 pipe_command(client_t
*con
, /* I - Client connection */
3022 int infile
, /* I - Standard input for command */
3023 int *outfile
, /* O - Standard output for command */
3024 char *command
, /* I - Command to run */
3025 char *options
) /* I - Options for command */
3027 int i
; /* Looping var */
3028 int pid
; /* Process ID */
3029 char *commptr
; /* Command string pointer */
3030 char *uriptr
; /* URI string pointer */
3031 int fd
; /* Looping var */
3032 int fds
[2]; /* Pipe FDs */
3033 int argc
; /* Number of arguments */
3034 int envc
; /* Number of environment variables */
3035 char argbuf
[10240], /* Argument buffer */
3036 *argv
[100], /* Argument strings */
3037 *envp
[100]; /* Environment variables */
3038 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3039 content_type
[1024], /* CONTENT_TYPE environment variable */
3040 cups_datadir
[1024], /* CUPS_DATADIR environment variable */
3041 cups_serverroot
[1024], /* CUPS_SERVERROOT environment variable */
3042 http_cookie
[1024], /* HTTP_COOKIE environment variable */
3043 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3044 ipp_port
[1024], /* IPP_PORT environment variable */
3045 lang
[1024], /* LANG environment variable */
3046 ld_library_path
[1024], /* LD_LIBRARY_PATH environment variable */
3047 ld_preload
[1024], /* LD_PRELOAD environment variable */
3048 dyld_library_path
[1024],/* DYLD_LIBRARY_PATH environment variable */
3049 shlib_path
[1024], /* SHLIB_PATH environment variable */
3050 nlspath
[1024], /* NLSPATH environment variable */
3051 query_string
[10240], /* QUERY_STRING env variable */
3052 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3053 remote_host
[1024], /* REMOTE_HOST environment variable */
3054 remote_user
[1024], /* REMOTE_USER environment variable */
3055 script_name
[1024], /* SCRIPT_NAME environment variable */
3056 server_name
[1024], /* SERVER_NAME environment variable */
3057 server_port
[1024], /* SERVER_PORT environment variable */
3058 tmpdir
[1024], /* TMPDIR environment variable */
3059 vg_args
[1024], /* VG_ARGS environment variable */
3060 ld_assume_kernel
[1024]; /* LD_ASSUME_KERNEL environment variable */
3061 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
3062 struct sigaction action
; /* POSIX signal handler */
3063 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
3064 static const char * const locale_encodings
[] =
3065 { /* Locale charset names */
3066 "ASCII", "ISO8859-1", "ISO8859-2", "ISO8859-3",
3067 "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7",
3068 "ISO8859-8", "ISO8859-9", "ISO8859-10", "UTF-8",
3069 "ISO8859-13", "ISO8859-14", "ISO8859-15", "CP874",
3070 "CP1250", "CP1251", "CP1252", "CP1253",
3071 "CP1254", "CP1255", "CP1256", "CP1257",
3072 "CP1258", "KOI8R", "KOI8U", "ISO8859-11",
3073 "ISO8859-16", "", "", "",
3084 "CP932", "CP936", "CP949", "CP950",
3085 "CP1361", "", "", "",
3102 "EUC-CN", "EUC-JP", "EUC-KR", "EUC-TW"
3107 * Copy the command string...
3110 strlcpy(argbuf
, options
, sizeof(argbuf
));
3113 * Parse the string; arguments can be separated by + and are terminated
3119 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
3120 if (*commptr
== ' ' || *commptr
== '+')
3124 while (*commptr
== ' ')
3127 if (*commptr
!= '\0')
3129 argv
[argc
] = commptr
;
3135 else if (*commptr
== '%')
3137 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3138 *commptr
= (commptr
[1] - '0') << 4;
3140 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3142 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3143 *commptr
|= commptr
[2] - '0';
3145 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3147 cups_strcpy(commptr
+ 1, commptr
+ 3);
3149 else if (*commptr
== '?')
3154 if (argv
[0][0] == '\0')
3155 argv
[0] = strrchr(command
, '/') + 1;
3158 * Setup the environment variables as needed...
3162 snprintf(lang
, sizeof(lang
), "LANG=%s.%s", con
->language
->language
,
3163 locale_encodings
[con
->language
->encoding
]);
3165 strcpy(lang
, "LANG=C");
3167 sprintf(ipp_port
, "IPP_PORT=%d", LocalPort
);
3169 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
3170 sprintf(server_port
, "SERVER_PORT=%d",
3171 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3173 #endif /* AF_INET6 */
3174 sprintf(server_port
, "SERVER_PORT=%d",
3175 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3177 if (strcmp(con
->http
.hostname
, "localhost") == 0)
3178 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
3180 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
3181 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
3182 strcpy(remote_addr
, "REMOTE_ADDR=");
3183 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3184 sizeof(remote_addr
) - 12);
3185 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3186 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
3187 snprintf(cups_datadir
, sizeof(cups_datadir
), "CUPS_DATADIR=%s", DataDir
);
3188 snprintf(cups_serverroot
, sizeof(cups_serverroot
), "CUPS_SERVERROOT=%s", ServerRoot
);
3192 envp
[envc
++] = "PATH=/bin:/usr/bin";
3193 envp
[envc
++] = "SERVER_SOFTWARE=CUPS/1.1";
3194 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3195 if (con
->http
.version
== HTTP_1_1
)
3196 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3197 else if (con
->http
.version
== HTTP_1_0
)
3198 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3200 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3201 envp
[envc
++] = "REDIRECT_STATUS=1";
3202 envp
[envc
++] = "CUPS_SERVER=localhost";
3203 envp
[envc
++] = ipp_port
;
3204 envp
[envc
++] = server_name
;
3205 envp
[envc
++] = server_port
;
3206 envp
[envc
++] = remote_addr
;
3207 envp
[envc
++] = remote_host
;
3208 envp
[envc
++] = remote_user
;
3209 envp
[envc
++] = lang
;
3211 envp
[envc
++] = tmpdir
;
3212 envp
[envc
++] = cups_datadir
;
3213 envp
[envc
++] = cups_serverroot
;
3215 if (getenv("VG_ARGS") != NULL
)
3217 snprintf(vg_args
, sizeof(vg_args
), "VG_ARGS=%s", getenv("VG_ARGS"));
3218 envp
[envc
++] = vg_args
;
3221 if (getenv("LD_ASSUME_KERNEL") != NULL
)
3223 snprintf(ld_assume_kernel
, sizeof(ld_assume_kernel
), "LD_ASSUME_KERNEL=%s",
3224 getenv("LD_ASSUME_KERNEL"));
3225 envp
[envc
++] = ld_assume_kernel
;
3228 if (getenv("LD_LIBRARY_PATH") != NULL
)
3230 snprintf(ld_library_path
, sizeof(ld_library_path
), "LD_LIBRARY_PATH=%s",
3231 getenv("LD_LIBRARY_PATH"));
3232 envp
[envc
++] = ld_library_path
;
3235 if (getenv("LD_PRELOAD") != NULL
)
3237 snprintf(ld_preload
, sizeof(ld_preload
), "LD_PRELOAD=%s",
3238 getenv("LD_PRELOAD"));
3239 envp
[envc
++] = ld_preload
;
3242 if (getenv("DYLD_LIBRARY_PATH") != NULL
)
3244 snprintf(dyld_library_path
, sizeof(dyld_library_path
), "DYLD_LIBRARY_PATH=%s",
3245 getenv("DYLD_LIBRARY_PATH"));
3246 envp
[envc
++] = dyld_library_path
;
3249 if (getenv("SHLIB_PATH") != NULL
)
3251 snprintf(shlib_path
, sizeof(shlib_path
), "SHLIB_PATH=%s",
3252 getenv("SHLIB_PATH"));
3253 envp
[envc
++] = shlib_path
;
3256 if (getenv("NLSPATH") != NULL
)
3258 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
3259 envp
[envc
++] = nlspath
;
3262 if (con
->http
.cookie
)
3264 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3266 envp
[envc
++] = http_cookie
;
3269 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3271 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3272 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3273 envp
[envc
++] = http_user_agent
;
3276 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3277 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3279 envp
[envc
++] = script_name
;
3281 if (con
->operation
== HTTP_GET
)
3283 for (i
= 0; i
< argc
; i
++)
3284 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3285 envp
[envc
++] = "REQUEST_METHOD=GET";
3290 * Add GET form variables after ?...
3295 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
3296 envp
[envc
++] = query_string
;
3301 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3302 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3303 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3305 envp
[envc
++] = "REQUEST_METHOD=POST";
3306 envp
[envc
++] = content_length
;
3307 envp
[envc
++] = content_type
;
3311 * Tell the CGI if we are using encryption...
3314 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3316 envp
[envc
++] = "HTTPS=ON";
3317 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
3322 if (LogLevel
== L_DEBUG2
)
3324 for (i
= 0; i
< argc
; i
++)
3325 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3326 for (i
= 0; i
< envc
; i
++)
3327 LogMessage(L_DEBUG2
, "envp[%d] = \"%s\"", i
, envp
[i
]);
3331 * Create a pipe for the output...
3336 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3337 argv
[0], strerror(errno
));
3342 * Block signals before forking...
3348 * Then execute the command...
3351 if ((pid
= fork()) == 0)
3354 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
3360 * Running as root, so change to a non-priviledged user...
3366 if (setgroups(1, &Group
))
3375 * Reset group membership to just the main one we belong to.
3378 setgroups(1, &Group
);
3382 * Update stdin/stdout/stderr...
3388 if (dup(infile
) < 0)
3393 if (dup(fds
[1]) < 0)
3400 * Close extra file descriptors...
3403 for (fd
= 3; fd
< MaxFDs
; fd
++)
3407 * Change umask to restrict permissions on created files...
3413 * Unblock signals before doing the exec...
3417 sigset(SIGTERM
, SIG_DFL
);
3418 sigset(SIGCHLD
, SIG_DFL
);
3419 #elif defined(HAVE_SIGACTION)
3420 memset(&action
, 0, sizeof(action
));
3422 sigemptyset(&action
.sa_mask
);
3423 action
.sa_handler
= SIG_DFL
;
3425 sigaction(SIGTERM
, &action
, NULL
);
3426 sigaction(SIGCHLD
, &action
, NULL
);
3428 signal(SIGTERM
, SIG_DFL
);
3429 signal(SIGCHLD
, SIG_DFL
);
3430 #endif /* HAVE_SIGSET */
3435 * Execute the pipe program; if an error occurs, exit with status 1...
3438 execve(command
, argv
, envp
);
3445 * Error - can't fork!
3448 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3458 * Fork successful - return the PID...
3461 AddCert(pid
, con
->username
);
3463 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3475 #if defined(HAVE_CDSASSL)
3477 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3480 static OSStatus
/* O - -1 on error, 0 on success */
3481 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3482 void *data
, /* I - Data buffer */
3483 size_t *dataLength
) /* IO - Number of bytes */
3485 ssize_t bytes
; /* Number of bytes read */
3488 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3491 *dataLength
= bytes
;
3500 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3503 static OSStatus
/* O - -1 on error, 0 on success */
3504 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3505 const void *data
, /* I - Data buffer */
3506 size_t *dataLength
) /* IO - Number of bytes */
3511 bytes
= write((int)connection
, data
, *dataLength
);
3514 *dataLength
= bytes
;
3520 #endif /* HAVE_CDSASSL */
3524 * End of "$Id: client.c,v 1.91.2.76 2004/02/25 16:22:01 mike Exp $".