2 * "$Id: client.c,v 1.91.2.75 2004/02/05 20:54:44 mike Exp $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2003 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * AcceptClient() - Accept a new client.
27 * CloseAllClients() - Close all remote clients immediately.
28 * CloseClient() - Close a remote client.
29 * EncryptClient() - Enable encryption for the client...
30 * IsCGI() - Is the resource a CGI script/program?
31 * ReadClient() - Read data from a client.
32 * SendCommand() - Send output from a command via HTTP.
33 * SendError() - Send an error message via HTTP.
34 * SendFile() - Send a file via HTTP.
35 * SendHeader() - Send an HTTP request.
36 * UpdateCGI() - Read status messages from CGI scripts and programs.
37 * WriteClient() - Write data to a client as needed.
38 * check_if_modified() - Decode an "If-Modified-Since" line.
39 * decode_auth() - Decode an authorization string.
40 * get_file() - Get a filename and state info.
41 * install_conf_file() - Install a configuration file.
42 * pipe_command() - Pipe the output of a command to the remote client.
43 * CDSAReadFunc() - Read function for CDSA decryption code.
44 * CDSAWriteFunc() - Write function for CDSA encryption code.
48 * Include necessary headers...
51 #include <cups/http-private.h>
60 static int check_if_modified(client_t
*con
,
61 struct stat
*filestats
);
62 static void decode_auth(client_t
*con
);
63 static char *get_file(client_t
*con
, struct stat
*filestats
,
64 char *filename
, int len
);
65 static http_status_t
install_conf_file(client_t
*con
);
66 static int pipe_command(client_t
*con
, int infile
, int *outfile
,
67 char *command
, char *options
);
70 static OSStatus
CDSAReadFunc(SSLConnectionRef connection
, void *data
,
72 static OSStatus
CDSAWriteFunc(SSLConnectionRef connection
,
73 const void *data
, size_t *dataLength
);
74 #endif /* HAVE_CDSASSL */
78 * 'AcceptClient()' - Accept a new client.
82 AcceptClient(listener_t
*lis
) /* I - Listener socket */
84 int i
; /* Looping var */
85 int count
; /* Count of connections on a host */
86 int val
; /* Parameter value */
87 client_t
*con
; /* New client pointer */
88 const struct hostent
*host
; /* Host entry for address */
89 char *hostname
;/* Hostname for address */
90 http_addr_t temp
; /* Temporary address variable */
91 static time_t last_dos
= 0;
92 /* Time of last DoS attack */
95 LogMessage(L_DEBUG2
, "AcceptClient(%p) %d NumClients = %d",
96 lis
, lis
->fd
, NumClients
);
99 * Make sure we don't have a full set of clients already...
102 if (NumClients
== MaxClients
)
106 * Get a pointer to the next available client...
109 con
= Clients
+ NumClients
;
111 memset(con
, 0, sizeof(client_t
));
112 con
->http
.activity
= time(NULL
);
115 * Accept the client and get the remote address...
118 val
= sizeof(struct sockaddr_in
);
120 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
123 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
129 if (lis
->address
.addr
.sa_family
== AF_INET6
)
130 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
132 #endif /* AF_INET6 */
133 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
136 * Check the number of clients on the same address...
139 for (i
= 0, count
= 0; i
< NumClients
; i
++)
140 if (memcmp(&(Clients
[i
].http
.hostaddr
), &(con
->http
.hostaddr
),
141 sizeof(con
->http
.hostaddr
)) == 0)
144 if (count
>= MaxClientsPerHost
)
148 if (count
>= MaxClientsPerHost
)
150 if ((time(NULL
) - last_dos
) >= 60)
152 last_dos
= time(NULL
);
153 LogMessage(L_WARN
, "Possible DoS attack - more than %d clients connecting from %s!",
154 MaxClientsPerHost
, Clients
[i
].http
.hostname
);
158 closesocket(con
->http
.fd
);
167 * Get the hostname or format the IP address as needed...
171 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
172 sizeof(con
->http
.hostname
));
176 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
177 sizeof(con
->http
.hostname
));
180 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
183 * Map accesses from the loopback interface to "localhost"...
186 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
188 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
191 * Map accesses from the same host to the server name.
194 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
197 if (hostname
== NULL
&& HostNameLookups
== 2)
200 * Can't have an unresolved IP address with double-lookups enabled...
203 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
207 closesocket(con
->http
.fd
);
212 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
217 if (HostNameLookups
== 2)
220 * Do double lookups as needed...
223 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
226 * See if the hostname maps to the same IP address...
229 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
232 * Not the right type of address...
240 * Compare all of the addresses against this one...
243 for (i
= 0; host
->h_addr_list
[i
]; i
++)
245 httpAddrLoad(host
, 0, i
, &temp
);
247 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
251 if (!host
->h_addr_list
[i
])
259 * Can't have a hostname that doesn't resolve to the same IP address
260 * with double-lookups enabled...
263 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
267 closesocket(con
->http
.fd
);
272 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
279 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
280 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
281 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
283 #endif /* AF_INET6 */
284 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
285 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
288 * Using TCP_NODELAY improves responsiveness, especially on systems
289 * with a slow loopback interface... Since we write large buffers
290 * when sending print files and requests, there shouldn't be any
291 * performance penalty for this...
295 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
298 * Close this file on all execs...
301 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
304 * Add the socket to the select() input mask.
307 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
309 FD_SET(con
->http
.fd
, InputSet
);
314 * Temporarily suspend accept()'s until we lose a client...
317 if (NumClients
== MaxClients
)
322 * See if we are connecting on a secure port...
325 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
328 * https connection; go secure...
331 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
335 #endif /* HAVE_SSL */
340 * 'CloseAllClients()' - Close all remote clients immediately.
344 CloseAllClients(void)
346 while (NumClients
> 0)
347 CloseClient(Clients
);
352 * 'CloseClient()' - Close a remote client.
356 CloseClient(client_t
*con
) /* I - Client to close */
358 int partial
; /* Do partial close for SSL? */
359 #if defined(HAVE_LIBSSL)
360 SSL_CTX
*context
; /* Context for encryption */
361 SSL
*conn
; /* Connection for encryption */
362 unsigned long error
; /* Error code */
363 #elif defined(HAVE_GNUTLS)
364 http_tls_t
*conn
; /* TLS connection information */
365 int error
; /* Error code */
366 gnutls_certificate_server_credentials
*credentials
;
367 /* TLS credentials */
368 #endif /* HAVE_GNUTLS */
371 LogMessage(L_DEBUG
, "CloseClient() %d", con
->http
.fd
);
377 * Shutdown encryption as needed...
385 conn
= (SSL
*)(con
->http
.tls
);
386 context
= SSL_get_SSL_CTX(conn
);
388 switch (SSL_shutdown(conn
))
391 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
394 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
396 while ((error
= ERR_get_error()) != 0)
397 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
401 SSL_CTX_free(context
);
404 # elif defined(HAVE_GNUTLS)
405 conn
= (http_tls_t
*)(con
->http
.tls
);
406 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
408 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
411 case GNUTLS_E_SUCCESS
:
412 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
415 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
419 gnutls_deinit(conn
->session
);
420 gnutls_certificate_free_credentials(*credentials
);
424 # elif defined(HAVE_CDSASSL)
425 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
426 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
427 # endif /* HAVE_LIBSSL */
429 con
->http
.tls
= NULL
;
431 #endif /* HAVE_SSL */
434 * Close the socket and clear the file from the input set for select()...
437 if (con
->http
.fd
> 0)
442 * Only do a partial close so that the encrypted client gets everything.
445 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from OutputSet...",
447 shutdown(con
->http
.fd
, 0);
448 FD_CLR(con
->http
.fd
, OutputSet
);
453 * Shut the socket down fully...
456 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
459 FD_CLR(con
->http
.fd
, InputSet
);
460 FD_CLR(con
->http
.fd
, OutputSet
);
465 if (con
->pipe_pid
!= 0)
468 * Stop any CGI process...
471 LogMessage(L_DEBUG2
, "CloseClient: %d Killing process ID %d...",
472 con
->http
.fd
, con
->pipe_pid
);
473 kill(con
->pipe_pid
, SIGKILL
);
475 LogMessage(L_DEBUG2
, "CloseClient: %d Removing fd %d from InputSet...",
476 con
->http
.fd
, con
->file
);
477 FD_CLR(con
->file
, InputSet
);
479 LogMessage(L_DEBUG2
, "CloseClient: %d Closing data file %d.",
480 con
->http
.fd
, con
->file
);
488 * Close the open data file...
492 LogMessage(L_DEBUG2
, "CloseClient: %d Removing fd %d from InputSet.",
493 con
->http
.fd
, con
->file
);
495 FD_CLR(con
->file
, InputSet
);
497 LogMessage(L_DEBUG2
, "CloseClient: %d Closing data file %d.",
498 con
->http
.fd
, con
->file
);
510 if (con
->http
.input_set
)
511 free(con
->http
.input_set
);
513 httpClearCookie(HTTP(con
));
515 ClearString(&con
->filename
);
516 ClearString(&con
->command
);
517 ClearString(&con
->options
);
521 ippDelete(con
->request
);
527 ippDelete(con
->response
);
528 con
->response
= NULL
;
533 cupsLangFree(con
->language
);
534 con
->language
= NULL
;
538 * Re-enable new client connections if we are going back under the
542 if (NumClients
== MaxClients
)
546 * Compact the list of clients as necessary...
551 if (con
< (Clients
+ NumClients
))
552 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
558 * 'EncryptClient()' - Enable encryption for the client...
561 int /* O - 1 on success, 0 on error */
562 EncryptClient(client_t
*con
) /* I - Client to encrypt */
564 #if defined HAVE_LIBSSL
565 SSL_CTX
*context
; /* Context for encryption */
566 SSL
*conn
; /* Connection for encryption */
567 unsigned long error
; /* Error code */
571 * Create the SSL context and accept the connection...
574 context
= SSL_CTX_new(SSLv23_server_method());
576 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
577 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
579 conn
= SSL_new(context
);
581 SSL_set_fd(conn
, con
->http
.fd
);
582 if (SSL_accept(conn
) != 1)
584 while ((error
= ERR_get_error()) != 0)
585 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
587 SSL_CTX_free(context
);
592 con
->http
.tls
= conn
;
595 #elif defined(HAVE_GNUTLS)
596 http_tls_t
*conn
; /* TLS session object */
597 int error
; /* Error code */
598 gnutls_certificate_server_credentials
*credentials
;
599 /* TLS credentials */
602 * Create the SSL object and perform the SSL handshake...
605 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
610 credentials
= (gnutls_certificate_server_credentials
*)
611 malloc(sizeof(gnutls_certificate_server_credentials
));
612 if (credentials
== NULL
)
618 gnutls_certificate_allocate_credentials(credentials
);
619 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
620 ServerKey
, GNUTLS_X509_FMT_PEM
);
622 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
623 gnutls_set_default_priority(conn
->session
);
624 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
625 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
627 error
= gnutls_handshake(conn
->session
);
629 if (error
!= GNUTLS_E_SUCCESS
)
631 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
632 gnutls_deinit(conn
->session
);
633 gnutls_certificate_free_credentials(*credentials
);
639 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
642 conn
->credentials
= credentials
;
643 con
->http
.tls
= conn
;
646 #elif defined(HAVE_CDSASSL)
647 OSStatus error
; /* Error info */
648 SSLContextRef conn
; /* New connection */
649 SSLProtocol tryVersion
; /* Protocol version */
650 const char *hostName
; /* Local hostname */
651 int allowExpired
; /* Allow expired certificates? */
652 int allowAnyRoot
; /* Allow any root certificate? */
653 SSLProtocol
*negVersion
; /* Negotiated protocol version */
654 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
655 CFArrayRef
*peerCerts
; /* Certificates */
659 error
= SSLNewContext(true, &conn
);
664 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
667 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
670 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
674 hostName
= ServerName
; /* MRS: ??? */
675 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
678 /* have to do these options befor setting server certs */
679 if (!error
&& allowExpired
)
680 error
= SSLSetAllowsExpiredCerts(conn
, true);
682 if (!error
&& allowAnyRoot
)
683 error
= SSLSetAllowsAnyRoot(conn
, true);
685 if (!error
&& ServerCertificatesArray
!= NULL
)
686 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
689 * Perform SSL/TLS handshake
694 error
= SSLHandshake(conn
);
696 while (error
== errSSLWouldBlock
);
700 LogMessage(L_ERROR
, "EncryptClient: %d", error
);
702 con
->http
.error
= error
;
703 con
->http
.status
= HTTP_ERROR
;
706 SSLDisposeContext(conn
);
711 LogMessage(L_DEBUG
, "EncryptClient() %d Connection now encrypted.",
713 con
->http
.tls
= conn
;
718 #endif /* HAVE_GNUTLS */
723 * 'IsCGI()' - Is the resource a CGI script/program?
726 int /* O - 1 = CGI, 0 = file */
727 IsCGI(client_t
*con
, /* I - Client connection */
728 const char *filename
, /* I - Real filename */
729 struct stat
*filestats
, /* I - File information */
730 mime_type_t
*type
) /* I - MIME type */
732 const char *options
; /* Options on URL */
735 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
736 con
, filename
, filestats
, type
? type
->super
: "unknown",
737 type
? type
->type
: "unknown");
740 * Get the options, if any...
743 if ((options
= strchr(con
->uri
, '?')) != NULL
)
747 * Check for known types...
750 if (strcasecmp(type
->super
, "application"))
752 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
756 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
757 (filestats
->st_mode
& 0111))
760 * "application/x-httpd-cgi" is a CGI script.
763 SetString(&con
->command
, filename
);
765 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
768 SetStringf(&con
->options
, "%s %s", filename
, options
);
770 SetStringf(&con
->options
, "%s", filename
);
772 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
773 con
->command
, con
->options
);
778 else if (!strcasecmp(type
->type
, "x-httpd-java"))
781 * "application/x-httpd-java" is a Java servlet.
784 SetString(&con
->command
, CUPS_JAVA
);
787 SetStringf(&con
->options
, "java %s %s", filename
, options
);
789 SetStringf(&con
->options
, "java %s", filename
);
791 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
792 con
->command
, con
->options
);
796 #endif /* HAVE_JAVA */
798 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
801 * "application/x-httpd-perl" is a Perl page.
804 SetString(&con
->command
, CUPS_PERL
);
807 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
809 SetStringf(&con
->options
, "perl %s", filename
);
811 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
812 con
->command
, con
->options
);
816 #endif /* HAVE_PERL */
818 else if (!strcasecmp(type
->type
, "x-httpd-php"))
821 * "application/x-httpd-php" is a PHP page.
824 SetString(&con
->command
, CUPS_PHP
);
827 SetStringf(&con
->options
, "php %s %s", filename
, options
);
829 SetStringf(&con
->options
, "php %s", filename
);
831 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
832 con
->command
, con
->options
);
836 #endif /* HAVE_PHP */
838 else if (!strcasecmp(type
->type
, "x-httpd-python"))
841 * "application/x-httpd-python" is a Python page.
844 SetString(&con
->command
, CUPS_PYTHON
);
847 SetStringf(&con
->options
, "python %s %s", filename
, options
);
849 SetStringf(&con
->options
, "python %s", filename
);
851 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
852 con
->command
, con
->options
);
856 #endif /* HAVE_PYTHON */
858 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
865 * 'ReadClient()' - Read data from a client.
868 int /* O - 1 on success, 0 on error */
869 ReadClient(client_t
*con
) /* I - Client to read from */
871 char line
[32768], /* Line from client... */
872 operation
[64], /* Operation code from socket */
873 version
[64], /* HTTP version number string */
874 locale
[64], /* Locale */
875 *ptr
; /* Pointer into strings */
876 int major
, minor
; /* HTTP version numbers */
877 http_status_t status
; /* Transfer status */
878 ipp_state_t ipp_state
; /* State of IPP transfer */
879 int bytes
; /* Number of bytes to POST */
880 char *filename
; /* Name of file for GET/HEAD */
881 char buf
[1024]; /* Buffer for real filename */
882 struct stat filestats
; /* File information */
883 mime_type_t
*type
; /* MIME type of file */
884 printer_t
*p
; /* Printer */
885 location_t
*best
; /* Best match for authentication */
886 static unsigned request_id
= 0; /* Request ID for temp files */
889 status
= HTTP_CONTINUE
;
891 LogMessage(L_DEBUG2
, "ReadClient() %d, used=%d", con
->http
.fd
,
900 switch (con
->http
.state
)
904 * See if we've received a request line...
907 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
914 * Ignore blank request lines...
921 * Clear other state variables...
924 httpClearFields(HTTP(con
));
926 con
->http
.activity
= time(NULL
);
927 con
->http
.version
= HTTP_1_0
;
928 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
929 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
930 con
->http
.data_remaining
= 0;
931 con
->operation
= HTTP_WAITING
;
935 con
->username
[0] = '\0';
936 con
->password
[0] = '\0';
939 ClearString(&con
->command
);
940 ClearString(&con
->options
);
942 if (con
->language
!= NULL
)
944 cupsLangFree(con
->language
);
945 con
->language
= NULL
;
949 * Grab the request line...
952 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
955 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
956 SendError(con
, HTTP_BAD_REQUEST
);
960 con
->http
.version
= HTTP_0_9
;
963 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
965 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
966 SendError(con
, HTTP_BAD_REQUEST
);
973 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
974 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
975 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
977 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
981 SendError(con
, HTTP_NOT_SUPPORTED
);
989 * Handle full URLs in the request line...
992 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
994 char method
[HTTP_MAX_URI
], /* Method/scheme */
995 userpass
[HTTP_MAX_URI
], /* Username:password */
996 hostname
[HTTP_MAX_URI
], /* Hostname */
997 resource
[HTTP_MAX_URI
]; /* Resource path */
998 int port
; /* Port number */
1002 * Separate the URI into its components...
1005 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
1008 * Only allow URIs with the servername, localhost, or an IP
1012 if (strcasecmp(hostname
, ServerName
) &&
1013 strcasecmp(hostname
, "localhost") &&
1014 !isdigit(hostname
[0]))
1017 * Nope, we don't do proxies...
1020 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
1021 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
1027 * Copy the resource portion back into the URI; both resource and
1028 * con->uri are HTTP_MAX_URI bytes in size...
1031 strcpy(con
->uri
, resource
);
1035 * Process the request...
1038 if (strcmp(operation
, "GET") == 0)
1039 con
->http
.state
= HTTP_GET
;
1040 else if (strcmp(operation
, "PUT") == 0)
1041 con
->http
.state
= HTTP_PUT
;
1042 else if (strcmp(operation
, "POST") == 0)
1043 con
->http
.state
= HTTP_POST
;
1044 else if (strcmp(operation
, "DELETE") == 0)
1045 con
->http
.state
= HTTP_DELETE
;
1046 else if (strcmp(operation
, "TRACE") == 0)
1047 con
->http
.state
= HTTP_TRACE
;
1048 else if (strcmp(operation
, "OPTIONS") == 0)
1049 con
->http
.state
= HTTP_OPTIONS
;
1050 else if (strcmp(operation
, "HEAD") == 0)
1051 con
->http
.state
= HTTP_HEAD
;
1054 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1055 SendError(con
, HTTP_BAD_REQUEST
);
1060 con
->start
= time(NULL
);
1061 con
->operation
= con
->http
.state
;
1063 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
1064 operation
, con
->uri
,
1065 con
->http
.version
/ 100, con
->http
.version
% 100);
1067 con
->http
.status
= HTTP_OK
;
1077 * Parse incoming parameters until the status changes...
1080 status
= httpUpdate(HTTP(con
));
1082 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1084 SendError(con
, HTTP_BAD_REQUEST
);
1091 break; /* Anti-compiler-warning-code */
1095 * Handle new transfers...
1098 if (status
== HTTP_OK
)
1100 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1103 * Figure out the locale from the Accept-Language and Content-Type
1107 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1110 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1113 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1116 * Combine language and charset, and trim any extra params in the
1120 snprintf(locale
, sizeof(locale
), "%s.%s",
1121 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1123 if ((ptr
= strchr(locale
, ',')) != NULL
)
1127 snprintf(locale
, sizeof(locale
), "%s.%s",
1128 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1130 con
->language
= cupsLangGet(locale
);
1133 con
->language
= cupsLangGet(DefaultLocale
);
1137 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1139 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1141 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1142 con
->http
.version
>= HTTP_1_1
)
1145 * HTTP/1.1 and higher require the "Host:" field...
1148 if (!SendError(con
, HTTP_BAD_REQUEST
))
1154 else if (con
->operation
== HTTP_OPTIONS
)
1157 * Do OPTIONS command...
1160 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1161 best
->type
!= AUTH_NONE
)
1163 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1170 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1171 con
->http
.tls
== NULL
)
1175 * Do encryption stuff...
1178 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1184 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1185 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1186 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1187 httpPrintf(HTTP(con
), "\r\n");
1191 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1196 #endif /* HAVE_SSL */
1199 if (con
->http
.expect
)
1201 /**** TODO: send expected header ****/
1204 if (!SendHeader(con
, HTTP_OK
, NULL
))
1210 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1211 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1212 httpPrintf(HTTP(con
), "\r\n");
1214 else if (strstr(con
->uri
, "..") != NULL
)
1217 * Protect against malicious users!
1220 if (!SendError(con
, HTTP_FORBIDDEN
))
1228 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
1229 con
->http
.tls
== NULL
)
1233 * Do encryption stuff...
1236 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1242 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1243 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1244 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1245 httpPrintf(HTTP(con
), "\r\n");
1249 status
= IsAuthorized(con
);
1251 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1256 #endif /* HAVE_SSL */
1259 if (status
!= HTTP_OK
)
1261 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1263 SendError(con
, status
);
1268 if (con
->http
.expect
)
1270 /**** TODO: send expected header ****/
1273 switch (con
->http
.state
)
1275 case HTTP_GET_SEND
:
1276 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1277 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1280 * Send PPD file - get the real printer name since printer
1281 * names are not case sensitive but filenames can be...
1284 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1286 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1287 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1290 if (!SendError(con
, HTTP_NOT_FOUND
))
1300 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1301 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1302 strncmp(con
->uri
, "/printers", 9) == 0 ||
1303 strncmp(con
->uri
, "/classes", 8) == 0 ||
1304 strncmp(con
->uri
, "/jobs", 5) == 0)
1307 * Send CGI output...
1310 if (strncmp(con
->uri
, "/admin", 6) == 0)
1312 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1313 SetString(&con
->options
, con
->uri
+ 6);
1315 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1317 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1318 SetString(&con
->options
, con
->uri
+ 9);
1320 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1322 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1323 SetString(&con
->options
, con
->uri
+ 8);
1327 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1328 SetString(&con
->options
, con
->uri
+ 5);
1331 if (con
->options
[0] == '/')
1332 cups_strcpy(con
->options
, con
->options
+ 1);
1334 if (!SendCommand(con
, con
->command
, con
->options
))
1336 if (!SendError(con
, HTTP_NOT_FOUND
))
1343 LogRequest(con
, HTTP_OK
);
1345 if (con
->http
.version
<= HTTP_1_0
)
1346 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1348 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1349 (strchr(con
->uri
+ 12, '/') != NULL
||
1350 strlen(con
->uri
) == 12))
1353 * GET can only be done to configuration files under
1357 if (!SendError(con
, HTTP_FORBIDDEN
))
1371 if ((filename
= get_file(con
, &filestats
, buf
,
1372 sizeof(buf
))) == NULL
)
1374 if (!SendError(con
, HTTP_NOT_FOUND
))
1383 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1385 if (IsCGI(con
, filename
, &filestats
, type
))
1387 if (!SendCommand(con
, con
->command
, con
->options
))
1389 if (!SendError(con
, HTTP_NOT_FOUND
))
1396 LogRequest(con
, HTTP_OK
);
1398 if (con
->http
.version
<= HTTP_1_0
)
1399 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1403 if (!check_if_modified(con
, &filestats
))
1405 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1414 strcpy(line
, "text/plain");
1416 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1418 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1427 case HTTP_POST_RECV
:
1429 * See if the POST request includes a Content-Length field, and if
1430 * so check the length against any limits that are set...
1433 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1434 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1436 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1437 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1441 * Request too large...
1444 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1452 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1455 * Negative content lengths are invalid!
1458 if (!SendError(con
, HTTP_BAD_REQUEST
))
1468 * See what kind of POST request this is; for IPP requests the
1469 * content-type field will be "application/ipp"...
1472 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1473 con
->request
= ippNew();
1474 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1475 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1476 strncmp(con
->uri
, "/printers", 9) == 0 ||
1477 strncmp(con
->uri
, "/classes", 8) == 0 ||
1478 strncmp(con
->uri
, "/jobs", 5) == 0)
1484 if (strncmp(con
->uri
, "/admin", 6) == 0)
1486 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1487 SetString(&con
->options
, con
->uri
+ 6);
1489 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1491 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1492 SetString(&con
->options
, con
->uri
+ 9);
1494 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1496 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1497 SetString(&con
->options
, con
->uri
+ 8);
1501 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1502 SetString(&con
->options
, con
->uri
+ 5);
1505 if (con
->options
[0] == '/')
1506 cups_strcpy(con
->options
, con
->options
+ 1);
1508 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
1509 con
->http
.fd
, con
->command
, con
->options
);
1511 if (con
->http
.version
<= HTTP_1_0
)
1512 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1520 if ((filename
= get_file(con
, &filestats
, buf
,
1521 sizeof(buf
))) == NULL
)
1523 if (!SendError(con
, HTTP_NOT_FOUND
))
1532 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1534 if (!IsCGI(con
, filename
, &filestats
, type
))
1537 * Only POST to CGI's...
1540 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1549 case HTTP_PUT_RECV
:
1551 * Validate the resource name...
1554 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1555 strchr(con
->uri
+ 12, '/') != NULL
||
1556 strlen(con
->uri
) == 12)
1559 * PUT can only be done to configuration files under
1563 if (!SendError(con
, HTTP_FORBIDDEN
))
1573 * See if the PUT request includes a Content-Length field, and if
1574 * so check the length against any limits that are set...
1577 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1578 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1580 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1581 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1585 * Request too large...
1588 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1596 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1599 * Negative content lengths are invalid!
1602 if (!SendError(con
, HTTP_BAD_REQUEST
))
1612 * Open a temporary file to hold the request...
1615 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1616 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1617 fchmod(con
->file
, 0640);
1618 fchown(con
->file
, getuid(), Group
);
1620 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1621 con
->filename
, con
->file
);
1625 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1635 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1640 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1641 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1644 * Send PPD file - get the real printer name since printer
1645 * names are not case sensitive but filenames can be...
1648 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1650 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1651 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1654 if (!SendError(con
, HTTP_NOT_FOUND
))
1664 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1665 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1666 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1667 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1668 strncmp(con
->uri
, "/jobs/", 6) == 0)
1674 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1680 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1686 LogRequest(con
, HTTP_OK
);
1688 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1689 (strchr(con
->uri
+ 12, '/') != NULL
||
1690 strlen(con
->uri
) == 12))
1693 * HEAD can only be done to configuration files under
1697 if (!SendError(con
, HTTP_FORBIDDEN
))
1705 else if ((filename
= get_file(con
, &filestats
, buf
,
1706 sizeof(buf
))) == NULL
)
1708 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1714 LogRequest(con
, HTTP_NOT_FOUND
);
1716 else if (!check_if_modified(con
, &filestats
))
1718 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1724 LogRequest(con
, HTTP_NOT_MODIFIED
);
1732 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1734 strcpy(line
, "text/plain");
1736 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1738 if (!SendHeader(con
, HTTP_OK
, line
))
1744 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1745 httpGetDateString(filestats
.st_mtime
)) < 0)
1751 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1752 (unsigned long)filestats
.st_size
) < 0)
1758 LogRequest(con
, HTTP_OK
);
1761 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1767 con
->http
.state
= HTTP_WAITING
;
1771 break; /* Anti-compiler-warning-code */
1777 * Handle any incoming data...
1780 switch (con
->http
.state
)
1782 case HTTP_PUT_RECV
:
1783 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1785 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1786 con
->http
.data_remaining
, con
->file
);
1788 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1795 con
->bytes
+= bytes
;
1797 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1798 con
->http
.fd
, bytes
, con
->file
);
1800 if (write(con
->file
, line
, bytes
) < bytes
)
1802 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1803 bytes
, con
->filename
, strerror(errno
));
1805 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1810 unlink(con
->filename
);
1811 ClearString(&con
->filename
);
1813 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1821 if (con
->http
.state
== HTTP_WAITING
)
1824 * End of file, see how big it is...
1827 fstat(con
->file
, &filestats
);
1829 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1830 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1835 if (filestats
.st_size
> MaxRequestSize
&&
1839 * Request is too big; remove it and send an error...
1842 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1843 con
->http
.fd
, con
->filename
);
1844 unlink(con
->filename
);
1845 ClearString(&con
->filename
);
1847 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1855 * Install the configuration file...
1858 status
= install_conf_file(con
);
1861 * Return the status to the client...
1864 if (!SendError(con
, status
))
1872 case HTTP_POST_RECV
:
1873 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1875 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1876 con
->http
.data_remaining
, con
->file
);
1878 if (con
->request
!= NULL
)
1881 * Grab any request data from the connection...
1884 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1886 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1889 if (!SendError(con
, HTTP_BAD_REQUEST
))
1898 else if (ipp_state
!= IPP_DATA
)
1901 con
->bytes
+= ippLength(con
->request
);
1904 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
1907 * Create a file as needed for the request data...
1910 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1911 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1912 fchmod(con
->file
, 0640);
1913 fchown(con
->file
, getuid(), Group
);
1915 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1916 con
->filename
, con
->file
);
1920 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1928 if (con
->http
.state
!= HTTP_POST_SEND
)
1930 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1937 con
->bytes
+= bytes
;
1939 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1940 con
->http
.fd
, bytes
, con
->file
);
1942 if (write(con
->file
, line
, bytes
) < bytes
)
1944 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1945 bytes
, con
->filename
, strerror(errno
));
1947 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1952 unlink(con
->filename
);
1953 ClearString(&con
->filename
);
1955 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1962 else if (con
->http
.state
== HTTP_POST_RECV
)
1966 else if (con
->http
.state
!= HTTP_POST_SEND
)
1973 if (con
->http
.state
== HTTP_POST_SEND
)
1977 fstat(con
->file
, &filestats
);
1979 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1980 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1985 if (filestats
.st_size
> MaxRequestSize
&&
1989 * Request is too big; remove it and send an error...
1992 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1993 con
->http
.fd
, con
->filename
);
1994 unlink(con
->filename
);
1995 ClearString(&con
->filename
);
2000 * Delete any IPP request data...
2003 ippDelete(con
->request
);
2004 con
->request
= NULL
;
2007 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
2016 if (!SendCommand(con
, con
->command
, con
->options
))
2018 if (!SendError(con
, HTTP_NOT_FOUND
))
2025 LogRequest(con
, HTTP_OK
);
2030 return (ProcessIPPRequest(con
));
2035 break; /* Anti-compiler-warning-code */
2038 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2049 * 'SendCommand()' - Send output from a command via HTTP.
2053 SendCommand(client_t
*con
,
2061 fd
= open(con
->filename
, O_RDONLY
);
2063 fd
= open("/dev/null", O_RDONLY
);
2065 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
2069 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
2071 LogMessage(L_DEBUG
, "SendCommand() %d file=%d", con
->http
.fd
, con
->file
);
2073 if (con
->pipe_pid
== 0)
2076 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2078 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
2079 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
2082 FD_SET(con
->file
, InputSet
);
2083 FD_SET(con
->http
.fd
, OutputSet
);
2085 if (!SendHeader(con
, HTTP_OK
, NULL
))
2088 if (con
->http
.version
== HTTP_1_1
)
2090 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2092 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2096 con
->got_fields
= 0;
2104 * 'SendError()' - Send an error message via HTTP.
2107 int /* O - 1 if successful, 0 otherwise */
2108 SendError(client_t
*con
, /* I - Connection */
2109 http_status_t code
) /* I - Error code */
2111 char message
[1024]; /* Message for user */
2115 * Put the request in the access_log file...
2118 if (con
->operation
> HTTP_WAITING
)
2119 LogRequest(con
, code
);
2121 LogMessage(L_DEBUG
, "SendError() %d code=%d (%s)", con
->http
.fd
, code
,
2125 * To work around bugs in some proxies, don't use Keep-Alive for some
2129 if (code
>= HTTP_BAD_REQUEST
)
2130 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2133 * Send an error message back to the client. If the error code is a
2134 * 400 or 500 series, make sure the message contains some text, too!
2137 if (!SendHeader(con
, code
, NULL
))
2141 if (code
== HTTP_UPGRADE_REQUIRED
)
2142 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2145 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2147 #endif /* HAVE_SSL */
2149 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2150 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2152 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2156 if (code
>= HTTP_BAD_REQUEST
)
2159 * Send a human-readable error message.
2162 snprintf(message
, sizeof(message
),
2163 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2164 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2165 code
, httpStatus(code
), httpStatus(code
),
2166 con
->language
? con
->language
->messages
[code
] :
2169 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
2171 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2172 (int)strlen(message
)) < 0)
2174 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2176 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2179 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2182 con
->http
.state
= HTTP_WAITING
;
2189 * 'SendFile()' - Send a file via HTTP.
2193 SendFile(client_t
*con
,
2197 struct stat
*filestats
)
2199 con
->file
= open(filename
, O_RDONLY
);
2201 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
2206 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2210 if (!SendHeader(con
, code
, type
))
2213 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2215 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2216 (unsigned long)filestats
->st_size
) < 0)
2218 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2221 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2223 FD_SET(con
->http
.fd
, OutputSet
);
2230 * 'SendHeader()' - Send an HTTP request.
2233 int /* O - 1 on success, 0 on failure */
2234 SendHeader(client_t
*con
, /* I - Client to send to */
2235 http_status_t code
, /* I - HTTP status code */
2236 char *type
) /* I - MIME type of document */
2238 location_t
*loc
; /* Authentication location */
2241 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2242 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2244 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2246 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
2248 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2250 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2252 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2255 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2256 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2259 if (code
== HTTP_UNAUTHORIZED
)
2262 * This already succeeded in IsAuthorized...
2265 loc
= FindBest(con
->uri
, con
->http
.state
);
2267 if (loc
->type
!= AUTH_DIGEST
)
2269 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2274 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
2275 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2279 if (con
->language
!= NULL
)
2281 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2282 con
->language
->language
) < 0)
2286 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
2287 cupsLangEncoding(con
->language
)) < 0)
2290 else if (type
!= NULL
)
2291 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2299 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2305 int bytes
; /* Number of bytes read */
2306 char *lineptr
, /* Pointer to end of line in buffer */
2307 *message
; /* Pointer to message text */
2308 int loglevel
; /* Log level for message */
2309 static int bufused
= 0; /* Number of bytes used in buffer */
2310 static char buffer
[1024]; /* Status buffer */
2313 if ((bytes
= read(CGIPipes
[0], buffer
+ bufused
,
2314 sizeof(buffer
) - bufused
- 1)) > 0)
2317 buffer
[bufused
] = '\0';
2318 lineptr
= strchr(buffer
, '\n');
2320 else if (bytes
< 0 && errno
== EINTR
)
2324 lineptr
= buffer
+ bufused
;
2328 if (bytes
== 0 && bufused
== 0)
2331 while (lineptr
!= NULL
)
2334 * Terminate each line and process it...
2340 * Figure out the logging level...
2343 if (strncmp(buffer
, "EMERG:", 6) == 0)
2346 message
= buffer
+ 6;
2348 else if (strncmp(buffer
, "ALERT:", 6) == 0)
2351 message
= buffer
+ 6;
2353 else if (strncmp(buffer
, "CRIT:", 5) == 0)
2356 message
= buffer
+ 5;
2358 else if (strncmp(buffer
, "ERROR:", 6) == 0)
2361 message
= buffer
+ 6;
2363 else if (strncmp(buffer
, "WARNING:", 8) == 0)
2366 message
= buffer
+ 8;
2368 else if (strncmp(buffer
, "NOTICE:", 6) == 0)
2370 loglevel
= L_NOTICE
;
2371 message
= buffer
+ 6;
2373 else if (strncmp(buffer
, "INFO:", 5) == 0)
2376 message
= buffer
+ 5;
2378 else if (strncmp(buffer
, "DEBUG:", 6) == 0)
2381 message
= buffer
+ 6;
2383 else if (strncmp(buffer
, "DEBUG2:", 7) == 0)
2385 loglevel
= L_DEBUG2
;
2386 message
= buffer
+ 7;
2388 else if (strncmp(buffer
, "PAGE:", 5) == 0)
2391 message
= buffer
+ 5;
2400 * Skip leading whitespace in the message...
2403 while (isspace(*message
))
2406 LogMessage(loglevel
, "[CGI] %s", message
);
2409 * Copy over the buffer data we've used up...
2412 strcpy(buffer
, lineptr
);
2413 bufused
-= lineptr
- buffer
;
2418 lineptr
= strchr(buffer
, '\n');
2424 * Fatal error on pipe - should never happen!
2427 LogMessage(L_ERROR
, "UpdateCGI: error reading from CGI error pipe - %s",
2434 * 'WriteClient()' - Write data to a client as needed.
2437 int /* O - 1 if success, 0 if fail */
2438 WriteClient(client_t
*con
) /* I - Client connection */
2440 int bytes
; /* Number of bytes written */
2441 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
2442 char *bufptr
; /* Pointer into buffer */
2443 ipp_state_t ipp_state
; /* IPP state value */
2446 if (con
->http
.state
!= HTTP_GET_SEND
&&
2447 con
->http
.state
!= HTTP_POST_SEND
)
2450 if (con
->response
!= NULL
)
2452 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2453 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2455 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
2457 if (con
->pipe_pid
&& !con
->got_fields
)
2460 * Inspect the data for Content-Type and other fields.
2465 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2466 if (*bufptr
== '\n')
2469 * Send line to client...
2472 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2476 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2477 LogMessage(L_DEBUG2
, "WriteClient() %d %s", con
->http
.fd
, buf
);
2483 bytes
-= (bufptr
- buf
);
2484 memcpy(buf
, bufptr
, bytes
+ 1);
2488 * See if the line was empty...
2491 if (con
->field_col
== 0)
2492 con
->got_fields
= 1;
2496 else if (*bufptr
!= '\r')
2499 if (bytes
> 0 && !con
->got_fields
)
2502 * Remaining text needs to go out...
2505 httpPrintf(HTTP(con
), "%s", buf
);
2507 con
->http
.activity
= time(NULL
);
2510 else if (bytes
== 0)
2512 con
->http
.activity
= time(NULL
);
2517 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2523 con
->bytes
+= bytes
;
2528 LogRequest(con
, HTTP_OK
);
2530 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2532 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2539 con
->http
.state
= HTTP_WAITING
;
2541 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from OutputSet...",
2544 FD_CLR(con
->http
.fd
, OutputSet
);
2548 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from InputSet...",
2550 FD_CLR(con
->file
, InputSet
);
2553 kill(con
->pipe_pid
, SIGTERM
);
2555 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
2556 con
->http
.fd
, con
->file
);
2565 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
2566 con
->http
.fd
, con
->filename
);
2567 unlink(con
->filename
);
2568 ClearString(&con
->filename
);
2571 if (con
->request
!= NULL
)
2573 ippDelete(con
->request
);
2574 con
->request
= NULL
;
2577 if (con
->response
!= NULL
)
2579 ippDelete(con
->response
);
2580 con
->response
= NULL
;
2583 ClearString(&con
->command
);
2584 ClearString(&con
->options
);
2586 if (!con
->http
.keep_alive
)
2594 LogMessage(L_DEBUG2
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
2596 con
->http
.activity
= time(NULL
);
2603 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2606 static int /* O - 1 if modified since */
2607 check_if_modified(client_t
*con
, /* I - Client connection */
2608 struct stat
*filestats
) /* I - File information */
2610 char *ptr
; /* Pointer into field */
2611 time_t date
; /* Time/date value */
2612 int size
; /* Size/length value */
2617 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2622 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
2625 while (*ptr
!= '\0')
2627 while (isspace(*ptr
) || *ptr
== ';')
2630 if (strncasecmp(ptr
, "length=", 7) == 0)
2635 while (isdigit(*ptr
))
2638 else if (isalpha(*ptr
))
2640 date
= httpGetDateTime(ptr
);
2641 while (*ptr
!= '\0' && *ptr
!= ';')
2646 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
2647 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2648 (int)filestats
->st_mtime
);
2650 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2651 (date
< filestats
->st_mtime
&& date
!= 0) ||
2652 (size
== 0 && date
== 0));
2657 * 'decode_auth()' - Decode an authorization string.
2661 decode_auth(client_t
*con
) /* I - Client to decode to */
2663 char *s
, /* Authorization string */
2664 value
[1024]; /* Value string */
2665 const char *username
; /* Certificate username */
2669 * Decode the string...
2672 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2674 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2677 if (strncmp(s
, "Basic", 5) == 0)
2683 httpDecode64(value
, s
);
2686 * Pull the username and password out...
2689 if ((s
= strchr(value
, ':')) == NULL
)
2691 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2692 con
->http
.fd
, value
);
2698 strlcpy(con
->username
, value
, sizeof(con
->username
));
2699 strlcpy(con
->password
, s
, sizeof(con
->password
));
2701 else if (strncmp(s
, "Local", 5) == 0)
2707 if ((username
= FindCert(s
)) != NULL
)
2708 strlcpy(con
->username
, username
, sizeof(con
->username
));
2710 else if (strncmp(s
, "Digest", 5) == 0)
2713 * Get the username and password from the Digest attributes...
2716 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2718 strlcpy(con
->username
, value
, sizeof(con
->username
));
2720 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2722 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2725 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2726 con
->http
.fd
, con
->username
);
2730 static char * /* O - Real filename */
2731 get_file(client_t
*con
, /* I - Client connection */
2732 struct stat
*filestats
, /* O - File information */
2733 char *filename
, /* IO - Filename buffer */
2734 int len
) /* I - Buffer length */
2736 int status
; /* Status of filesystem calls */
2737 char *ptr
; /* Pointer info filename */
2738 int plen
; /* Remaining length after pointer */
2742 * Need to add DocumentRoot global...
2745 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2746 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2747 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2748 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2749 else if (con
->language
!= NULL
)
2750 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2753 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2755 if ((ptr
= strchr(filename
, '?')) != NULL
)
2759 * Grab the status for this language; if there isn't a language-specific file
2760 * then fallback to the default one...
2763 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2766 * Drop the language prefix and try the current directory...
2769 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2770 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2772 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2774 if ((ptr
= strchr(filename
, '?')) != NULL
)
2777 status
= stat(filename
, filestats
);
2782 * If we're found a directory, get the index.html file instead...
2785 if (!status
&& S_ISDIR(filestats
->st_mode
))
2787 if (filename
[strlen(filename
) - 1] != '/')
2788 strlcat(filename
, "/", len
);
2790 ptr
= filename
+ strlen(filename
);
2791 plen
= len
- (ptr
- filename
);
2793 strlcpy(ptr
, "index.html", plen
);
2794 status
= stat(filename
, filestats
);
2799 strlcpy(ptr
, "index.class", plen
);
2800 status
= stat(filename
, filestats
);
2802 #endif /* HAVE_JAVA */
2807 strlcpy(ptr
, "index.pl", plen
);
2808 status
= stat(filename
, filestats
);
2810 #endif /* HAVE_PERL */
2815 strlcpy(ptr
, "index.php", plen
);
2816 status
= stat(filename
, filestats
);
2818 #endif /* HAVE_PHP */
2823 strlcpy(ptr
, "index.pyc", plen
);
2824 status
= stat(filename
, filestats
);
2829 strlcpy(ptr
, "index.py", plen
);
2830 status
= stat(filename
, filestats
);
2832 #endif /* HAVE_PYTHON */
2835 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2836 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2846 * 'install_conf_file()' - Install a configuration file.
2849 static http_status_t
/* O - Status */
2850 install_conf_file(client_t
*con
) /* I - Connection */
2852 cups_file_t
*in
, /* Input file */
2853 *out
; /* Output file */
2854 char buffer
[1024]; /* Copy buffer */
2855 int bytes
; /* Number of bytes */
2856 char conffile
[1024], /* Configuration filename */
2857 newfile
[1024], /* New config filename */
2858 oldfile
[1024]; /* Old config filename */
2859 struct stat confinfo
; /* Config file info */
2863 * First construct the filenames...
2866 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2867 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2868 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2870 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2873 * Get the owner, group, and permissions of the configuration file.
2874 * If it doesn't exist, assign it to the User and Group in the
2875 * cupsd.conf file with mode 0640 permissions.
2878 if (stat(conffile
, &confinfo
))
2880 confinfo
.st_uid
= User
;
2881 confinfo
.st_gid
= Group
;
2882 confinfo
.st_mode
= ConfigFilePerm
;
2886 * Open the request file and new config file...
2889 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2891 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2892 con
->filename
, strerror(errno
));
2893 return (HTTP_SERVER_ERROR
);
2896 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2899 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2900 newfile
, strerror(errno
));
2901 return (HTTP_SERVER_ERROR
);
2904 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2905 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2908 * Copy from the request to the new config file...
2911 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2912 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2914 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2915 newfile
, strerror(errno
));
2921 return (HTTP_SERVER_ERROR
);
2925 * Close the files...
2929 if (cupsFileClose(out
))
2931 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2932 newfile
, strerror(errno
));
2936 return (HTTP_SERVER_ERROR
);
2940 * Remove the request file...
2943 unlink(con
->filename
);
2944 ClearString(&con
->filename
);
2947 * Unlink the old backup, rename the current config file to the backup
2948 * filename, and rename the new config file to the config file name...
2951 if (unlink(oldfile
))
2952 if (errno
!= ENOENT
)
2954 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2955 oldfile
, strerror(errno
));
2959 return (HTTP_SERVER_ERROR
);
2962 if (rename(conffile
, oldfile
))
2963 if (errno
!= ENOENT
)
2965 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2966 conffile
, strerror(errno
));
2970 return (HTTP_SERVER_ERROR
);
2973 if (rename(newfile
, conffile
))
2975 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2976 newfile
, strerror(errno
));
2978 rename(oldfile
, conffile
);
2981 return (HTTP_SERVER_ERROR
);
2985 * If the cupsd.conf file was updated, set the NeedReload flag...
2988 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2989 NeedReload
= RELOAD_CUPSD
;
2991 NeedReload
= RELOAD_ALL
;
2993 ReloadTime
= time(NULL
);
2996 * Return that the file was created successfully...
2999 return (HTTP_CREATED
);
3004 * 'pipe_command()' - Pipe the output of a command to the remote client.
3007 static int /* O - Process ID */
3008 pipe_command(client_t
*con
, /* I - Client connection */
3009 int infile
, /* I - Standard input for command */
3010 int *outfile
, /* O - Standard output for command */
3011 char *command
, /* I - Command to run */
3012 char *options
) /* I - Options for command */
3014 int i
; /* Looping var */
3015 int pid
; /* Process ID */
3016 char *commptr
; /* Command string pointer */
3017 char *uriptr
; /* URI string pointer */
3018 int fd
; /* Looping var */
3019 int fds
[2]; /* Pipe FDs */
3020 int argc
; /* Number of arguments */
3021 int envc
; /* Number of environment variables */
3022 char argbuf
[10240], /* Argument buffer */
3023 *argv
[100], /* Argument strings */
3024 *envp
[100]; /* Environment variables */
3025 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3026 content_type
[1024], /* CONTENT_TYPE environment variable */
3027 cups_datadir
[1024], /* CUPS_DATADIR environment variable */
3028 cups_serverroot
[1024], /* CUPS_SERVERROOT environment variable */
3029 http_cookie
[1024], /* HTTP_COOKIE environment variable */
3030 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3031 ipp_port
[1024], /* IPP_PORT environment variable */
3032 lang
[1024], /* LANG environment variable */
3033 ld_library_path
[1024], /* LD_LIBRARY_PATH environment variable */
3034 ld_preload
[1024], /* LD_PRELOAD environment variable */
3035 dyld_library_path
[1024],/* DYLD_LIBRARY_PATH environment variable */
3036 shlib_path
[1024], /* SHLIB_PATH environment variable */
3037 nlspath
[1024], /* NLSPATH environment variable */
3038 query_string
[10240], /* QUERY_STRING env variable */
3039 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3040 remote_host
[1024], /* REMOTE_HOST environment variable */
3041 remote_user
[1024], /* REMOTE_USER environment variable */
3042 script_name
[1024], /* SCRIPT_NAME environment variable */
3043 server_name
[1024], /* SERVER_NAME environment variable */
3044 server_port
[1024], /* SERVER_PORT environment variable */
3045 tmpdir
[1024], /* TMPDIR environment variable */
3046 vg_args
[1024], /* VG_ARGS environment variable */
3047 ld_assume_kernel
[1024]; /* LD_ASSUME_KERNEL environment variable */
3048 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
3049 struct sigaction action
; /* POSIX signal handler */
3050 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
3051 static const char * const locale_encodings
[] =
3052 { /* Locale charset names */
3053 "ASCII", "ISO8859-1", "ISO8859-2", "ISO8859-3",
3054 "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7",
3055 "ISO8859-8", "ISO8859-9", "ISO8859-10", "UTF-8",
3056 "ISO8859-13", "ISO8859-14", "ISO8859-15", "CP874",
3057 "CP1250", "CP1251", "CP1252", "CP1253",
3058 "CP1254", "CP1255", "CP1256", "CP1257",
3059 "CP1258", "KOI8R", "KOI8U", "ISO8859-11",
3060 "ISO8859-16", "", "", "",
3071 "CP932", "CP936", "CP949", "CP950",
3072 "CP1361", "", "", "",
3089 "EUC-CN", "EUC-JP", "EUC-KR", "EUC-TW"
3094 * Copy the command string...
3097 strlcpy(argbuf
, options
, sizeof(argbuf
));
3100 * Parse the string; arguments can be separated by + and are terminated
3106 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
3107 if (*commptr
== ' ' || *commptr
== '+')
3111 while (*commptr
== ' ')
3114 if (*commptr
!= '\0')
3116 argv
[argc
] = commptr
;
3122 else if (*commptr
== '%')
3124 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3125 *commptr
= (commptr
[1] - '0') << 4;
3127 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3129 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3130 *commptr
|= commptr
[2] - '0';
3132 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3134 cups_strcpy(commptr
+ 1, commptr
+ 3);
3136 else if (*commptr
== '?')
3141 if (argv
[0][0] == '\0')
3142 argv
[0] = strrchr(command
, '/') + 1;
3145 * Setup the environment variables as needed...
3149 snprintf(lang
, sizeof(lang
), "LANG=%s.%s", con
->language
->language
,
3150 locale_encodings
[con
->language
->encoding
]);
3152 strcpy(lang
, "LANG=C");
3154 sprintf(ipp_port
, "IPP_PORT=%d", LocalPort
);
3156 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
3157 sprintf(server_port
, "SERVER_PORT=%d",
3158 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
3160 #endif /* AF_INET6 */
3161 sprintf(server_port
, "SERVER_PORT=%d",
3162 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
3164 if (strcmp(con
->http
.hostname
, "localhost") == 0)
3165 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
3167 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
3168 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
3169 strcpy(remote_addr
, "REMOTE_ADDR=");
3170 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3171 sizeof(remote_addr
) - 12);
3172 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3173 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
3174 snprintf(cups_datadir
, sizeof(cups_datadir
), "CUPS_DATADIR=%s", DataDir
);
3175 snprintf(cups_serverroot
, sizeof(cups_serverroot
), "CUPS_SERVERROOT=%s", ServerRoot
);
3179 envp
[envc
++] = "PATH=/bin:/usr/bin";
3180 envp
[envc
++] = "SERVER_SOFTWARE=CUPS/1.1";
3181 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3182 if (con
->http
.version
== HTTP_1_1
)
3183 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3184 else if (con
->http
.version
== HTTP_1_0
)
3185 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3187 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3188 envp
[envc
++] = "REDIRECT_STATUS=1";
3189 envp
[envc
++] = "CUPS_SERVER=localhost";
3190 envp
[envc
++] = ipp_port
;
3191 envp
[envc
++] = server_name
;
3192 envp
[envc
++] = server_port
;
3193 envp
[envc
++] = remote_addr
;
3194 envp
[envc
++] = remote_host
;
3195 envp
[envc
++] = remote_user
;
3196 envp
[envc
++] = lang
;
3198 envp
[envc
++] = tmpdir
;
3199 envp
[envc
++] = cups_datadir
;
3200 envp
[envc
++] = cups_serverroot
;
3202 if (getenv("VG_ARGS") != NULL
)
3204 snprintf(vg_args
, sizeof(vg_args
), "VG_ARGS=%s", getenv("VG_ARGS"));
3205 envp
[envc
++] = vg_args
;
3208 if (getenv("LD_ASSUME_KERNEL") != NULL
)
3210 snprintf(ld_assume_kernel
, sizeof(ld_assume_kernel
), "LD_ASSUME_KERNEL=%s",
3211 getenv("LD_ASSUME_KERNEL"));
3212 envp
[envc
++] = ld_assume_kernel
;
3215 if (getenv("LD_LIBRARY_PATH") != NULL
)
3217 snprintf(ld_library_path
, sizeof(ld_library_path
), "LD_LIBRARY_PATH=%s",
3218 getenv("LD_LIBRARY_PATH"));
3219 envp
[envc
++] = ld_library_path
;
3222 if (getenv("LD_PRELOAD") != NULL
)
3224 snprintf(ld_preload
, sizeof(ld_preload
), "LD_PRELOAD=%s",
3225 getenv("LD_PRELOAD"));
3226 envp
[envc
++] = ld_preload
;
3229 if (getenv("DYLD_LIBRARY_PATH") != NULL
)
3231 snprintf(dyld_library_path
, sizeof(dyld_library_path
), "DYLD_LIBRARY_PATH=%s",
3232 getenv("DYLD_LIBRARY_PATH"));
3233 envp
[envc
++] = dyld_library_path
;
3236 if (getenv("SHLIB_PATH") != NULL
)
3238 snprintf(shlib_path
, sizeof(shlib_path
), "SHLIB_PATH=%s",
3239 getenv("SHLIB_PATH"));
3240 envp
[envc
++] = shlib_path
;
3243 if (getenv("NLSPATH") != NULL
)
3245 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
3246 envp
[envc
++] = nlspath
;
3249 if (con
->http
.cookie
)
3251 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3253 envp
[envc
++] = http_cookie
;
3256 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3258 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3259 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3260 envp
[envc
++] = http_user_agent
;
3263 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3264 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3266 envp
[envc
++] = script_name
;
3268 if (con
->operation
== HTTP_GET
)
3270 for (i
= 0; i
< argc
; i
++)
3271 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3272 envp
[envc
++] = "REQUEST_METHOD=GET";
3277 * Add GET form variables after ?...
3282 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
3283 envp
[envc
++] = query_string
;
3288 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3289 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3290 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3292 envp
[envc
++] = "REQUEST_METHOD=POST";
3293 envp
[envc
++] = content_length
;
3294 envp
[envc
++] = content_type
;
3298 * Tell the CGI if we are using encryption...
3301 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3303 envp
[envc
++] = "HTTPS=ON";
3304 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
3309 if (LogLevel
== L_DEBUG2
)
3311 for (i
= 0; i
< argc
; i
++)
3312 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3313 for (i
= 0; i
< envc
; i
++)
3314 LogMessage(L_DEBUG2
, "envp[%d] = \"%s\"", i
, envp
[i
]);
3318 * Create a pipe for the output...
3323 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3324 argv
[0], strerror(errno
));
3329 * Block signals before forking...
3335 * Then execute the command...
3338 if ((pid
= fork()) == 0)
3341 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
3347 * Running as root, so change to a non-priviledged user...
3353 if (setgroups(1, &Group
))
3362 * Reset group membership to just the main one we belong to.
3365 setgroups(1, &Group
);
3369 * Update stdin/stdout/stderr...
3375 if (dup(infile
) < 0)
3380 if (dup(fds
[1]) < 0)
3387 * Close extra file descriptors...
3390 for (fd
= 3; fd
< MaxFDs
; fd
++)
3394 * Change umask to restrict permissions on created files...
3400 * Unblock signals before doing the exec...
3404 sigset(SIGTERM
, SIG_DFL
);
3405 sigset(SIGCHLD
, SIG_DFL
);
3406 #elif defined(HAVE_SIGACTION)
3407 memset(&action
, 0, sizeof(action
));
3409 sigemptyset(&action
.sa_mask
);
3410 action
.sa_handler
= SIG_DFL
;
3412 sigaction(SIGTERM
, &action
, NULL
);
3413 sigaction(SIGCHLD
, &action
, NULL
);
3415 signal(SIGTERM
, SIG_DFL
);
3416 signal(SIGCHLD
, SIG_DFL
);
3417 #endif /* HAVE_SIGSET */
3422 * Execute the pipe program; if an error occurs, exit with status 1...
3425 execve(command
, argv
, envp
);
3432 * Error - can't fork!
3435 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3445 * Fork successful - return the PID...
3448 AddCert(pid
, con
->username
);
3450 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3462 #if defined(HAVE_CDSASSL)
3464 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3467 static OSStatus
/* O - -1 on error, 0 on success */
3468 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3469 void *data
, /* I - Data buffer */
3470 size_t *dataLength
) /* IO - Number of bytes */
3472 ssize_t bytes
; /* Number of bytes read */
3475 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3478 *dataLength
= bytes
;
3487 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3490 static OSStatus
/* O - -1 on error, 0 on success */
3491 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3492 const void *data
, /* I - Data buffer */
3493 size_t *dataLength
) /* IO - Number of bytes */
3498 bytes
= write((int)connection
, data
, *dataLength
);
3501 *dataLength
= bytes
;
3507 #endif /* HAVE_CDSASSL */
3511 * End of "$Id: client.c,v 1.91.2.75 2004/02/05 20:54:44 mike Exp $".