2 * "$Id: client.c,v 1.91.2.61 2003/07/19 21:57:46 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 int status
; /* Exit status of pipe command */
360 #if defined(HAVE_LIBSSL)
361 SSL_CTX
*context
; /* Context for encryption */
362 SSL
*conn
; /* Connection for encryption */
363 unsigned long error
; /* Error code */
364 #elif defined(HAVE_GNUTLS)
365 http_tls_t
*conn
; /* TLS connection information */
366 int error
; /* Error code */
367 gnutls_certificate_server_credentials
*credentials
;
368 /* TLS credentials */
369 #endif /* HAVE_GNUTLS */
372 LogMessage(L_DEBUG
, "CloseClient() %d", con
->http
.fd
);
374 if (con
->http
.input_set
)
375 free(con
->http
.input_set
);
377 httpClearCookie(HTTP(con
));
379 ClearString(&con
->filename
);
380 ClearString(&con
->command
);
381 ClearString(&con
->options
);
385 * Shutdown encryption as needed...
391 conn
= (SSL
*)(con
->http
.tls
);
392 context
= SSL_get_SSL_CTX(conn
);
394 switch (SSL_shutdown(conn
))
397 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
400 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
402 while ((error
= ERR_get_error()) != 0)
403 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
407 SSL_CTX_free(context
);
410 # elif defined(HAVE_GNUTLS)
411 conn
= (http_tls_t
*)(con
->http
.tls
);
412 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
414 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
417 case GNUTLS_E_SUCCESS
:
418 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
421 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
425 gnutls_deinit(conn
->session
);
426 gnutls_certificate_free_credentials(*credentials
);
430 # elif defined(HAVE_CDSASSL)
431 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
432 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
433 # endif /* HAVE_LIBSSL */
435 con
->http
.tls
= NULL
;
437 #endif /* HAVE_SSL */
440 * Close the socket and clear the file from the input set for select()...
443 if (con
->http
.fd
>= 0)
445 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
448 FD_CLR(con
->http
.fd
, InputSet
);
449 FD_CLR(con
->http
.fd
, OutputSet
);
453 if (con
->pipe_pid
!= 0)
455 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet...",
457 FD_CLR(con
->file
, InputSet
);
463 * Close the open data file...
468 kill(con
->pipe_pid
, SIGKILL
);
469 waitpid(con
->pipe_pid
, &status
, WNOHANG
);
472 LogMessage(L_DEBUG2
, "CloseClient() %d Closing data file %d.",
473 con
->http
.fd
, con
->file
);
474 LogMessage(L_DEBUG2
, "CloseClient() %d Removing fd %d from InputSet.",
475 con
->http
.fd
, con
->file
);
477 FD_CLR(con
->file
, InputSet
);
484 ippDelete(con
->request
);
490 ippDelete(con
->response
);
491 con
->response
= NULL
;
496 cupsLangFree(con
->language
);
497 con
->language
= NULL
;
501 * Re-enable new client connections if we are going back under the
505 if (NumClients
== MaxClients
)
509 * Compact the list of clients as necessary...
514 if (con
< (Clients
+ NumClients
))
515 memcpy(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
520 * 'EncryptClient()' - Enable encryption for the client...
523 int /* O - 1 on success, 0 on error */
524 EncryptClient(client_t
*con
) /* I - Client to encrypt */
526 #if defined HAVE_LIBSSL
527 SSL_CTX
*context
; /* Context for encryption */
528 SSL
*conn
; /* Connection for encryption */
529 unsigned long error
; /* Error code */
533 * Create the SSL context and accept the connection...
536 context
= SSL_CTX_new(SSLv23_server_method());
538 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
539 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
541 conn
= SSL_new(context
);
543 SSL_set_fd(conn
, con
->http
.fd
);
544 if (SSL_accept(conn
) != 1)
546 while ((error
= ERR_get_error()) != 0)
547 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
549 SSL_CTX_free(context
);
554 con
->http
.tls
= conn
;
557 #elif defined(HAVE_GNUTLS)
558 http_tls_t
*conn
; /* TLS session object */
559 int error
; /* Error code */
560 gnutls_certificate_server_credentials
*credentials
;
561 /* TLS credentials */
564 * Create the SSL object and perform the SSL handshake...
567 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
572 credentials
= (gnutls_certificate_server_credentials
*)
573 malloc(sizeof(gnutls_certificate_server_credentials
));
574 if (credentials
== NULL
)
580 gnutls_certificate_allocate_credentials(credentials
);
581 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
582 ServerKey
, GNUTLS_X509_FMT_PEM
);
584 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
585 gnutls_set_default_priority(conn
->session
);
586 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
587 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
589 error
= gnutls_handshake(conn
->session
);
591 if (error
!= GNUTLS_E_SUCCESS
)
593 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
594 gnutls_deinit(conn
->session
);
595 gnutls_certificate_free_credentials(*credentials
);
601 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
604 conn
->credentials
= credentials
;
605 con
->http
.tls
= conn
;
608 #elif defined(HAVE_CDSASSL)
609 OSStatus error
; /* Error info */
610 SSLContextRef conn
; /* New connection */
611 SSLProtocol tryVersion
; /* Protocol version */
612 const char *hostName
; /* Local hostname */
613 int allowExpired
; /* Allow expired certificates? */
614 int allowAnyRoot
; /* Allow any root certificate? */
615 SSLProtocol
*negVersion
; /* Negotiated protocol version */
616 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
617 CFArrayRef
*peerCerts
; /* Certificates */
621 error
= SSLNewContext(true, &conn
);
626 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
629 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
632 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
636 hostName
= ServerName
; /* MRS: ??? */
637 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
640 /* have to do these options befor setting server certs */
641 if (!error
&& allowExpired
)
642 error
= SSLSetAllowsExpiredCerts(conn
, true);
644 if (!error
&& allowAnyRoot
)
645 error
= SSLSetAllowsAnyRoot(conn
, true);
647 if (!error
&& ServerCertificatesArray
!= NULL
)
648 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
651 * Perform SSL/TLS handshake
656 error
= SSLHandshake(conn
);
658 while (error
== errSSLWouldBlock
);
662 LogMessage(L_ERROR
, "EncryptClient: %d", error
);
664 con
->http
.error
= error
;
665 con
->http
.status
= HTTP_ERROR
;
668 SSLDisposeContext(conn
);
673 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
675 con
->http
.tls
= conn
;
680 #endif /* HAVE_GNUTLS */
685 * 'IsCGI()' - Is the resource a CGI script/program?
688 int /* O - 1 = CGI, 0 = file */
689 IsCGI(client_t
*con
, /* I - Client connection */
690 const char *filename
, /* I - Real filename */
691 struct stat
*filestats
, /* I - File information */
692 mime_type_t
*type
) /* I - MIME type */
694 const char *options
; /* Options on URL */
697 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
698 con
, filename
, filestats
, type
? type
->super
: "unknown",
699 type
? type
->type
: "unknown");
702 * Get the options, if any...
705 if ((options
= strchr(con
->uri
, '?')) != NULL
)
709 * Check for known types...
712 if (strcasecmp(type
->super
, "application"))
714 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
718 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
719 (filestats
->st_mode
& 0111))
722 * "application/x-httpd-cgi" is a CGI script.
725 SetString(&con
->command
, filename
);
727 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
730 SetStringf(&con
->options
, "%s %s", filename
, options
);
732 SetStringf(&con
->options
, "%s", filename
);
734 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
735 con
->command
, con
->options
);
740 else if (!strcasecmp(type
->type
, "x-httpd-java"))
743 * "application/x-httpd-java" is a Java servlet.
746 SetString(&con
->command
, CUPS_JAVA
);
749 SetStringf(&con
->options
, "java %s %s", filename
, options
);
751 SetStringf(&con
->options
, "java %s", filename
);
753 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
754 con
->command
, con
->options
);
758 #endif /* HAVE_JAVA */
760 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
763 * "application/x-httpd-perl" is a Perl page.
766 SetString(&con
->command
, CUPS_PERL
);
769 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
771 SetStringf(&con
->options
, "perl %s", filename
);
773 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
774 con
->command
, con
->options
);
778 #endif /* HAVE_PERL */
780 else if (!strcasecmp(type
->type
, "x-httpd-php"))
783 * "application/x-httpd-php" is a PHP page.
786 SetString(&con
->command
, CUPS_PHP
);
789 SetStringf(&con
->options
, "php %s %s", filename
, options
);
791 SetStringf(&con
->options
, "php %s", filename
);
793 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
794 con
->command
, con
->options
);
798 #endif /* HAVE_PHP */
800 else if (!strcasecmp(type
->type
, "x-httpd-python"))
803 * "application/x-httpd-python" is a Python page.
806 SetString(&con
->command
, CUPS_PYTHON
);
809 SetStringf(&con
->options
, "python %s %s", filename
, options
);
811 SetStringf(&con
->options
, "python %s", filename
);
813 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
814 con
->command
, con
->options
);
818 #endif /* HAVE_PYTHON */
820 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
827 * 'ReadClient()' - Read data from a client.
830 int /* O - 1 on success, 0 on error */
831 ReadClient(client_t
*con
) /* I - Client to read from */
833 char line
[32768], /* Line from client... */
834 operation
[64], /* Operation code from socket */
835 version
[64]; /* HTTP version number string */
836 int major
, minor
; /* HTTP version numbers */
837 http_status_t status
; /* Transfer status */
838 ipp_state_t ipp_state
; /* State of IPP transfer */
839 int bytes
; /* Number of bytes to POST */
840 char *filename
; /* Name of file for GET/HEAD */
841 char buf
[1024]; /* Buffer for real filename */
842 struct stat filestats
; /* File information */
843 mime_type_t
*type
; /* MIME type of file */
844 printer_t
*p
; /* Printer */
845 location_t
*best
; /* Best match for authentication */
846 static unsigned request_id
= 0;/* Request ID for temp files */
849 status
= HTTP_CONTINUE
;
851 LogMessage(L_DEBUG2
, "ReadClient() %d, used=%d", con
->http
.fd
,
860 switch (con
->http
.state
)
864 * See if we've received a request line...
867 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
874 * Ignore blank request lines...
881 * Clear other state variables...
884 httpClearFields(HTTP(con
));
886 con
->http
.activity
= time(NULL
);
887 con
->http
.version
= HTTP_1_0
;
888 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
889 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
890 con
->http
.data_remaining
= 0;
891 con
->operation
= HTTP_WAITING
;
895 con
->username
[0] = '\0';
896 con
->password
[0] = '\0';
899 ClearString(&con
->command
);
900 ClearString(&con
->options
);
902 if (con
->language
!= NULL
)
904 cupsLangFree(con
->language
);
905 con
->language
= NULL
;
909 * Grab the request line...
912 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
915 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
916 SendError(con
, HTTP_BAD_REQUEST
);
920 con
->http
.version
= HTTP_0_9
;
923 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
925 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
926 SendError(con
, HTTP_BAD_REQUEST
);
933 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
934 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
935 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
937 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
941 SendError(con
, HTTP_NOT_SUPPORTED
);
949 * Handle full URLs in the request line...
952 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
954 char method
[HTTP_MAX_URI
], /* Method/scheme */
955 userpass
[HTTP_MAX_URI
], /* Username:password */
956 hostname
[HTTP_MAX_URI
], /* Hostname */
957 resource
[HTTP_MAX_URI
]; /* Resource path */
958 int port
; /* Port number */
962 * Separate the URI into its components...
965 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
968 * Only allow URIs with the servername, localhost, or an IP
972 if (strcasecmp(hostname
, ServerName
) &&
973 strcasecmp(hostname
, "localhost") &&
974 !isdigit(hostname
[0]))
977 * Nope, we don't do proxies...
980 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
981 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
987 * Copy the resource portion back into the URI; both resource and
988 * con->uri are HTTP_MAX_URI bytes in size...
991 strcpy(con
->uri
, resource
);
995 * Process the request...
998 if (strcmp(operation
, "GET") == 0)
999 con
->http
.state
= HTTP_GET
;
1000 else if (strcmp(operation
, "PUT") == 0)
1001 con
->http
.state
= HTTP_PUT
;
1002 else if (strcmp(operation
, "POST") == 0)
1003 con
->http
.state
= HTTP_POST
;
1004 else if (strcmp(operation
, "DELETE") == 0)
1005 con
->http
.state
= HTTP_DELETE
;
1006 else if (strcmp(operation
, "TRACE") == 0)
1007 con
->http
.state
= HTTP_TRACE
;
1008 else if (strcmp(operation
, "OPTIONS") == 0)
1009 con
->http
.state
= HTTP_OPTIONS
;
1010 else if (strcmp(operation
, "HEAD") == 0)
1011 con
->http
.state
= HTTP_HEAD
;
1014 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1015 SendError(con
, HTTP_BAD_REQUEST
);
1016 ShutdownClient(con
);
1020 con
->start
= time(NULL
);
1021 con
->operation
= con
->http
.state
;
1023 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
1024 operation
, con
->uri
,
1025 con
->http
.version
/ 100, con
->http
.version
% 100);
1027 con
->http
.status
= HTTP_OK
;
1037 * Parse incoming parameters until the status changes...
1040 status
= httpUpdate(HTTP(con
));
1042 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1044 SendError(con
, HTTP_BAD_REQUEST
);
1045 ShutdownClient(con
);
1051 break; /* Anti-compiler-warning-code */
1055 * Handle new transfers...
1058 if (status
== HTTP_OK
)
1060 con
->language
= cupsLangGet(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1064 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1066 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1068 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1069 con
->http
.version
>= HTTP_1_1
)
1072 * HTTP/1.1 and higher require the "Host:" field...
1075 if (!SendError(con
, HTTP_BAD_REQUEST
))
1081 else if (con
->operation
== HTTP_OPTIONS
)
1084 * Do OPTIONS command...
1087 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1088 best
->type
!= AUTH_NONE
)
1090 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1097 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1098 con
->http
.tls
== NULL
)
1102 * Do encryption stuff...
1105 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1111 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1112 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1113 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1114 httpPrintf(HTTP(con
), "\r\n");
1118 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1123 #endif /* HAVE_SSL */
1126 if (con
->http
.expect
)
1128 /**** TODO: send expected header ****/
1131 if (!SendHeader(con
, HTTP_OK
, NULL
))
1137 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1138 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1139 httpPrintf(HTTP(con
), "\r\n");
1141 else if (strstr(con
->uri
, "..") != NULL
)
1144 * Protect against malicious users!
1147 if (!SendError(con
, HTTP_FORBIDDEN
))
1155 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1156 con
->http
.tls
== NULL
)
1160 * Do encryption stuff...
1163 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1169 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1170 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1171 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1172 httpPrintf(HTTP(con
), "\r\n");
1176 status
= IsAuthorized(con
);
1178 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1183 #endif /* HAVE_SSL */
1186 if (status
!= HTTP_OK
)
1188 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1190 SendError(con
, status
);
1191 ShutdownClient(con
);
1195 if (con
->http
.expect
)
1197 /**** TODO: send expected header ****/
1200 switch (con
->http
.state
)
1202 case HTTP_GET_SEND
:
1203 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1204 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1207 * Send PPD file - get the real printer name since printer
1208 * names are not case sensitive but filenames can be...
1211 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1213 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1214 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1217 if (!SendError(con
, HTTP_NOT_FOUND
))
1227 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1228 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1229 strncmp(con
->uri
, "/printers", 9) == 0 ||
1230 strncmp(con
->uri
, "/classes", 8) == 0 ||
1231 strncmp(con
->uri
, "/jobs", 5) == 0)
1234 * Send CGI output...
1237 if (strncmp(con
->uri
, "/admin", 6) == 0)
1239 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1240 SetString(&con
->options
, con
->uri
+ 6);
1242 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1244 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1245 SetString(&con
->options
, con
->uri
+ 9);
1247 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1249 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1250 SetString(&con
->options
, con
->uri
+ 8);
1254 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1255 SetString(&con
->options
, con
->uri
+ 5);
1258 if (con
->options
[0] == '/')
1259 strcpy(con
->options
, con
->options
+ 1);
1261 if (!SendCommand(con
, con
->command
, con
->options
))
1263 if (!SendError(con
, HTTP_NOT_FOUND
))
1270 LogRequest(con
, HTTP_OK
);
1272 if (con
->http
.version
<= HTTP_1_0
)
1273 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1275 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1276 (strchr(con
->uri
+ 12, '/') != NULL
||
1277 strlen(con
->uri
) == 12))
1280 * GET can only be done to configuration files under
1284 if (!SendError(con
, HTTP_FORBIDDEN
))
1298 if ((filename
= get_file(con
, &filestats
, buf
,
1299 sizeof(buf
))) == NULL
)
1301 if (!SendError(con
, HTTP_NOT_FOUND
))
1310 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1312 if (IsCGI(con
, filename
, &filestats
, type
))
1314 if (!SendCommand(con
, con
->command
, con
->options
))
1316 if (!SendError(con
, HTTP_NOT_FOUND
))
1323 LogRequest(con
, HTTP_OK
);
1325 if (con
->http
.version
<= HTTP_1_0
)
1326 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1330 if (!check_if_modified(con
, &filestats
))
1332 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1341 strcpy(line
, "text/plain");
1343 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1345 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1354 case HTTP_POST_RECV
:
1356 * See if the POST request includes a Content-Length field, and if
1357 * so check the length against any limits that are set...
1360 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1361 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1363 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1364 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1368 * Request too large...
1371 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1379 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1382 * Negative content lengths are invalid!
1385 if (!SendError(con
, HTTP_BAD_REQUEST
))
1395 * See what kind of POST request this is; for IPP requests the
1396 * content-type field will be "application/ipp"...
1399 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1400 con
->request
= ippNew();
1401 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1402 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1403 strncmp(con
->uri
, "/printers", 9) == 0 ||
1404 strncmp(con
->uri
, "/classes", 8) == 0 ||
1405 strncmp(con
->uri
, "/jobs", 5) == 0)
1411 if (strncmp(con
->uri
, "/admin", 6) == 0)
1413 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1414 SetString(&con
->options
, con
->uri
+ 6);
1416 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1418 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1419 SetString(&con
->options
, con
->uri
+ 9);
1421 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1423 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1424 SetString(&con
->options
, con
->uri
+ 8);
1428 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1429 SetString(&con
->options
, con
->uri
+ 5);
1432 if (con
->options
[0] == '/')
1433 strcpy(con
->options
, con
->options
+ 1);
1435 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
1436 con
->http
.fd
, con
->command
, con
->options
);
1438 if (con
->http
.version
<= HTTP_1_0
)
1439 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1447 if ((filename
= get_file(con
, &filestats
, buf
,
1448 sizeof(buf
))) == NULL
)
1450 if (!SendError(con
, HTTP_NOT_FOUND
))
1459 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1461 if (!IsCGI(con
, filename
, &filestats
, type
))
1464 * Only POST to CGI's...
1467 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1476 case HTTP_PUT_RECV
:
1478 * Validate the resource name...
1481 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1482 strchr(con
->uri
+ 12, '/') != NULL
||
1483 strlen(con
->uri
) == 12)
1486 * PUT can only be done to configuration files under
1490 if (!SendError(con
, HTTP_FORBIDDEN
))
1500 * See if the PUT request includes a Content-Length field, and if
1501 * so check the length against any limits that are set...
1504 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1505 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1507 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1508 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1512 * Request too large...
1515 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1525 * Open a temporary file to hold the request...
1528 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1529 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1530 fchmod(con
->file
, 0640);
1531 fchown(con
->file
, User
, Group
);
1533 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1534 con
->filename
, con
->file
);
1538 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1548 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1549 ShutdownClient(con
);
1553 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1554 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1557 * Send PPD file - get the real printer name since printer
1558 * names are not case sensitive but filenames can be...
1561 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1563 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1564 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1567 if (!SendError(con
, HTTP_NOT_FOUND
))
1577 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1578 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1579 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1580 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1581 strncmp(con
->uri
, "/jobs/", 6) == 0)
1587 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1593 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1599 LogRequest(con
, HTTP_OK
);
1601 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1602 (strchr(con
->uri
+ 12, '/') != NULL
||
1603 strlen(con
->uri
) == 12))
1606 * HEAD can only be done to configuration files under
1610 if (!SendError(con
, HTTP_FORBIDDEN
))
1618 else if ((filename
= get_file(con
, &filestats
, buf
,
1619 sizeof(buf
))) == NULL
)
1621 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1627 LogRequest(con
, HTTP_NOT_FOUND
);
1629 else if (!check_if_modified(con
, &filestats
))
1631 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1637 LogRequest(con
, HTTP_NOT_MODIFIED
);
1645 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1647 strcpy(line
, "text/plain");
1649 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1651 if (!SendHeader(con
, HTTP_OK
, line
))
1657 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1658 httpGetDateString(filestats
.st_mtime
)) < 0)
1664 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1665 (unsigned long)filestats
.st_size
) < 0)
1671 LogRequest(con
, HTTP_OK
);
1674 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1680 con
->http
.state
= HTTP_WAITING
;
1684 break; /* Anti-compiler-warning-code */
1690 * Handle any incoming data...
1693 switch (con
->http
.state
)
1695 case HTTP_PUT_RECV
:
1696 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1698 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1699 con
->http
.data_remaining
, con
->file
);
1701 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1708 con
->bytes
+= bytes
;
1710 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1711 con
->http
.fd
, bytes
, con
->file
);
1713 if (write(con
->file
, line
, bytes
) < bytes
)
1715 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1716 bytes
, con
->filename
, strerror(errno
));
1718 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1723 unlink(con
->filename
);
1724 ClearString(&con
->filename
);
1726 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1734 if (con
->http
.state
== HTTP_WAITING
)
1737 * End of file, see how big it is...
1740 fstat(con
->file
, &filestats
);
1742 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1743 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1748 if (filestats
.st_size
> MaxRequestSize
&&
1752 * Request is too big; remove it and send an error...
1755 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1756 con
->http
.fd
, con
->filename
);
1757 unlink(con
->filename
);
1758 ClearString(&con
->filename
);
1760 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1768 * Install the configuration file...
1771 status
= install_conf_file(con
);
1774 * Return the status to the client...
1777 if (!SendError(con
, status
))
1785 case HTTP_POST_RECV
:
1786 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1788 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1789 con
->http
.data_remaining
, con
->file
);
1791 if (con
->request
!= NULL
)
1794 * Grab any request data from the connection...
1797 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1799 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1802 if (!SendError(con
, HTTP_BAD_REQUEST
))
1808 ShutdownClient(con
);
1811 else if (ipp_state
!= IPP_DATA
)
1814 con
->bytes
+= ippLength(con
->request
);
1817 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
1820 * Create a file as needed for the request data...
1823 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1824 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1825 fchmod(con
->file
, 0640);
1826 fchown(con
->file
, User
, Group
);
1828 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1829 con
->filename
, con
->file
);
1833 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1841 if (con
->http
.state
!= HTTP_POST_SEND
)
1843 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1850 con
->bytes
+= bytes
;
1852 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1853 con
->http
.fd
, bytes
, con
->file
);
1855 if (write(con
->file
, line
, bytes
) < bytes
)
1857 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1858 bytes
, con
->filename
, strerror(errno
));
1860 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1865 unlink(con
->filename
);
1866 ClearString(&con
->filename
);
1868 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1875 else if (con
->http
.state
== HTTP_POST_RECV
)
1879 else if (con
->http
.state
!= HTTP_POST_SEND
)
1886 if (con
->http
.state
== HTTP_POST_SEND
)
1890 fstat(con
->file
, &filestats
);
1892 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1893 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1898 if (filestats
.st_size
> MaxRequestSize
&&
1902 * Request is too big; remove it and send an error...
1905 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1906 con
->http
.fd
, con
->filename
);
1907 unlink(con
->filename
);
1908 ClearString(&con
->filename
);
1913 * Delete any IPP request data...
1916 ippDelete(con
->request
);
1917 con
->request
= NULL
;
1920 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1929 if (!SendCommand(con
, con
->command
, con
->options
))
1931 if (!SendError(con
, HTTP_NOT_FOUND
))
1938 LogRequest(con
, HTTP_OK
);
1943 return (ProcessIPPRequest(con
));
1948 break; /* Anti-compiler-warning-code */
1951 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1962 * 'SendCommand()' - Send output from a command via HTTP.
1966 SendCommand(client_t
*con
,
1974 fd
= open(con
->filename
, O_RDONLY
);
1976 fd
= open("/dev/null", O_RDONLY
);
1978 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
1982 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
1984 LogMessage(L_DEBUG
, "SendCommand() %d file=%d", con
->http
.fd
, con
->file
);
1986 if (con
->pipe_pid
== 0)
1989 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1991 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
1992 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
1995 FD_SET(con
->file
, InputSet
);
1996 FD_SET(con
->http
.fd
, OutputSet
);
1998 if (!SendHeader(con
, HTTP_OK
, NULL
))
2001 if (con
->http
.version
== HTTP_1_1
)
2003 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2005 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2009 con
->got_fields
= 0;
2017 * 'SendError()' - Send an error message via HTTP.
2020 int /* O - 1 if successful, 0 otherwise */
2021 SendError(client_t
*con
, /* I - Connection */
2022 http_status_t code
) /* I - Error code */
2024 char message
[1024]; /* Message for user */
2028 * Put the request in the access_log file...
2031 if (con
->operation
> HTTP_WAITING
)
2032 LogRequest(con
, code
);
2034 LogMessage(L_DEBUG
, "SendError() %d code=%d", con
->http
.fd
, code
);
2037 * To work around bugs in some proxies, don't use Keep-Alive for some
2041 if (code
>= HTTP_BAD_REQUEST
)
2042 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2045 * Send an error message back to the client. If the error code is a
2046 * 400 or 500 series, make sure the message contains some text, too!
2049 if (!SendHeader(con
, code
, NULL
))
2053 if (code
== HTTP_UPGRADE_REQUIRED
)
2054 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2057 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2059 #endif /* HAVE_SSL */
2061 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2062 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2064 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2068 if (code
>= HTTP_BAD_REQUEST
)
2071 * Send a human-readable error message.
2074 snprintf(message
, sizeof(message
),
2075 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2076 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2077 code
, httpStatus(code
), httpStatus(code
),
2078 con
->language
? con
->language
->messages
[code
] :
2081 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
2083 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2084 (int)strlen(message
)) < 0)
2086 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2088 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2091 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2094 con
->http
.state
= HTTP_WAITING
;
2101 * 'SendFile()' - Send a file via HTTP.
2105 SendFile(client_t
*con
,
2109 struct stat
*filestats
)
2111 con
->file
= open(filename
, O_RDONLY
);
2113 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
2118 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2122 if (!SendHeader(con
, code
, type
))
2125 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2127 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2128 (unsigned long)filestats
->st_size
) < 0)
2130 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2133 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2135 FD_SET(con
->http
.fd
, OutputSet
);
2142 * 'SendHeader()' - Send an HTTP request.
2145 int /* O - 1 on success, 0 on failure */
2146 SendHeader(client_t
*con
, /* I - Client to send to */
2147 http_status_t code
, /* I - HTTP status code */
2148 char *type
) /* I - MIME type of document */
2150 location_t
*loc
; /* Authentication location */
2153 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2154 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2156 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2158 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
2160 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2162 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2164 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2167 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2168 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2171 if (code
== HTTP_UNAUTHORIZED
)
2174 * This already succeeded in IsAuthorized...
2177 loc
= FindBest(con
->uri
, con
->http
.state
);
2179 if (loc
->type
!= AUTH_DIGEST
)
2181 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2186 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
2187 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2191 if (con
->language
!= NULL
)
2193 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2194 con
->language
->language
) < 0)
2198 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
2199 cupsLangEncoding(con
->language
)) < 0)
2202 else if (type
!= NULL
)
2203 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2211 * 'ShutdownClient()' - Shutdown the receiving end of a connection.
2215 ShutdownClient(client_t
*con
) /* I - Client connection */
2218 * Shutdown the receiving end of the socket, since the client
2219 * still needs to read the error message...
2222 shutdown(con
->http
.fd
, 0);
2226 * Update the activity time so that we timeout after 30 seconds rather
2227 * then the current Timeout setting (300 by default). This prevents
2228 * some DoS situations...
2231 con
->http
.activity
= time(NULL
) - Timeout
+ 30;
2233 LogMessage(L_DEBUG2
, "ShutdownClient: Removing fd %d from InputSet...",
2236 FD_CLR(con
->http
.fd
, InputSet
);
2241 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2247 int bytes
; /* Number of bytes read */
2248 char *lineptr
, /* Pointer to end of line in buffer */
2249 *message
; /* Pointer to message text */
2250 int loglevel
; /* Log level for message */
2251 static int bufused
= 0; /* Number of bytes used in buffer */
2252 static char buffer
[1024]; /* Status buffer */
2255 if ((bytes
= read(CGIPipes
[0], buffer
+ bufused
,
2256 sizeof(buffer
) - bufused
- 1)) > 0)
2259 buffer
[bufused
] = '\0';
2260 lineptr
= strchr(buffer
, '\n');
2262 else if (bytes
< 0 && errno
== EINTR
)
2266 lineptr
= buffer
+ bufused
;
2270 if (bytes
== 0 && bufused
== 0)
2273 while (lineptr
!= NULL
)
2276 * Terminate each line and process it...
2282 * Figure out the logging level...
2285 if (strncmp(buffer
, "EMERG:", 6) == 0)
2288 message
= buffer
+ 6;
2290 else if (strncmp(buffer
, "ALERT:", 6) == 0)
2293 message
= buffer
+ 6;
2295 else if (strncmp(buffer
, "CRIT:", 5) == 0)
2298 message
= buffer
+ 5;
2300 else if (strncmp(buffer
, "ERROR:", 6) == 0)
2303 message
= buffer
+ 6;
2305 else if (strncmp(buffer
, "WARNING:", 8) == 0)
2308 message
= buffer
+ 8;
2310 else if (strncmp(buffer
, "NOTICE:", 6) == 0)
2312 loglevel
= L_NOTICE
;
2313 message
= buffer
+ 6;
2315 else if (strncmp(buffer
, "INFO:", 5) == 0)
2318 message
= buffer
+ 5;
2320 else if (strncmp(buffer
, "DEBUG:", 6) == 0)
2323 message
= buffer
+ 6;
2325 else if (strncmp(buffer
, "DEBUG2:", 7) == 0)
2327 loglevel
= L_DEBUG2
;
2328 message
= buffer
+ 7;
2330 else if (strncmp(buffer
, "PAGE:", 5) == 0)
2333 message
= buffer
+ 5;
2342 * Skip leading whitespace in the message...
2345 while (isspace(*message
))
2348 LogMessage(loglevel
, "[CGI] %s", message
);
2351 * Copy over the buffer data we've used up...
2354 strcpy(buffer
, lineptr
);
2355 bufused
-= lineptr
- buffer
;
2360 lineptr
= strchr(buffer
, '\n');
2366 * Fatal error on pipe - should never happen!
2369 LogMessage(L_ERROR
, "UpdateCGI: error reading from CGI error pipe - %s",
2376 * 'WriteClient()' - Write data to a client as needed.
2379 int /* O - 1 if success, 0 if fail */
2380 WriteClient(client_t
*con
) /* I - Client connection */
2382 int bytes
; /* Number of bytes written */
2383 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
2384 char *bufptr
; /* Pointer into buffer */
2385 ipp_state_t ipp_state
; /* IPP state value */
2388 if (con
->http
.state
!= HTTP_GET_SEND
&&
2389 con
->http
.state
!= HTTP_POST_SEND
)
2392 if (con
->response
!= NULL
)
2394 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2395 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2397 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
2399 if (con
->pipe_pid
&& !con
->got_fields
)
2402 * Inspect the data for Content-Type and other fields.
2407 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2408 if (*bufptr
== '\n')
2411 * Send line to client...
2414 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2418 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2419 LogMessage(L_DEBUG2
, "WriteClient() %d %s", con
->http
.fd
, buf
);
2425 bytes
-= (bufptr
- buf
);
2426 memcpy(buf
, bufptr
, bytes
+ 1);
2430 * See if the line was empty...
2433 if (con
->field_col
== 0)
2434 con
->got_fields
= 1;
2438 else if (*bufptr
!= '\r')
2441 if (bytes
> 0 && !con
->got_fields
)
2444 * Remaining text needs to go out...
2447 httpPrintf(HTTP(con
), "%s", buf
);
2449 con
->http
.activity
= time(NULL
);
2452 else if (bytes
== 0)
2454 con
->http
.activity
= time(NULL
);
2459 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2465 con
->bytes
+= bytes
;
2470 LogRequest(con
, HTTP_OK
);
2472 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2474 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2481 con
->http
.state
= HTTP_WAITING
;
2483 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from OutputSet...",
2486 FD_CLR(con
->http
.fd
, OutputSet
);
2490 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from InputSet...",
2492 FD_CLR(con
->file
, InputSet
);
2495 kill(con
->pipe_pid
, SIGTERM
);
2497 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
2498 con
->http
.fd
, con
->file
);
2507 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
2508 con
->http
.fd
, con
->filename
);
2509 unlink(con
->filename
);
2510 ClearString(&con
->filename
);
2513 if (con
->request
!= NULL
)
2515 ippDelete(con
->request
);
2516 con
->request
= NULL
;
2519 if (con
->response
!= NULL
)
2521 ippDelete(con
->response
);
2522 con
->response
= NULL
;
2525 ClearString(&con
->command
);
2526 ClearString(&con
->options
);
2528 if (!con
->http
.keep_alive
)
2536 LogMessage(L_DEBUG2
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
2538 con
->http
.activity
= time(NULL
);
2545 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2548 static int /* O - 1 if modified since */
2549 check_if_modified(client_t
*con
, /* I - Client connection */
2550 struct stat
*filestats
) /* I - File information */
2552 char *ptr
; /* Pointer into field */
2553 time_t date
; /* Time/date value */
2554 int size
; /* Size/length value */
2559 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2564 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
2567 while (*ptr
!= '\0')
2569 while (isspace(*ptr
) || *ptr
== ';')
2572 if (strncasecmp(ptr
, "length=", 7) == 0)
2577 while (isdigit(*ptr
))
2580 else if (isalpha(*ptr
))
2582 date
= httpGetDateTime(ptr
);
2583 while (*ptr
!= '\0' && *ptr
!= ';')
2588 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
2589 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2590 (int)filestats
->st_mtime
);
2592 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2593 (date
< filestats
->st_mtime
&& date
!= 0) ||
2594 (size
== 0 && date
== 0));
2599 * 'decode_auth()' - Decode an authorization string.
2603 decode_auth(client_t
*con
) /* I - Client to decode to */
2605 char *s
, /* Authorization string */
2606 value
[1024]; /* Value string */
2607 const char *username
; /* Certificate username */
2611 * Decode the string...
2614 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2616 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2619 if (strncmp(s
, "Basic", 5) == 0)
2625 httpDecode64(value
, s
);
2628 * Pull the username and password out...
2631 if ((s
= strchr(value
, ':')) == NULL
)
2633 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2634 con
->http
.fd
, value
);
2640 strlcpy(con
->username
, value
, sizeof(con
->username
));
2641 strlcpy(con
->password
, s
, sizeof(con
->password
));
2643 else if (strncmp(s
, "Local", 5) == 0)
2649 if ((username
= FindCert(s
)) != NULL
)
2650 strlcpy(con
->username
, username
, sizeof(con
->username
));
2652 else if (strncmp(s
, "Digest", 5) == 0)
2655 * Get the username and password from the Digest attributes...
2658 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2660 strlcpy(con
->username
, value
, sizeof(con
->username
));
2662 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2664 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2667 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2668 con
->http
.fd
, con
->username
);
2673 * 'get_file()' - Get a filename and state info.
2676 static char * /* O - Real filename */
2677 get_file(client_t
*con
, /* I - Client connection */
2678 struct stat
*filestats
,/* O - File information */
2679 char *filename
, /* IO - Filename buffer */
2680 int len
) /* I - Buffer length */
2682 int status
; /* Status of filesystem calls */
2683 char *params
; /* Pointer to parameters in URI */
2687 * Need to add DocumentRoot global...
2690 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2691 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2692 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2693 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2694 else if (con
->language
!= NULL
)
2695 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2698 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2700 if ((params
= strchr(filename
, '?')) != NULL
)
2704 * Grab the status for this language; if there isn't a language-specific file
2705 * then fallback to the default one...
2708 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2711 * Drop the language prefix and try the current directory...
2714 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2715 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2717 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2719 status
= stat(filename
, filestats
);
2724 * If we're found a directory, get the index.html file instead...
2727 if (!status
&& S_ISDIR(filestats
->st_mode
))
2729 if (filename
[strlen(filename
) - 1] == '/')
2730 strlcat(filename
, "index.html", len
);
2732 strlcat(filename
, "/index.html", len
);
2734 status
= stat(filename
, filestats
);
2737 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2738 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2748 * 'install_conf_file()' - Install a configuration file.
2751 static http_status_t
/* O - Status */
2752 install_conf_file(client_t
*con
) /* I - Connection */
2754 cups_file_t
*in
, /* Input file */
2755 *out
; /* Output file */
2756 char buffer
[1024]; /* Copy buffer */
2757 int bytes
; /* Number of bytes */
2758 char conffile
[1024], /* Configuration filename */
2759 newfile
[1024], /* New config filename */
2760 oldfile
[1024]; /* Old config filename */
2761 struct stat confinfo
; /* Config file info */
2765 * First construct the filenames...
2768 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2769 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2770 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2772 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2775 * Get the owner, group, and permissions of the configuration file.
2776 * If it doesn't exist, assign it to the User and Group in the
2777 * cupsd.conf file with mode 0640 permissions.
2780 if (stat(conffile
, &confinfo
))
2782 confinfo
.st_uid
= User
;
2783 confinfo
.st_gid
= Group
;
2784 confinfo
.st_mode
= ConfigFilePerm
;
2788 * Open the request file and new config file...
2791 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2793 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2794 con
->filename
, strerror(errno
));
2795 return (HTTP_SERVER_ERROR
);
2798 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2801 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2802 newfile
, strerror(errno
));
2803 return (HTTP_SERVER_ERROR
);
2806 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2807 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2810 * Copy from the request to the new config file...
2813 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2814 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2816 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2817 newfile
, strerror(errno
));
2823 return (HTTP_SERVER_ERROR
);
2827 * Close the files...
2831 if (cupsFileClose(out
))
2833 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2834 newfile
, strerror(errno
));
2838 return (HTTP_SERVER_ERROR
);
2842 * Remove the request file...
2845 unlink(con
->filename
);
2846 ClearString(&con
->filename
);
2849 * Unlink the old backup, rename the current config file to the backup
2850 * filename, and rename the new config file to the config file name...
2853 if (unlink(oldfile
))
2854 if (errno
!= ENOENT
)
2856 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2857 oldfile
, strerror(errno
));
2861 return (HTTP_SERVER_ERROR
);
2864 if (rename(conffile
, oldfile
))
2865 if (errno
!= ENOENT
)
2867 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2868 conffile
, strerror(errno
));
2872 return (HTTP_SERVER_ERROR
);
2875 if (rename(newfile
, conffile
))
2877 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2878 newfile
, strerror(errno
));
2880 rename(oldfile
, conffile
);
2883 return (HTTP_SERVER_ERROR
);
2887 * If the cupsd.conf file was updated, set the NeedReload flag...
2890 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2891 NeedReload
= RELOAD_CUPSD
;
2893 NeedReload
= RELOAD_ALL
;
2896 * Return that the file was created successfully...
2899 return (HTTP_CREATED
);
2904 * 'pipe_command()' - Pipe the output of a command to the remote client.
2907 static int /* O - Process ID */
2908 pipe_command(client_t
*con
, /* I - Client connection */
2909 int infile
, /* I - Standard input for command */
2910 int *outfile
, /* O - Standard output for command */
2911 char *command
, /* I - Command to run */
2912 char *options
) /* I - Options for command */
2914 int i
; /* Looping var */
2915 int pid
; /* Process ID */
2916 char *commptr
; /* Command string pointer */
2917 char *uriptr
; /* URI string pointer */
2918 int fd
; /* Looping var */
2919 int fds
[2]; /* Pipe FDs */
2920 int argc
; /* Number of arguments */
2921 int envc
; /* Number of environment variables */
2922 char argbuf
[10240], /* Argument buffer */
2923 *argv
[100], /* Argument strings */
2924 *envp
[100]; /* Environment variables */
2925 char content_length
[1024], /* CONTENT_LENGTH environment variable */
2926 content_type
[1024], /* CONTENT_TYPE environment variable */
2927 cups_datadir
[1024], /* CUPS_DATADIR environment variable */
2928 cups_serverroot
[1024], /* CUPS_SERVERROOT environment variable */
2929 http_cookie
[1024], /* HTTP_COOKIE environment variable */
2930 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
2931 ipp_port
[1024], /* IPP_PORT environment variable */
2932 lang
[1024], /* LANG environment variable */
2933 ld_library_path
[1024], /* LD_LIBRARY_PATH environment variable */
2934 ld_preload
[1024], /* LD_PRELOAD environment variable */
2935 dyld_library_path
[1024],/* DYLD_LIBRARY_PATH environment variable */
2936 shlib_path
[1024], /* SHLIB_PATH environment variable */
2937 nlspath
[1024], /* NLSPATH environment variable */
2938 query_string
[10240], /* QUERY_STRING env variable */
2939 remote_addr
[1024], /* REMOTE_ADDR environment variable */
2940 remote_host
[1024], /* REMOTE_HOST environment variable */
2941 remote_user
[1024], /* REMOTE_USER environment variable */
2942 script_name
[1024], /* SCRIPT_NAME environment variable */
2943 server_name
[1024], /* SERVER_NAME environment variable */
2944 server_port
[1024], /* SERVER_PORT environment variable */
2945 tmpdir
[1024]; /* TMPDIR 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 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");
3009 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
3011 sprintf(ipp_port
, "IPP_PORT=%d", ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3012 sprintf(server_port
, "SERVER_PORT=%d",
3013 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3016 #endif /* AF_INET6 */
3018 sprintf(ipp_port
, "IPP_PORT=%d", ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3019 sprintf(server_port
, "SERVER_PORT=%d",
3020 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3023 if (strcmp(con
->http
.hostname
, "localhost") == 0)
3024 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
3026 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
3027 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
3028 strcpy(remote_addr
, "REMOTE_ADDR=");
3029 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3030 sizeof(remote_addr
) - 12);
3031 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3032 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
3033 snprintf(cups_datadir
, sizeof(cups_datadir
), "CUPS_DATADIR=%s", DataDir
);
3034 snprintf(cups_serverroot
, sizeof(cups_serverroot
), "CUPS_SERVERROOT=%s", ServerRoot
);
3038 envp
[envc
++] = "PATH=/bin:/usr/bin";
3039 envp
[envc
++] = "SERVER_SOFTWARE=CUPS/1.1";
3040 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3041 if (con
->http
.version
== HTTP_1_1
)
3042 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3043 else if (con
->http
.version
== HTTP_1_0
)
3044 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3046 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3047 envp
[envc
++] = "REDIRECT_STATUS=1";
3048 envp
[envc
++] = ipp_port
;
3049 envp
[envc
++] = server_name
;
3050 envp
[envc
++] = server_port
;
3051 envp
[envc
++] = remote_addr
;
3052 envp
[envc
++] = remote_host
;
3053 envp
[envc
++] = remote_user
;
3054 envp
[envc
++] = lang
;
3056 envp
[envc
++] = tmpdir
;
3057 envp
[envc
++] = cups_datadir
;
3058 envp
[envc
++] = cups_serverroot
;
3060 if (getenv("LD_LIBRARY_PATH") != NULL
)
3062 snprintf(ld_library_path
, sizeof(ld_library_path
), "LD_LIBRARY_PATH=%s",
3063 getenv("LD_LIBRARY_PATH"));
3064 envp
[envc
++] = ld_library_path
;
3067 if (getenv("LD_PRELOAD") != NULL
)
3069 snprintf(ld_preload
, sizeof(ld_preload
), "LD_PRELOAD=%s",
3070 getenv("LD_PRELOAD"));
3071 envp
[envc
++] = ld_preload
;
3074 if (getenv("DYLD_LIBRARY_PATH") != NULL
)
3076 snprintf(dyld_library_path
, sizeof(dyld_library_path
), "DYLD_LIBRARY_PATH=%s",
3077 getenv("DYLD_LIBRARY_PATH"));
3078 envp
[envc
++] = dyld_library_path
;
3081 if (getenv("SHLIB_PATH") != NULL
)
3083 snprintf(shlib_path
, sizeof(shlib_path
), "SHLIB_PATH=%s",
3084 getenv("SHLIB_PATH"));
3085 envp
[envc
++] = shlib_path
;
3088 if (getenv("NLSPATH") != NULL
)
3090 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
3091 envp
[envc
++] = nlspath
;
3094 if (con
->http
.cookie
)
3096 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3098 envp
[envc
++] = http_cookie
;
3101 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3103 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3104 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3105 envp
[envc
++] = http_user_agent
;
3108 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3109 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3111 envp
[envc
++] = script_name
;
3113 if (con
->operation
== HTTP_GET
)
3115 for (i
= 0; i
< argc
; i
++)
3116 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3117 envp
[envc
++] = "REQUEST_METHOD=GET";
3122 * Add GET form variables after ?...
3127 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
3128 envp
[envc
++] = query_string
;
3133 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3134 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3135 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3137 envp
[envc
++] = "REQUEST_METHOD=POST";
3138 envp
[envc
++] = content_length
;
3139 envp
[envc
++] = content_type
;
3143 * Tell the CGI if we are using encryption...
3146 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3148 envp
[envc
++] = "HTTPS=ON";
3149 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
3154 if (LogLevel
== L_DEBUG2
)
3156 for (i
= 0; i
< argc
; i
++)
3157 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3158 for (i
= 0; i
< envc
; i
++)
3159 LogMessage(L_DEBUG2
, "envp[%d] = \"%s\"", i
, envp
[i
]);
3163 * Create a pipe for the output...
3168 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3169 argv
[0], strerror(errno
));
3174 * Block signals before forking...
3180 * Then execute the command...
3183 if ((pid
= fork()) == 0)
3186 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
3192 * Running as root, so change to a non-priviledged user...
3198 if (setgroups(0, NULL
))
3206 * Reset group membership to just the main one we belong to.
3212 * Update stdin/stdout/stderr...
3218 if (dup(infile
) < 0)
3223 if (dup(fds
[1]) < 0)
3230 * Close extra file descriptors...
3233 for (fd
= 3; fd
< MaxFDs
; fd
++)
3237 * Change umask to restrict permissions on created files...
3243 * Unblock signals before doing the exec...
3247 sigset(SIGTERM
, SIG_DFL
);
3248 sigset(SIGCHLD
, SIG_DFL
);
3249 #elif defined(HAVE_SIGACTION)
3250 memset(&action
, 0, sizeof(action
));
3252 sigemptyset(&action
.sa_mask
);
3253 action
.sa_handler
= SIG_DFL
;
3255 sigaction(SIGTERM
, &action
, NULL
);
3256 sigaction(SIGCHLD
, &action
, NULL
);
3258 signal(SIGTERM
, SIG_DFL
);
3259 signal(SIGCHLD
, SIG_DFL
);
3260 #endif /* HAVE_SIGSET */
3265 * Execute the pipe program; if an error occurs, exit with status 1...
3268 execve(command
, argv
, envp
);
3275 * Error - can't fork!
3278 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3288 * Fork successful - return the PID...
3291 AddCert(pid
, con
->username
);
3293 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3305 #if defined(HAVE_CDSASSL)
3307 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3310 static OSStatus
/* O - -1 on error, 0 on success */
3311 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3312 void *data
, /* I - Data buffer */
3313 size_t *dataLength
) /* IO - Number of bytes */
3315 ssize_t bytes
; /* Number of bytes read */
3318 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3321 *dataLength
= bytes
;
3330 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3333 static OSStatus
/* O - -1 on error, 0 on success */
3334 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3335 const void *data
, /* I - Data buffer */
3336 size_t *dataLength
) /* IO - Number of bytes */
3341 bytes
= write((int)connection
, data
, *dataLength
);
3344 *dataLength
= bytes
;
3350 #endif /* HAVE_CDSASSL */
3354 * End of "$Id: client.c,v 1.91.2.61 2003/07/19 21:57:46 mike Exp $".