2 * "$Id: client.c,v 1.91.2.65 2003/07/20 12:51:43 mike Exp $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2003 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * AcceptClient() - Accept a new client.
27 * CloseAllClients() - Close all remote clients immediately.
28 * CloseClient() - Close a remote client.
29 * EncryptClient() - Enable encryption for the client...
30 * IsCGI() - Is the resource a CGI script/program?
31 * ReadClient() - Read data from a client.
32 * SendCommand() - Send output from a command via HTTP.
33 * SendError() - Send an error message via HTTP.
34 * SendFile() - Send a file via HTTP.
35 * SendHeader() - Send an HTTP request.
36 * ShutdownClient() - Shutdown the receiving end of a connection.
37 * UpdateCGI() - Read status messages from CGI scripts and programs.
38 * WriteClient() - Write data to a client as needed.
39 * check_if_modified() - Decode an "If-Modified-Since" line.
40 * decode_auth() - Decode an authorization string.
41 * get_file() - Get a filename and state info.
42 * install_conf_file() - Install a configuration file.
43 * pipe_command() - Pipe the output of a command to the remote client.
44 * CDSAReadFunc() - Read function for CDSA decryption code.
45 * CDSAWriteFunc() - Write function for CDSA encryption code.
49 * Include necessary headers...
52 #include <cups/http-private.h>
61 static int check_if_modified(client_t
*con
,
62 struct stat
*filestats
);
63 static void decode_auth(client_t
*con
);
64 static char *get_file(client_t
*con
, struct stat
*filestats
,
65 char *filename
, int len
);
66 static http_status_t
install_conf_file(client_t
*con
);
67 static int pipe_command(client_t
*con
, int infile
, int *outfile
,
68 char *command
, char *options
);
71 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
,
73 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
,
74 const void *data
, size_t *dataLength
);
75 #endif /* HAVE_CDSASSL */
79 * 'AcceptClient()' - Accept a new client.
83 AcceptClient(listener_t
*lis
) /* I - Listener socket */
85 int i
; /* Looping var */
86 int count
; /* Count of connections on a host */
87 int val
; /* Parameter value */
88 client_t
*con
; /* New client pointer */
89 const struct hostent
*host
; /* Host entry for address */
90 char *hostname
;/* Hostname for address */
91 http_addr_t temp
; /* Temporary address variable */
92 static time_t last_dos
= 0;
93 /* Time of last DoS attack */
96 LogMessage(L_DEBUG2
, "AcceptClient(%p) %d NumClients = %d",
97 lis
, lis
->fd
, NumClients
);
100 * Make sure we don't have a full set of clients already...
103 if (NumClients
== MaxClients
)
107 * Get a pointer to the next available client...
110 con
= Clients
+ NumClients
;
112 memset(con
, 0, sizeof(client_t
));
113 con
->http
.activity
= time(NULL
);
116 * Accept the client and get the remote address...
119 val
= sizeof(struct sockaddr_in
);
121 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
124 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
130 if (lis
->address
.addr
.sa_family
== AF_INET6
)
131 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
133 #endif /* AF_INET6 */
134 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
137 * Check the number of clients on the same address...
140 for (i
= 0, count
= 0; i
< NumClients
; i
++)
141 if (memcmp(&(Clients
[i
].http
.hostaddr
), &(con
->http
.hostaddr
),
142 sizeof(con
->http
.hostaddr
)) == 0)
145 if (count
>= MaxClientsPerHost
)
149 if (count
>= MaxClientsPerHost
)
151 if ((time(NULL
) - last_dos
) >= 60)
153 last_dos
= time(NULL
);
154 LogMessage(L_WARN
, "Possible DoS attack - more than %d clients connecting from %s!",
155 MaxClientsPerHost
, Clients
[i
].http
.hostname
);
159 closesocket(con
->http
.fd
);
168 * Get the hostname or format the IP address as needed...
172 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
173 sizeof(con
->http
.hostname
));
177 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
178 sizeof(con
->http
.hostname
));
181 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
184 * Map accesses from the loopback interface to "localhost"...
187 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
189 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
192 * Map accesses from the same host to the server name.
195 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
198 if (hostname
== NULL
&& HostNameLookups
== 2)
201 * Can't have an unresolved IP address with double-lookups enabled...
204 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
208 closesocket(con
->http
.fd
);
213 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
218 if (HostNameLookups
== 2)
221 * Do double lookups as needed...
224 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
227 * See if the hostname maps to the same IP address...
230 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
233 * Not the right type of address...
241 * Compare all of the addresses against this one...
244 for (i
= 0; host
->h_addr_list
[i
]; i
++)
246 httpAddrLoad(host
, 0, i
, &temp
);
248 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
252 if (!host
->h_addr_list
[i
])
260 * Can't have a hostname that doesn't resolve to the same IP address
261 * with double-lookups enabled...
264 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
268 closesocket(con
->http
.fd
);
273 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
280 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
281 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
282 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
284 #endif /* AF_INET6 */
285 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
286 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
289 * Using TCP_NODELAY improves responsiveness, especially on systems
290 * with a slow loopback interface... Since we write large buffers
291 * when sending print files and requests, there shouldn't be any
292 * performance penalty for this...
296 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
299 * Close this file on all execs...
302 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
305 * Add the socket to the select() input mask.
308 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
310 FD_SET(con
->http
.fd
, InputSet
);
315 * Temporarily suspend accept()'s until we lose a client...
318 if (NumClients
== MaxClients
)
323 * See if we are connecting on a secure port...
326 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
329 * https connection; go secure...
332 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
336 #endif /* HAVE_SSL */
341 * 'CloseAllClients()' - Close all remote clients immediately.
345 CloseAllClients(void)
347 while (NumClients
> 0)
348 CloseClient(Clients
);
353 * 'CloseClient()' - Close a remote client.
357 CloseClient(client_t
*con
) /* I - Client to close */
359 #if defined(HAVE_LIBSSL)
360 SSL_CTX
*context
; /* Context for encryption */
361 SSL
*conn
; /* Connection for encryption */
362 unsigned long error
; /* Error code */
363 #elif defined(HAVE_GNUTLS)
364 http_tls_t
*conn
; /* TLS connection information */
365 int error
; /* Error code */
366 gnutls_certificate_server_credentials
*credentials
;
367 /* TLS credentials */
368 #endif /* HAVE_GNUTLS */
371 LogMessage(L_DEBUG
, "CloseClient() %d", con
->http
.fd
);
373 if (con
->http
.input_set
)
374 free(con
->http
.input_set
);
376 httpClearCookie(HTTP(con
));
378 ClearString(&con
->filename
);
379 ClearString(&con
->command
);
380 ClearString(&con
->options
);
384 * Shutdown encryption as needed...
390 conn
= (SSL
*)(con
->http
.tls
);
391 context
= SSL_get_SSL_CTX(conn
);
393 switch (SSL_shutdown(conn
))
396 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
399 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
401 while ((error
= ERR_get_error()) != 0)
402 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
406 SSL_CTX_free(context
);
409 # elif defined(HAVE_GNUTLS)
410 conn
= (http_tls_t
*)(con
->http
.tls
);
411 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
413 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
416 case GNUTLS_E_SUCCESS
:
417 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
420 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
424 gnutls_deinit(conn
->session
);
425 gnutls_certificate_free_credentials(*credentials
);
429 # elif defined(HAVE_CDSASSL)
430 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
431 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
432 # endif /* HAVE_LIBSSL */
434 con
->http
.tls
= NULL
;
436 #endif /* HAVE_SSL */
439 * Close the socket and clear the file from the input set for select()...
442 if (con
->http
.fd
>= 0)
444 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
447 FD_CLR(con
->http
.fd
, InputSet
);
448 FD_CLR(con
->http
.fd
, OutputSet
);
452 if (con
->pipe_pid
!= 0)
454 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet...",
456 FD_CLR(con
->file
, InputSet
);
462 * Close the open data file...
466 kill(con
->pipe_pid
, SIGKILL
);
468 LogMessage(L_DEBUG2
, "CloseClient() %d Closing data file %d.",
469 con
->http
.fd
, con
->file
);
470 LogMessage(L_DEBUG2
, "CloseClient() %d Removing fd %d from InputSet.",
471 con
->http
.fd
, con
->file
);
473 FD_CLR(con
->file
, InputSet
);
480 ippDelete(con
->request
);
486 ippDelete(con
->response
);
487 con
->response
= NULL
;
492 cupsLangFree(con
->language
);
493 con
->language
= NULL
;
497 * Re-enable new client connections if we are going back under the
501 if (NumClients
== MaxClients
)
505 * Compact the list of clients as necessary...
510 if (con
< (Clients
+ NumClients
))
511 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
516 * 'EncryptClient()' - Enable encryption for the client...
519 int /* O - 1 on success, 0 on error */
520 EncryptClient(client_t
*con
) /* I - Client to encrypt */
522 #if defined HAVE_LIBSSL
523 SSL_CTX
*context
; /* Context for encryption */
524 SSL
*conn
; /* Connection for encryption */
525 unsigned long error
; /* Error code */
529 * Create the SSL context and accept the connection...
532 context
= SSL_CTX_new(SSLv23_server_method());
534 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
535 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
537 conn
= SSL_new(context
);
539 SSL_set_fd(conn
, con
->http
.fd
);
540 if (SSL_accept(conn
) != 1)
542 while ((error
= ERR_get_error()) != 0)
543 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
545 SSL_CTX_free(context
);
550 con
->http
.tls
= conn
;
553 #elif defined(HAVE_GNUTLS)
554 http_tls_t
*conn
; /* TLS session object */
555 int error
; /* Error code */
556 gnutls_certificate_server_credentials
*credentials
;
557 /* TLS credentials */
560 * Create the SSL object and perform the SSL handshake...
563 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
568 credentials
= (gnutls_certificate_server_credentials
*)
569 malloc(sizeof(gnutls_certificate_server_credentials
));
570 if (credentials
== NULL
)
576 gnutls_certificate_allocate_credentials(credentials
);
577 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
578 ServerKey
, GNUTLS_X509_FMT_PEM
);
580 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
581 gnutls_set_default_priority(conn
->session
);
582 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
583 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
585 error
= gnutls_handshake(conn
->session
);
587 if (error
!= GNUTLS_E_SUCCESS
)
589 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
590 gnutls_deinit(conn
->session
);
591 gnutls_certificate_free_credentials(*credentials
);
597 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
600 conn
->credentials
= credentials
;
601 con
->http
.tls
= conn
;
604 #elif defined(HAVE_CDSASSL)
605 OSStatus error
; /* Error info */
606 SSLContextRef conn
; /* New connection */
607 SSLProtocol tryVersion
; /* Protocol version */
608 const char *hostName
; /* Local hostname */
609 int allowExpired
; /* Allow expired certificates? */
610 int allowAnyRoot
; /* Allow any root certificate? */
611 SSLProtocol
*negVersion
; /* Negotiated protocol version */
612 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
613 CFArrayRef
*peerCerts
; /* Certificates */
617 error
= SSLNewContext(true, &conn
);
622 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
625 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
628 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
632 hostName
= ServerName
; /* MRS: ??? */
633 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
636 /* have to do these options befor setting server certs */
637 if (!error
&& allowExpired
)
638 error
= SSLSetAllowsExpiredCerts(conn
, true);
640 if (!error
&& allowAnyRoot
)
641 error
= SSLSetAllowsAnyRoot(conn
, true);
643 if (!error
&& ServerCertificatesArray
!= NULL
)
644 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
647 * Perform SSL/TLS handshake
652 error
= SSLHandshake(conn
);
654 while (error
== errSSLWouldBlock
);
658 LogMessage(L_ERROR
, "EncryptClient: %d", error
);
660 con
->http
.error
= error
;
661 con
->http
.status
= HTTP_ERROR
;
664 SSLDisposeContext(conn
);
669 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
671 con
->http
.tls
= conn
;
676 #endif /* HAVE_GNUTLS */
681 * 'IsCGI()' - Is the resource a CGI script/program?
684 int /* O - 1 = CGI, 0 = file */
685 IsCGI(client_t
*con
, /* I - Client connection */
686 const char *filename
, /* I - Real filename */
687 struct stat
*filestats
, /* I - File information */
688 mime_type_t
*type
) /* I - MIME type */
690 const char *options
; /* Options on URL */
693 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
694 con
, filename
, filestats
, type
? type
->super
: "unknown",
695 type
? type
->type
: "unknown");
698 * Get the options, if any...
701 if ((options
= strchr(con
->uri
, '?')) != NULL
)
705 * Check for known types...
708 if (strcasecmp(type
->super
, "application"))
710 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
714 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
715 (filestats
->st_mode
& 0111))
718 * "application/x-httpd-cgi" is a CGI script.
721 SetString(&con
->command
, filename
);
723 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
726 SetStringf(&con
->options
, "%s %s", filename
, options
);
728 SetStringf(&con
->options
, "%s", filename
);
730 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
731 con
->command
, con
->options
);
736 else if (!strcasecmp(type
->type
, "x-httpd-java"))
739 * "application/x-httpd-java" is a Java servlet.
742 SetString(&con
->command
, CUPS_JAVA
);
745 SetStringf(&con
->options
, "java %s %s", filename
, options
);
747 SetStringf(&con
->options
, "java %s", filename
);
749 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
750 con
->command
, con
->options
);
754 #endif /* HAVE_JAVA */
756 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
759 * "application/x-httpd-perl" is a Perl page.
762 SetString(&con
->command
, CUPS_PERL
);
765 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
767 SetStringf(&con
->options
, "perl %s", filename
);
769 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
770 con
->command
, con
->options
);
774 #endif /* HAVE_PERL */
776 else if (!strcasecmp(type
->type
, "x-httpd-php"))
779 * "application/x-httpd-php" is a PHP page.
782 SetString(&con
->command
, CUPS_PHP
);
785 SetStringf(&con
->options
, "php %s %s", filename
, options
);
787 SetStringf(&con
->options
, "php %s", filename
);
789 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
790 con
->command
, con
->options
);
794 #endif /* HAVE_PHP */
796 else if (!strcasecmp(type
->type
, "x-httpd-python"))
799 * "application/x-httpd-python" is a Python page.
802 SetString(&con
->command
, CUPS_PYTHON
);
805 SetStringf(&con
->options
, "python %s %s", filename
, options
);
807 SetStringf(&con
->options
, "python %s", filename
);
809 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
810 con
->command
, con
->options
);
814 #endif /* HAVE_PYTHON */
816 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
823 * 'ReadClient()' - Read data from a client.
826 int /* O - 1 on success, 0 on error */
827 ReadClient(client_t
*con
) /* I - Client to read from */
829 char line
[32768], /* Line from client... */
830 operation
[64], /* Operation code from socket */
831 version
[64]; /* HTTP version number string */
832 int major
, minor
; /* HTTP version numbers */
833 http_status_t status
; /* Transfer status */
834 ipp_state_t ipp_state
; /* State of IPP transfer */
835 int bytes
; /* Number of bytes to POST */
836 char *filename
; /* Name of file for GET/HEAD */
837 char buf
[1024]; /* Buffer for real filename */
838 struct stat filestats
; /* File information */
839 mime_type_t
*type
; /* MIME type of file */
840 printer_t
*p
; /* Printer */
841 location_t
*best
; /* Best match for authentication */
842 static unsigned request_id
= 0;/* Request ID for temp files */
845 status
= HTTP_CONTINUE
;
847 LogMessage(L_DEBUG2
, "ReadClient() %d, used=%d", con
->http
.fd
,
856 switch (con
->http
.state
)
860 * See if we've received a request line...
863 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
870 * Ignore blank request lines...
877 * Clear other state variables...
880 httpClearFields(HTTP(con
));
882 con
->http
.activity
= time(NULL
);
883 con
->http
.version
= HTTP_1_0
;
884 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
885 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
886 con
->http
.data_remaining
= 0;
887 con
->operation
= HTTP_WAITING
;
891 con
->username
[0] = '\0';
892 con
->password
[0] = '\0';
895 ClearString(&con
->command
);
896 ClearString(&con
->options
);
898 if (con
->language
!= NULL
)
900 cupsLangFree(con
->language
);
901 con
->language
= NULL
;
905 * Grab the request line...
908 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
911 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
912 SendError(con
, HTTP_BAD_REQUEST
);
916 con
->http
.version
= HTTP_0_9
;
919 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
921 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
922 SendError(con
, HTTP_BAD_REQUEST
);
929 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
930 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
931 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
933 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
937 SendError(con
, HTTP_NOT_SUPPORTED
);
945 * Handle full URLs in the request line...
948 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
950 char method
[HTTP_MAX_URI
], /* Method/scheme */
951 userpass
[HTTP_MAX_URI
], /* Username:password */
952 hostname
[HTTP_MAX_URI
], /* Hostname */
953 resource
[HTTP_MAX_URI
]; /* Resource path */
954 int port
; /* Port number */
958 * Separate the URI into its components...
961 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
964 * Only allow URIs with the servername, localhost, or an IP
968 if (strcasecmp(hostname
, ServerName
) &&
969 strcasecmp(hostname
, "localhost") &&
970 !isdigit(hostname
[0]))
973 * Nope, we don't do proxies...
976 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
977 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
983 * Copy the resource portion back into the URI; both resource and
984 * con->uri are HTTP_MAX_URI bytes in size...
987 strcpy(con
->uri
, resource
);
991 * Process the request...
994 if (strcmp(operation
, "GET") == 0)
995 con
->http
.state
= HTTP_GET
;
996 else if (strcmp(operation
, "PUT") == 0)
997 con
->http
.state
= HTTP_PUT
;
998 else if (strcmp(operation
, "POST") == 0)
999 con
->http
.state
= HTTP_POST
;
1000 else if (strcmp(operation
, "DELETE") == 0)
1001 con
->http
.state
= HTTP_DELETE
;
1002 else if (strcmp(operation
, "TRACE") == 0)
1003 con
->http
.state
= HTTP_TRACE
;
1004 else if (strcmp(operation
, "OPTIONS") == 0)
1005 con
->http
.state
= HTTP_OPTIONS
;
1006 else if (strcmp(operation
, "HEAD") == 0)
1007 con
->http
.state
= HTTP_HEAD
;
1010 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1011 SendError(con
, HTTP_BAD_REQUEST
);
1012 ShutdownClient(con
);
1016 con
->start
= time(NULL
);
1017 con
->operation
= con
->http
.state
;
1019 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
1020 operation
, con
->uri
,
1021 con
->http
.version
/ 100, con
->http
.version
% 100);
1023 con
->http
.status
= HTTP_OK
;
1033 * Parse incoming parameters until the status changes...
1036 status
= httpUpdate(HTTP(con
));
1038 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1040 SendError(con
, HTTP_BAD_REQUEST
);
1041 ShutdownClient(con
);
1047 break; /* Anti-compiler-warning-code */
1051 * Handle new transfers...
1054 if (status
== HTTP_OK
)
1056 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1057 con
->language
= cupsLangGet(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1059 con
->language
= cupsLangGet(DefaultLanguage
);
1063 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1065 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1067 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1068 con
->http
.version
>= HTTP_1_1
)
1071 * HTTP/1.1 and higher require the "Host:" field...
1074 if (!SendError(con
, HTTP_BAD_REQUEST
))
1080 else if (con
->operation
== HTTP_OPTIONS
)
1083 * Do OPTIONS command...
1086 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1087 best
->type
!= AUTH_NONE
)
1089 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1096 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1097 con
->http
.tls
== NULL
)
1101 * Do encryption stuff...
1104 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1110 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1111 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1112 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1113 httpPrintf(HTTP(con
), "\r\n");
1117 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1122 #endif /* HAVE_SSL */
1125 if (con
->http
.expect
)
1127 /**** TODO: send expected header ****/
1130 if (!SendHeader(con
, HTTP_OK
, NULL
))
1136 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1137 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1138 httpPrintf(HTTP(con
), "\r\n");
1140 else if (strstr(con
->uri
, "..") != NULL
)
1143 * Protect against malicious users!
1146 if (!SendError(con
, HTTP_FORBIDDEN
))
1154 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1155 con
->http
.tls
== NULL
)
1159 * Do encryption stuff...
1162 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1168 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1169 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1170 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1171 httpPrintf(HTTP(con
), "\r\n");
1175 status
= IsAuthorized(con
);
1177 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1182 #endif /* HAVE_SSL */
1185 if (status
!= HTTP_OK
)
1187 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1189 SendError(con
, status
);
1190 ShutdownClient(con
);
1194 if (con
->http
.expect
)
1196 /**** TODO: send expected header ****/
1199 switch (con
->http
.state
)
1201 case HTTP_GET_SEND
:
1202 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1203 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1206 * Send PPD file - get the real printer name since printer
1207 * names are not case sensitive but filenames can be...
1210 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1212 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1213 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1216 if (!SendError(con
, HTTP_NOT_FOUND
))
1226 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1227 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1228 strncmp(con
->uri
, "/printers", 9) == 0 ||
1229 strncmp(con
->uri
, "/classes", 8) == 0 ||
1230 strncmp(con
->uri
, "/jobs", 5) == 0)
1233 * Send CGI output...
1236 if (strncmp(con
->uri
, "/admin", 6) == 0)
1238 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1239 SetString(&con
->options
, con
->uri
+ 6);
1241 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1243 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1244 SetString(&con
->options
, con
->uri
+ 9);
1246 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1248 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1249 SetString(&con
->options
, con
->uri
+ 8);
1253 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1254 SetString(&con
->options
, con
->uri
+ 5);
1257 if (con
->options
[0] == '/')
1258 cups_strcpy(con
->options
, con
->options
+ 1);
1260 if (!SendCommand(con
, con
->command
, con
->options
))
1262 if (!SendError(con
, HTTP_NOT_FOUND
))
1269 LogRequest(con
, HTTP_OK
);
1271 if (con
->http
.version
<= HTTP_1_0
)
1272 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1274 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1275 (strchr(con
->uri
+ 12, '/') != NULL
||
1276 strlen(con
->uri
) == 12))
1279 * GET can only be done to configuration files under
1283 if (!SendError(con
, HTTP_FORBIDDEN
))
1297 if ((filename
= get_file(con
, &filestats
, buf
,
1298 sizeof(buf
))) == NULL
)
1300 if (!SendError(con
, HTTP_NOT_FOUND
))
1309 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1311 if (IsCGI(con
, filename
, &filestats
, type
))
1313 if (!SendCommand(con
, con
->command
, con
->options
))
1315 if (!SendError(con
, HTTP_NOT_FOUND
))
1322 LogRequest(con
, HTTP_OK
);
1324 if (con
->http
.version
<= HTTP_1_0
)
1325 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1329 if (!check_if_modified(con
, &filestats
))
1331 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1340 strcpy(line
, "text/plain");
1342 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1344 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1353 case HTTP_POST_RECV
:
1355 * See if the POST request includes a Content-Length field, and if
1356 * so check the length against any limits that are set...
1359 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1360 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1362 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1363 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1367 * Request too large...
1370 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1378 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1381 * Negative content lengths are invalid!
1384 if (!SendError(con
, HTTP_BAD_REQUEST
))
1394 * See what kind of POST request this is; for IPP requests the
1395 * content-type field will be "application/ipp"...
1398 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1399 con
->request
= ippNew();
1400 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1401 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1402 strncmp(con
->uri
, "/printers", 9) == 0 ||
1403 strncmp(con
->uri
, "/classes", 8) == 0 ||
1404 strncmp(con
->uri
, "/jobs", 5) == 0)
1410 if (strncmp(con
->uri
, "/admin", 6) == 0)
1412 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1413 SetString(&con
->options
, con
->uri
+ 6);
1415 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1417 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1418 SetString(&con
->options
, con
->uri
+ 9);
1420 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1422 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1423 SetString(&con
->options
, con
->uri
+ 8);
1427 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1428 SetString(&con
->options
, con
->uri
+ 5);
1431 if (con
->options
[0] == '/')
1432 cups_strcpy(con
->options
, con
->options
+ 1);
1434 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
1435 con
->http
.fd
, con
->command
, con
->options
);
1437 if (con
->http
.version
<= HTTP_1_0
)
1438 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1446 if ((filename
= get_file(con
, &filestats
, buf
,
1447 sizeof(buf
))) == NULL
)
1449 if (!SendError(con
, HTTP_NOT_FOUND
))
1458 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1460 if (!IsCGI(con
, filename
, &filestats
, type
))
1463 * Only POST to CGI's...
1466 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1475 case HTTP_PUT_RECV
:
1477 * Validate the resource name...
1480 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1481 strchr(con
->uri
+ 12, '/') != NULL
||
1482 strlen(con
->uri
) == 12)
1485 * PUT can only be done to configuration files under
1489 if (!SendError(con
, HTTP_FORBIDDEN
))
1499 * See if the PUT request includes a Content-Length field, and if
1500 * so check the length against any limits that are set...
1503 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1504 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1506 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1507 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1511 * Request too large...
1514 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1524 * Open a temporary file to hold the request...
1527 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1528 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1529 fchmod(con
->file
, 0640);
1530 fchown(con
->file
, User
, Group
);
1532 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1533 con
->filename
, con
->file
);
1537 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1547 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1548 ShutdownClient(con
);
1552 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1553 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1556 * Send PPD file - get the real printer name since printer
1557 * names are not case sensitive but filenames can be...
1560 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1562 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1563 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1566 if (!SendError(con
, HTTP_NOT_FOUND
))
1576 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1577 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1578 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1579 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1580 strncmp(con
->uri
, "/jobs/", 6) == 0)
1586 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1592 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1598 LogRequest(con
, HTTP_OK
);
1600 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1601 (strchr(con
->uri
+ 12, '/') != NULL
||
1602 strlen(con
->uri
) == 12))
1605 * HEAD can only be done to configuration files under
1609 if (!SendError(con
, HTTP_FORBIDDEN
))
1617 else if ((filename
= get_file(con
, &filestats
, buf
,
1618 sizeof(buf
))) == NULL
)
1620 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1626 LogRequest(con
, HTTP_NOT_FOUND
);
1628 else if (!check_if_modified(con
, &filestats
))
1630 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1636 LogRequest(con
, HTTP_NOT_MODIFIED
);
1644 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1646 strcpy(line
, "text/plain");
1648 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1650 if (!SendHeader(con
, HTTP_OK
, line
))
1656 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1657 httpGetDateString(filestats
.st_mtime
)) < 0)
1663 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1664 (unsigned long)filestats
.st_size
) < 0)
1670 LogRequest(con
, HTTP_OK
);
1673 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1679 con
->http
.state
= HTTP_WAITING
;
1683 break; /* Anti-compiler-warning-code */
1689 * Handle any incoming data...
1692 switch (con
->http
.state
)
1694 case HTTP_PUT_RECV
:
1695 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1697 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1698 con
->http
.data_remaining
, con
->file
);
1700 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1707 con
->bytes
+= bytes
;
1709 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1710 con
->http
.fd
, bytes
, con
->file
);
1712 if (write(con
->file
, line
, bytes
) < bytes
)
1714 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1715 bytes
, con
->filename
, strerror(errno
));
1717 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1722 unlink(con
->filename
);
1723 ClearString(&con
->filename
);
1725 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1733 if (con
->http
.state
== HTTP_WAITING
)
1736 * End of file, see how big it is...
1739 fstat(con
->file
, &filestats
);
1741 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1742 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1747 if (filestats
.st_size
> MaxRequestSize
&&
1751 * Request is too big; remove it and send an error...
1754 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1755 con
->http
.fd
, con
->filename
);
1756 unlink(con
->filename
);
1757 ClearString(&con
->filename
);
1759 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1767 * Install the configuration file...
1770 status
= install_conf_file(con
);
1773 * Return the status to the client...
1776 if (!SendError(con
, status
))
1784 case HTTP_POST_RECV
:
1785 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1787 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1788 con
->http
.data_remaining
, con
->file
);
1790 if (con
->request
!= NULL
)
1793 * Grab any request data from the connection...
1796 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1798 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1801 if (!SendError(con
, HTTP_BAD_REQUEST
))
1807 ShutdownClient(con
);
1810 else if (ipp_state
!= IPP_DATA
)
1813 con
->bytes
+= ippLength(con
->request
);
1816 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
1819 * Create a file as needed for the request data...
1822 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1823 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1824 fchmod(con
->file
, 0640);
1825 fchown(con
->file
, User
, Group
);
1827 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1828 con
->filename
, con
->file
);
1832 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1840 if (con
->http
.state
!= HTTP_POST_SEND
)
1842 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1849 con
->bytes
+= bytes
;
1851 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1852 con
->http
.fd
, bytes
, con
->file
);
1854 if (write(con
->file
, line
, bytes
) < bytes
)
1856 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1857 bytes
, con
->filename
, strerror(errno
));
1859 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1864 unlink(con
->filename
);
1865 ClearString(&con
->filename
);
1867 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1874 else if (con
->http
.state
== HTTP_POST_RECV
)
1878 else if (con
->http
.state
!= HTTP_POST_SEND
)
1885 if (con
->http
.state
== HTTP_POST_SEND
)
1889 fstat(con
->file
, &filestats
);
1891 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1892 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1897 if (filestats
.st_size
> MaxRequestSize
&&
1901 * Request is too big; remove it and send an error...
1904 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1905 con
->http
.fd
, con
->filename
);
1906 unlink(con
->filename
);
1907 ClearString(&con
->filename
);
1912 * Delete any IPP request data...
1915 ippDelete(con
->request
);
1916 con
->request
= NULL
;
1919 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1928 if (!SendCommand(con
, con
->command
, con
->options
))
1930 if (!SendError(con
, HTTP_NOT_FOUND
))
1937 LogRequest(con
, HTTP_OK
);
1942 return (ProcessIPPRequest(con
));
1947 break; /* Anti-compiler-warning-code */
1950 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1961 * 'SendCommand()' - Send output from a command via HTTP.
1965 SendCommand(client_t
*con
,
1973 fd
= open(con
->filename
, O_RDONLY
);
1975 fd
= open("/dev/null", O_RDONLY
);
1977 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
1981 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
1983 LogMessage(L_DEBUG
, "SendCommand() %d file=%d", con
->http
.fd
, con
->file
);
1985 if (con
->pipe_pid
== 0)
1988 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1990 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
1991 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
1994 FD_SET(con
->file
, InputSet
);
1995 FD_SET(con
->http
.fd
, OutputSet
);
1997 if (!SendHeader(con
, HTTP_OK
, NULL
))
2000 if (con
->http
.version
== HTTP_1_1
)
2002 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2004 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2008 con
->got_fields
= 0;
2016 * 'SendError()' - Send an error message via HTTP.
2019 int /* O - 1 if successful, 0 otherwise */
2020 SendError(client_t
*con
, /* I - Connection */
2021 http_status_t code
) /* I - Error code */
2023 char message
[1024]; /* Message for user */
2027 * Put the request in the access_log file...
2030 if (con
->operation
> HTTP_WAITING
)
2031 LogRequest(con
, code
);
2033 LogMessage(L_DEBUG
, "SendError() %d code=%d", con
->http
.fd
, code
);
2036 * To work around bugs in some proxies, don't use Keep-Alive for some
2040 if (code
>= HTTP_BAD_REQUEST
)
2041 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2044 * Send an error message back to the client. If the error code is a
2045 * 400 or 500 series, make sure the message contains some text, too!
2048 if (!SendHeader(con
, code
, NULL
))
2052 if (code
== HTTP_UPGRADE_REQUIRED
)
2053 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2056 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2058 #endif /* HAVE_SSL */
2060 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2061 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2063 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2067 if (code
>= HTTP_BAD_REQUEST
)
2070 * Send a human-readable error message.
2073 snprintf(message
, sizeof(message
),
2074 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2075 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2076 code
, httpStatus(code
), httpStatus(code
),
2077 con
->language
? con
->language
->messages
[code
] :
2080 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
2082 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2083 (int)strlen(message
)) < 0)
2085 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2087 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2090 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2093 con
->http
.state
= HTTP_WAITING
;
2100 * 'SendFile()' - Send a file via HTTP.
2104 SendFile(client_t
*con
,
2108 struct stat
*filestats
)
2110 con
->file
= open(filename
, O_RDONLY
);
2112 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
2117 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2121 if (!SendHeader(con
, code
, type
))
2124 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2126 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2127 (unsigned long)filestats
->st_size
) < 0)
2129 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2132 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2134 FD_SET(con
->http
.fd
, OutputSet
);
2141 * 'SendHeader()' - Send an HTTP request.
2144 int /* O - 1 on success, 0 on failure */
2145 SendHeader(client_t
*con
, /* I - Client to send to */
2146 http_status_t code
, /* I - HTTP status code */
2147 char *type
) /* I - MIME type of document */
2149 location_t
*loc
; /* Authentication location */
2152 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2153 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2155 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2157 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
2159 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2161 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2163 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2166 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2167 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2170 if (code
== HTTP_UNAUTHORIZED
)
2173 * This already succeeded in IsAuthorized...
2176 loc
= FindBest(con
->uri
, con
->http
.state
);
2178 if (loc
->type
!= AUTH_DIGEST
)
2180 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2185 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
2186 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2190 if (con
->language
!= NULL
)
2192 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2193 con
->language
->language
) < 0)
2197 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
2198 cupsLangEncoding(con
->language
)) < 0)
2201 else if (type
!= NULL
)
2202 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2210 * 'ShutdownClient()' - Shutdown the receiving end of a connection.
2214 ShutdownClient(client_t
*con
) /* I - Client connection */
2217 * Shutdown the receiving end of the socket, since the client
2218 * still needs to read the error message...
2221 shutdown(con
->http
.fd
, 0);
2225 * Update the activity time so that we timeout after 30 seconds rather
2226 * then the current Timeout setting (300 by default). This prevents
2227 * some DoS situations...
2230 con
->http
.activity
= time(NULL
) - Timeout
+ 30;
2232 LogMessage(L_DEBUG2
, "ShutdownClient: Removing fd %d from InputSet...",
2235 FD_CLR(con
->http
.fd
, InputSet
);
2240 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2246 int bytes
; /* Number of bytes read */
2247 char *lineptr
, /* Pointer to end of line in buffer */
2248 *message
; /* Pointer to message text */
2249 int loglevel
; /* Log level for message */
2250 static int bufused
= 0; /* Number of bytes used in buffer */
2251 static char buffer
[1024]; /* Status buffer */
2254 if ((bytes
= read(CGIPipes
[0], buffer
+ bufused
,
2255 sizeof(buffer
) - bufused
- 1)) > 0)
2258 buffer
[bufused
] = '\0';
2259 lineptr
= strchr(buffer
, '\n');
2261 else if (bytes
< 0 && errno
== EINTR
)
2265 lineptr
= buffer
+ bufused
;
2269 if (bytes
== 0 && bufused
== 0)
2272 while (lineptr
!= NULL
)
2275 * Terminate each line and process it...
2281 * Figure out the logging level...
2284 if (strncmp(buffer
, "EMERG:", 6) == 0)
2287 message
= buffer
+ 6;
2289 else if (strncmp(buffer
, "ALERT:", 6) == 0)
2292 message
= buffer
+ 6;
2294 else if (strncmp(buffer
, "CRIT:", 5) == 0)
2297 message
= buffer
+ 5;
2299 else if (strncmp(buffer
, "ERROR:", 6) == 0)
2302 message
= buffer
+ 6;
2304 else if (strncmp(buffer
, "WARNING:", 8) == 0)
2307 message
= buffer
+ 8;
2309 else if (strncmp(buffer
, "NOTICE:", 6) == 0)
2311 loglevel
= L_NOTICE
;
2312 message
= buffer
+ 6;
2314 else if (strncmp(buffer
, "INFO:", 5) == 0)
2317 message
= buffer
+ 5;
2319 else if (strncmp(buffer
, "DEBUG:", 6) == 0)
2322 message
= buffer
+ 6;
2324 else if (strncmp(buffer
, "DEBUG2:", 7) == 0)
2326 loglevel
= L_DEBUG2
;
2327 message
= buffer
+ 7;
2329 else if (strncmp(buffer
, "PAGE:", 5) == 0)
2332 message
= buffer
+ 5;
2341 * Skip leading whitespace in the message...
2344 while (isspace(*message
))
2347 LogMessage(loglevel
, "[CGI] %s", message
);
2350 * Copy over the buffer data we've used up...
2353 strcpy(buffer
, lineptr
);
2354 bufused
-= lineptr
- buffer
;
2359 lineptr
= strchr(buffer
, '\n');
2365 * Fatal error on pipe - should never happen!
2368 LogMessage(L_ERROR
, "UpdateCGI: error reading from CGI error pipe - %s",
2375 * 'WriteClient()' - Write data to a client as needed.
2378 int /* O - 1 if success, 0 if fail */
2379 WriteClient(client_t
*con
) /* I - Client connection */
2381 int bytes
; /* Number of bytes written */
2382 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
2383 char *bufptr
; /* Pointer into buffer */
2384 ipp_state_t ipp_state
; /* IPP state value */
2387 if (con
->http
.state
!= HTTP_GET_SEND
&&
2388 con
->http
.state
!= HTTP_POST_SEND
)
2391 if (con
->response
!= NULL
)
2393 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2394 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2396 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
2398 if (con
->pipe_pid
&& !con
->got_fields
)
2401 * Inspect the data for Content-Type and other fields.
2406 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2407 if (*bufptr
== '\n')
2410 * Send line to client...
2413 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2417 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2418 LogMessage(L_DEBUG2
, "WriteClient() %d %s", con
->http
.fd
, buf
);
2424 bytes
-= (bufptr
- buf
);
2425 memcpy(buf
, bufptr
, bytes
+ 1);
2429 * See if the line was empty...
2432 if (con
->field_col
== 0)
2433 con
->got_fields
= 1;
2437 else if (*bufptr
!= '\r')
2440 if (bytes
> 0 && !con
->got_fields
)
2443 * Remaining text needs to go out...
2446 httpPrintf(HTTP(con
), "%s", buf
);
2448 con
->http
.activity
= time(NULL
);
2451 else if (bytes
== 0)
2453 con
->http
.activity
= time(NULL
);
2458 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2464 con
->bytes
+= bytes
;
2469 LogRequest(con
, HTTP_OK
);
2471 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2473 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2480 con
->http
.state
= HTTP_WAITING
;
2482 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from OutputSet...",
2485 FD_CLR(con
->http
.fd
, OutputSet
);
2489 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from InputSet...",
2491 FD_CLR(con
->file
, InputSet
);
2494 kill(con
->pipe_pid
, SIGTERM
);
2496 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
2497 con
->http
.fd
, con
->file
);
2506 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
2507 con
->http
.fd
, con
->filename
);
2508 unlink(con
->filename
);
2509 ClearString(&con
->filename
);
2512 if (con
->request
!= NULL
)
2514 ippDelete(con
->request
);
2515 con
->request
= NULL
;
2518 if (con
->response
!= NULL
)
2520 ippDelete(con
->response
);
2521 con
->response
= NULL
;
2524 ClearString(&con
->command
);
2525 ClearString(&con
->options
);
2527 if (!con
->http
.keep_alive
)
2535 LogMessage(L_DEBUG2
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
2537 con
->http
.activity
= time(NULL
);
2544 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2547 static int /* O - 1 if modified since */
2548 check_if_modified(client_t
*con
, /* I - Client connection */
2549 struct stat
*filestats
) /* I - File information */
2551 char *ptr
; /* Pointer into field */
2552 time_t date
; /* Time/date value */
2553 int size
; /* Size/length value */
2558 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2563 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
2566 while (*ptr
!= '\0')
2568 while (isspace(*ptr
) || *ptr
== ';')
2571 if (strncasecmp(ptr
, "length=", 7) == 0)
2576 while (isdigit(*ptr
))
2579 else if (isalpha(*ptr
))
2581 date
= httpGetDateTime(ptr
);
2582 while (*ptr
!= '\0' && *ptr
!= ';')
2587 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
2588 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2589 (int)filestats
->st_mtime
);
2591 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2592 (date
< filestats
->st_mtime
&& date
!= 0) ||
2593 (size
== 0 && date
== 0));
2598 * 'decode_auth()' - Decode an authorization string.
2602 decode_auth(client_t
*con
) /* I - Client to decode to */
2604 char *s
, /* Authorization string */
2605 value
[1024]; /* Value string */
2606 const char *username
; /* Certificate username */
2610 * Decode the string...
2613 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2615 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2618 if (strncmp(s
, "Basic", 5) == 0)
2624 httpDecode64(value
, s
);
2627 * Pull the username and password out...
2630 if ((s
= strchr(value
, ':')) == NULL
)
2632 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2633 con
->http
.fd
, value
);
2639 strlcpy(con
->username
, value
, sizeof(con
->username
));
2640 strlcpy(con
->password
, s
, sizeof(con
->password
));
2642 else if (strncmp(s
, "Local", 5) == 0)
2648 if ((username
= FindCert(s
)) != NULL
)
2649 strlcpy(con
->username
, username
, sizeof(con
->username
));
2651 else if (strncmp(s
, "Digest", 5) == 0)
2654 * Get the username and password from the Digest attributes...
2657 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2659 strlcpy(con
->username
, value
, sizeof(con
->username
));
2661 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2663 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2666 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2667 con
->http
.fd
, con
->username
);
2672 * 'get_file()' - Get a filename and state info.
2675 static char * /* O - Real filename */
2676 get_file(client_t
*con
, /* I - Client connection */
2677 struct stat
*filestats
,/* O - File information */
2678 char *filename
, /* IO - Filename buffer */
2679 int len
) /* I - Buffer length */
2681 int status
; /* Status of filesystem calls */
2682 char *params
; /* Pointer to parameters in URI */
2686 * Need to add DocumentRoot global...
2689 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2690 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2691 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2692 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2693 else if (con
->language
!= NULL
)
2694 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2697 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2699 if ((params
= strchr(filename
, '?')) != NULL
)
2703 * Grab the status for this language; if there isn't a language-specific file
2704 * then fallback to the default one...
2707 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2710 * Drop the language prefix and try the current directory...
2713 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2714 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2716 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2718 status
= stat(filename
, filestats
);
2723 * If we're found a directory, get the index.html file instead...
2726 if (!status
&& S_ISDIR(filestats
->st_mode
))
2728 if (filename
[strlen(filename
) - 1] == '/')
2729 strlcat(filename
, "index.html", len
);
2731 strlcat(filename
, "/index.html", len
);
2733 status
= stat(filename
, filestats
);
2736 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2737 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2747 * 'install_conf_file()' - Install a configuration file.
2750 static http_status_t
/* O - Status */
2751 install_conf_file(client_t
*con
) /* I - Connection */
2753 cups_file_t
*in
, /* Input file */
2754 *out
; /* Output file */
2755 char buffer
[1024]; /* Copy buffer */
2756 int bytes
; /* Number of bytes */
2757 char conffile
[1024], /* Configuration filename */
2758 newfile
[1024], /* New config filename */
2759 oldfile
[1024]; /* Old config filename */
2760 struct stat confinfo
; /* Config file info */
2764 * First construct the filenames...
2767 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2768 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2769 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2771 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2774 * Get the owner, group, and permissions of the configuration file.
2775 * If it doesn't exist, assign it to the User and Group in the
2776 * cupsd.conf file with mode 0640 permissions.
2779 if (stat(conffile
, &confinfo
))
2781 confinfo
.st_uid
= User
;
2782 confinfo
.st_gid
= Group
;
2783 confinfo
.st_mode
= ConfigFilePerm
;
2787 * Open the request file and new config file...
2790 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2792 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2793 con
->filename
, strerror(errno
));
2794 return (HTTP_SERVER_ERROR
);
2797 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2800 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2801 newfile
, strerror(errno
));
2802 return (HTTP_SERVER_ERROR
);
2805 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2806 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2809 * Copy from the request to the new config file...
2812 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2813 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2815 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2816 newfile
, strerror(errno
));
2822 return (HTTP_SERVER_ERROR
);
2826 * Close the files...
2830 if (cupsFileClose(out
))
2832 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2833 newfile
, strerror(errno
));
2837 return (HTTP_SERVER_ERROR
);
2841 * Remove the request file...
2844 unlink(con
->filename
);
2845 ClearString(&con
->filename
);
2848 * Unlink the old backup, rename the current config file to the backup
2849 * filename, and rename the new config file to the config file name...
2852 if (unlink(oldfile
))
2853 if (errno
!= ENOENT
)
2855 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2856 oldfile
, strerror(errno
));
2860 return (HTTP_SERVER_ERROR
);
2863 if (rename(conffile
, oldfile
))
2864 if (errno
!= ENOENT
)
2866 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2867 conffile
, strerror(errno
));
2871 return (HTTP_SERVER_ERROR
);
2874 if (rename(newfile
, conffile
))
2876 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2877 newfile
, strerror(errno
));
2879 rename(oldfile
, conffile
);
2882 return (HTTP_SERVER_ERROR
);
2886 * If the cupsd.conf file was updated, set the NeedReload flag...
2889 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2890 NeedReload
= RELOAD_CUPSD
;
2892 NeedReload
= RELOAD_ALL
;
2895 * Return that the file was created successfully...
2898 return (HTTP_CREATED
);
2903 * 'pipe_command()' - Pipe the output of a command to the remote client.
2906 static int /* O - Process ID */
2907 pipe_command(client_t
*con
, /* I - Client connection */
2908 int infile
, /* I - Standard input for command */
2909 int *outfile
, /* O - Standard output for command */
2910 char *command
, /* I - Command to run */
2911 char *options
) /* I - Options for command */
2913 int i
; /* Looping var */
2914 int pid
; /* Process ID */
2915 char *commptr
; /* Command string pointer */
2916 char *uriptr
; /* URI string pointer */
2917 int fd
; /* Looping var */
2918 int fds
[2]; /* Pipe FDs */
2919 int argc
; /* Number of arguments */
2920 int envc
; /* Number of environment variables */
2921 char argbuf
[10240], /* Argument buffer */
2922 *argv
[100], /* Argument strings */
2923 *envp
[100]; /* Environment variables */
2924 char content_length
[1024], /* CONTENT_LENGTH environment variable */
2925 content_type
[1024], /* CONTENT_TYPE environment variable */
2926 cups_datadir
[1024], /* CUPS_DATADIR environment variable */
2927 cups_serverroot
[1024], /* CUPS_SERVERROOT environment variable */
2928 http_cookie
[1024], /* HTTP_COOKIE environment variable */
2929 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
2930 ipp_port
[1024], /* IPP_PORT environment variable */
2931 lang
[1024], /* LANG environment variable */
2932 ld_library_path
[1024], /* LD_LIBRARY_PATH environment variable */
2933 ld_preload
[1024], /* LD_PRELOAD environment variable */
2934 dyld_library_path
[1024],/* DYLD_LIBRARY_PATH environment variable */
2935 shlib_path
[1024], /* SHLIB_PATH environment variable */
2936 nlspath
[1024], /* NLSPATH environment variable */
2937 query_string
[10240], /* QUERY_STRING env variable */
2938 remote_addr
[1024], /* REMOTE_ADDR environment variable */
2939 remote_host
[1024], /* REMOTE_HOST environment variable */
2940 remote_user
[1024], /* REMOTE_USER environment variable */
2941 script_name
[1024], /* SCRIPT_NAME environment variable */
2942 server_name
[1024], /* SERVER_NAME environment variable */
2943 server_port
[1024], /* SERVER_PORT environment variable */
2944 tmpdir
[1024], /* TMPDIR environment variable */
2945 vg_args
[1024]; /* VG_ARGS environment variable */
2946 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
2947 struct sigaction action
; /* POSIX signal handler */
2948 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
2952 * Copy the command string...
2955 strlcpy(argbuf
, options
, sizeof(argbuf
));
2958 * Parse the string; arguments can be separated by + and are terminated
2964 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
2965 if (*commptr
== ' ' || *commptr
== '+')
2969 while (*commptr
== ' ')
2972 if (*commptr
!= '\0')
2974 argv
[argc
] = commptr
;
2980 else if (*commptr
== '%')
2982 if (commptr
[1] >= '0' && commptr
[1] <= '9')
2983 *commptr
= (commptr
[1] - '0') << 4;
2985 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
2987 if (commptr
[2] >= '0' && commptr
[2] <= '9')
2988 *commptr
|= commptr
[2] - '0';
2990 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
2992 cups_strcpy(commptr
+ 1, commptr
+ 3);
2994 else if (*commptr
== '?')
2999 if (argv
[0][0] == '\0')
3000 argv
[0] = strrchr(command
, '/') + 1;
3003 * Setup the environment variables as needed...
3006 snprintf(lang
, sizeof(lang
), "LANG=%s",
3007 con
->language
? con
->language
->language
: "C");
3008 sprintf(ipp_port
, "IPP_PORT=%d", LocalPort
);
3010 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
3011 sprintf(server_port
, "SERVER_PORT=%d",
3012 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3014 #endif /* AF_INET6 */
3015 sprintf(server_port
, "SERVER_PORT=%d",
3016 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3018 if (strcmp(con
->http
.hostname
, "localhost") == 0)
3019 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
3021 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
3022 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
3023 strcpy(remote_addr
, "REMOTE_ADDR=");
3024 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3025 sizeof(remote_addr
) - 12);
3026 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3027 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
3028 snprintf(cups_datadir
, sizeof(cups_datadir
), "CUPS_DATADIR=%s", DataDir
);
3029 snprintf(cups_serverroot
, sizeof(cups_serverroot
), "CUPS_SERVERROOT=%s", ServerRoot
);
3033 envp
[envc
++] = "PATH=/bin:/usr/bin";
3034 envp
[envc
++] = "SERVER_SOFTWARE=CUPS/1.1";
3035 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3036 if (con
->http
.version
== HTTP_1_1
)
3037 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3038 else if (con
->http
.version
== HTTP_1_0
)
3039 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3041 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3042 envp
[envc
++] = "REDIRECT_STATUS=1";
3043 envp
[envc
++] = "CUPS_SERVER=localhost";
3044 envp
[envc
++] = ipp_port
;
3045 envp
[envc
++] = server_name
;
3046 envp
[envc
++] = server_port
;
3047 envp
[envc
++] = remote_addr
;
3048 envp
[envc
++] = remote_host
;
3049 envp
[envc
++] = remote_user
;
3050 envp
[envc
++] = lang
;
3052 envp
[envc
++] = tmpdir
;
3053 envp
[envc
++] = cups_datadir
;
3054 envp
[envc
++] = cups_serverroot
;
3056 if (getenv("VG_ARGS") != NULL
)
3058 snprintf(vg_args
, sizeof(vg_args
), "VG_ARGS=%s", getenv("VG_ARGS"));
3059 envp
[envc
++] = vg_args
;
3062 if (getenv("LD_LIBRARY_PATH") != NULL
)
3064 snprintf(ld_library_path
, sizeof(ld_library_path
), "LD_LIBRARY_PATH=%s",
3065 getenv("LD_LIBRARY_PATH"));
3066 envp
[envc
++] = ld_library_path
;
3069 if (getenv("LD_PRELOAD") != NULL
)
3071 snprintf(ld_preload
, sizeof(ld_preload
), "LD_PRELOAD=%s",
3072 getenv("LD_PRELOAD"));
3073 envp
[envc
++] = ld_preload
;
3076 if (getenv("DYLD_LIBRARY_PATH") != NULL
)
3078 snprintf(dyld_library_path
, sizeof(dyld_library_path
), "DYLD_LIBRARY_PATH=%s",
3079 getenv("DYLD_LIBRARY_PATH"));
3080 envp
[envc
++] = dyld_library_path
;
3083 if (getenv("SHLIB_PATH") != NULL
)
3085 snprintf(shlib_path
, sizeof(shlib_path
), "SHLIB_PATH=%s",
3086 getenv("SHLIB_PATH"));
3087 envp
[envc
++] = shlib_path
;
3090 if (getenv("NLSPATH") != NULL
)
3092 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
3093 envp
[envc
++] = nlspath
;
3096 if (con
->http
.cookie
)
3098 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3100 envp
[envc
++] = http_cookie
;
3103 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3105 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3106 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3107 envp
[envc
++] = http_user_agent
;
3110 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3111 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3113 envp
[envc
++] = script_name
;
3115 if (con
->operation
== HTTP_GET
)
3117 for (i
= 0; i
< argc
; i
++)
3118 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3119 envp
[envc
++] = "REQUEST_METHOD=GET";
3124 * Add GET form variables after ?...
3129 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
3130 envp
[envc
++] = query_string
;
3135 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3136 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3137 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3139 envp
[envc
++] = "REQUEST_METHOD=POST";
3140 envp
[envc
++] = content_length
;
3141 envp
[envc
++] = content_type
;
3145 * Tell the CGI if we are using encryption...
3148 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3150 envp
[envc
++] = "HTTPS=ON";
3151 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
3156 if (LogLevel
== L_DEBUG2
)
3158 for (i
= 0; i
< argc
; i
++)
3159 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3160 for (i
= 0; i
< envc
; i
++)
3161 LogMessage(L_DEBUG2
, "envp[%d] = \"%s\"", i
, envp
[i
]);
3165 * Create a pipe for the output...
3170 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3171 argv
[0], strerror(errno
));
3176 * Block signals before forking...
3182 * Then execute the command...
3185 if ((pid
= fork()) == 0)
3188 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
3194 * Running as root, so change to a non-priviledged user...
3200 if (setgroups(0, NULL
))
3209 * Reset group membership to just the main one we belong to.
3216 * Update stdin/stdout/stderr...
3222 if (dup(infile
) < 0)
3227 if (dup(fds
[1]) < 0)
3234 * Close extra file descriptors...
3237 for (fd
= 3; fd
< MaxFDs
; fd
++)
3241 * Change umask to restrict permissions on created files...
3247 * Unblock signals before doing the exec...
3251 sigset(SIGTERM
, SIG_DFL
);
3252 sigset(SIGCHLD
, SIG_DFL
);
3253 #elif defined(HAVE_SIGACTION)
3254 memset(&action
, 0, sizeof(action
));
3256 sigemptyset(&action
.sa_mask
);
3257 action
.sa_handler
= SIG_DFL
;
3259 sigaction(SIGTERM
, &action
, NULL
);
3260 sigaction(SIGCHLD
, &action
, NULL
);
3262 signal(SIGTERM
, SIG_DFL
);
3263 signal(SIGCHLD
, SIG_DFL
);
3264 #endif /* HAVE_SIGSET */
3269 * Execute the pipe program; if an error occurs, exit with status 1...
3272 execve(command
, argv
, envp
);
3279 * Error - can't fork!
3282 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3292 * Fork successful - return the PID...
3295 AddCert(pid
, con
->username
);
3297 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3309 #if defined(HAVE_CDSASSL)
3311 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3314 static OSStatus
/* O - -1 on error, 0 on success */
3315 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3316 void *data
, /* I - Data buffer */
3317 size_t *dataLength
) /* IO - Number of bytes */
3319 ssize_t bytes
; /* Number of bytes read */
3322 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3325 *dataLength
= bytes
;
3334 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3337 static OSStatus
/* O - -1 on error, 0 on success */
3338 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3339 const void *data
, /* I - Data buffer */
3340 size_t *dataLength
) /* IO - Number of bytes */
3345 bytes
= write((int)connection
, data
, *dataLength
);
3348 *dataLength
= bytes
;
3354 #endif /* HAVE_CDSASSL */
3358 * End of "$Id: client.c,v 1.91.2.65 2003/07/20 12:51:43 mike Exp $".