4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2005 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 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * AcceptClient() - Accept a new client.
27 * CloseAllClients() - Close all remote clients immediately.
28 * CloseClient() - Close a remote client.
29 * EncryptClient() - Enable encryption for the client...
30 * IsCGI() - Is the resource a CGI script/program?
31 * ReadClient() - Read data from a client.
32 * SendCommand() - Send output from a command via HTTP.
33 * SendError() - Send an error message via HTTP.
34 * SendFile() - Send a file via HTTP.
35 * SendHeader() - Send an HTTP request.
36 * UpdateCGI() - Read status messages from CGI scripts and programs.
37 * WriteClient() - Write data to a client as needed.
38 * check_if_modified() - Decode an "If-Modified-Since" line.
39 * decode_auth() - Decode an authorization string.
40 * get_file() - Get a filename and state info.
41 * install_conf_file() - Install a configuration file.
42 * is_path_absolute() - Is a path absolute and free of relative elements.
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>
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 is_path_absolute(const char *path
);
67 static int pipe_command(client_t
*con
, int infile
, int *outfile
,
68 char *command
, char *options
, int root
);
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(lis=%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
);
117 * Accept the client and get the remote address...
120 val
= sizeof(struct sockaddr_in
);
122 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
125 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
131 if (lis
->address
.addr
.sa_family
== AF_INET6
)
132 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
134 #endif /* AF_INET6 */
135 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
138 * Check the number of clients on the same address...
141 for (i
= 0, count
= 0; i
< NumClients
; i
++)
142 if (httpAddrEqual(&(Clients
[i
].http
.hostaddr
), &(con
->http
.hostaddr
)))
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...
171 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
174 * Map accesses from the loopback interface to "localhost"...
177 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
178 hostname
= con
->http
.hostname
;
180 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
183 * Map accesses from the same host to the server name.
186 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
187 hostname
= con
->http
.hostname
;
189 else if (HostNameLookups
)
190 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
191 sizeof(con
->http
.hostname
));
195 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
196 sizeof(con
->http
.hostname
));
199 if (hostname
== NULL
&& HostNameLookups
== 2)
202 * Can't have an unresolved IP address with double-lookups enabled...
205 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
209 closesocket(con
->http
.fd
);
214 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
219 if (HostNameLookups
== 2)
222 * Do double lookups as needed...
225 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
228 * See if the hostname maps to the same IP address...
231 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
234 * Not the right type of address...
242 * Compare all of the addresses against this one...
245 for (i
= 0; host
->h_addr_list
[i
]; i
++)
247 httpAddrLoad(host
, 0, i
, &temp
);
249 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
253 if (!host
->h_addr_list
[i
])
261 * Can't have a hostname that doesn't resolve to the same IP address
262 * with double-lookups enabled...
265 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
269 closesocket(con
->http
.fd
);
274 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
281 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
282 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
283 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
285 #endif /* AF_INET6 */
286 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
287 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
290 * Get the local address the client connected to...
294 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &i
))
296 LogMessage(L_ERROR
, "Unable to get local address - %s", strerror(errno
));
298 strcpy(con
->servername
, "localhost");
299 con
->serverport
= LocalPort
;
304 if (temp
.addr
.sa_family
== AF_INET6
)
306 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
307 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
310 #endif /* AF_INET6 */
311 if (temp
.addr
.sa_family
== AF_INET
)
313 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
314 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
318 strcpy(con
->servername
, "localhost");
319 con
->serverport
= LocalPort
;
323 LogMessage(L_DEBUG2
, "AcceptClient: %d connected to server on %s:%d",
324 con
->http
.fd
, con
->servername
, con
->serverport
);
326 * Using TCP_NODELAY improves responsiveness, especially on systems
327 * with a slow loopback interface... Since we write large buffers
328 * when sending print files and requests, there shouldn't be any
329 * performance penalty for this...
333 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
336 * Close this file on all execs...
339 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
342 * Add the socket to the select() input mask.
345 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
347 FD_SET(con
->http
.fd
, InputSet
);
352 * Temporarily suspend accept()'s until we lose a client...
355 if (NumClients
== MaxClients
)
360 * See if we are connecting on a secure port...
363 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
366 * https connection; go secure...
369 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
375 #endif /* HAVE_SSL */
380 * 'CloseAllClients()' - Close all remote clients immediately.
384 CloseAllClients(void)
386 while (NumClients
> 0)
387 CloseClient(Clients
);
392 * 'CloseClient()' - Close a remote client.
395 int /* O - 1 if partial close, 0 if fully closed */
396 CloseClient(client_t
*con
) /* I - Client to close */
398 int partial
; /* Do partial close for SSL? */
399 #if defined(HAVE_LIBSSL)
400 SSL_CTX
*context
; /* Context for encryption */
401 SSL
*conn
; /* Connection for encryption */
402 unsigned long error
; /* Error code */
403 #elif defined(HAVE_GNUTLS)
404 http_tls_t
*conn
; /* TLS connection information */
405 int error
; /* Error code */
406 gnutls_certificate_server_credentials
*credentials
;
407 /* TLS credentials */
408 #elif defined(HAVE_CDSASSL)
409 int status
; /* Error status */
410 #endif /* HAVE_LIBSSL */
413 LogMessage(L_DEBUG
, "CloseClient: %d", con
->http
.fd
);
416 * Flush pending writes before closing...
419 httpFlushWrite(HTTP(con
));
425 * Shutdown encryption as needed...
433 conn
= (SSL
*)(con
->http
.tls
);
434 context
= SSL_get_SSL_CTX(conn
);
436 switch (SSL_shutdown(conn
))
439 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
442 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
444 while ((error
= ERR_get_error()) != 0)
445 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
449 SSL_CTX_free(context
);
452 # elif defined(HAVE_GNUTLS)
453 conn
= (http_tls_t
*)(con
->http
.tls
);
454 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
456 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
459 case GNUTLS_E_SUCCESS
:
460 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
463 LogMessage(L_ERROR
, "CloseClient: %s", gnutls_strerror(error
));
467 gnutls_deinit(conn
->session
);
468 gnutls_certificate_free_credentials(*credentials
);
472 # elif defined(HAVE_CDSASSL)
473 status
= SSLClose((SSLContextRef
)con
->http
.tls
);
474 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
475 # endif /* HAVE_LIBSSL */
477 con
->http
.tls
= NULL
;
479 #endif /* HAVE_SSL */
482 * Close the socket and clear the file from the input set for select()...
485 if (con
->http
.fd
> 0)
490 * Only do a partial close so that the encrypted client gets everything.
493 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from OutputSet...",
495 shutdown(con
->http
.fd
, 0);
496 FD_CLR(con
->http
.fd
, OutputSet
);
501 * Shut the socket down fully...
504 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
507 FD_CLR(con
->http
.fd
, InputSet
);
508 FD_CLR(con
->http
.fd
, OutputSet
);
513 if (con
->pipe_pid
!= 0)
516 * Stop any CGI process...
519 LogMessage(L_DEBUG2
, "CloseClient: %d Killing process ID %d...",
520 con
->http
.fd
, con
->pipe_pid
);
521 cupsdEndProcess(con
->pipe_pid
, 1);
526 if (FD_ISSET(con
->file
, InputSet
))
528 LogMessage(L_DEBUG2
, "CloseClient: %d Removing fd %d from InputSet...",
529 con
->http
.fd
, con
->file
);
530 FD_CLR(con
->file
, InputSet
);
533 LogMessage(L_DEBUG2
, "CloseClient: %d Closing data file %d.",
534 con
->http
.fd
, con
->file
);
546 if (con
->http
.input_set
)
547 free(con
->http
.input_set
);
549 httpClearCookie(HTTP(con
));
551 ClearString(&con
->filename
);
552 ClearString(&con
->command
);
553 ClearString(&con
->options
);
557 ippDelete(con
->request
);
563 ippDelete(con
->response
);
564 con
->response
= NULL
;
569 cupsLangFree(con
->language
);
570 con
->language
= NULL
;
574 * Re-enable new client connections if we are going back under the
578 if (NumClients
== MaxClients
)
582 * Compact the list of clients as necessary...
587 if (con
< (Clients
+ NumClients
))
588 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
596 * 'EncryptClient()' - Enable encryption for the client...
599 int /* O - 1 on success, 0 on error */
600 EncryptClient(client_t
*con
) /* I - Client to encrypt */
602 #if defined HAVE_LIBSSL
603 SSL_CTX
*context
; /* Context for encryption */
604 SSL
*conn
; /* Connection for encryption */
605 unsigned long error
; /* Error code */
609 * Create the SSL context and accept the connection...
612 context
= SSL_CTX_new(SSLv23_server_method());
614 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
615 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
616 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
618 conn
= SSL_new(context
);
620 SSL_set_fd(conn
, con
->http
.fd
);
621 if (SSL_accept(conn
) != 1)
623 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
626 while ((error
= ERR_get_error()) != 0)
627 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
629 SSL_CTX_free(context
);
634 LogMessage(L_DEBUG
, "EncryptClient: %d Connection from %s now encrypted.",
635 con
->http
.fd
, con
->http
.hostname
);
637 con
->http
.tls
= conn
;
640 #elif defined(HAVE_GNUTLS)
641 http_tls_t
*conn
; /* TLS session object */
642 int error
; /* Error code */
643 gnutls_certificate_server_credentials
*credentials
;
644 /* TLS credentials */
647 * Create the SSL object and perform the SSL handshake...
650 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
655 credentials
= (gnutls_certificate_server_credentials
*)
656 malloc(sizeof(gnutls_certificate_server_credentials
));
657 if (credentials
== NULL
)
659 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
661 LogMessage(L_ERROR
, "EncryptClient: %s", strerror(errno
));
667 gnutls_certificate_allocate_credentials(credentials
);
668 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
669 ServerKey
, GNUTLS_X509_FMT_PEM
);
671 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
672 gnutls_set_default_priority(conn
->session
);
673 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
674 gnutls_transport_set_ptr(conn
->session
, con
->http
.fd
);
676 error
= gnutls_handshake(conn
->session
);
678 if (error
!= GNUTLS_E_SUCCESS
)
680 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
682 LogMessage(L_ERROR
, "EncryptClient: %s", gnutls_strerror(error
));
684 gnutls_deinit(conn
->session
);
685 gnutls_certificate_free_credentials(*credentials
);
691 LogMessage(L_DEBUG
, "EncryptClient: %d Connection from %s now encrypted.",
692 con
->http
.fd
, con
->http
.hostname
);
694 conn
->credentials
= credentials
;
695 con
->http
.tls
= conn
;
698 #elif defined(HAVE_CDSASSL)
699 OSStatus error
; /* Error info */
700 SSLContextRef conn
; /* New connection */
701 SSLProtocol tryVersion
; /* Protocol version */
702 const char *hostName
; /* Local hostname */
703 int allowExpired
; /* Allow expired certificates? */
704 int allowAnyRoot
; /* Allow any root certificate? */
705 SSLProtocol
*negVersion
; /* Negotiated protocol version */
706 SSLCipherSuite
*negCipher
; /* Negotiated cypher */
707 CFArrayRef
*peerCerts
; /* Certificates */
711 error
= SSLNewContext(true, &conn
);
716 error
= SSLSetIOFuncs(conn
, CDSAReadFunc
, CDSAWriteFunc
);
719 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
722 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
726 hostName
= ServerName
; /* MRS: ??? */
727 error
= SSLSetPeerDomainName(conn
, hostName
, strlen(hostName
) + 1);
730 /* have to do these options befor setting server certs */
731 if (!error
&& allowExpired
)
732 error
= SSLSetAllowsExpiredCerts(conn
, true);
734 if (!error
&& allowAnyRoot
)
735 error
= SSLSetAllowsAnyRoot(conn
, true);
737 if (!error
&& ServerCertificatesArray
!= NULL
)
738 error
= SSLSetCertificate(conn
, ServerCertificatesArray
);
741 * Perform SSL/TLS handshake
746 error
= SSLHandshake(conn
);
748 while (error
== errSSLWouldBlock
);
752 LogMessage(L_ERROR
, "EncryptClient: Unable to encrypt connection from %s!",
755 LogMessage(L_ERROR
, "EncryptClient: CDSA error code is %d", error
);
757 con
->http
.error
= error
;
758 con
->http
.status
= HTTP_ERROR
;
761 SSLDisposeContext(conn
);
766 LogMessage(L_DEBUG
, "EncryptClient: %d Connection from %s now encrypted.",
767 con
->http
.fd
, con
->http
.hostname
);
769 con
->http
.tls
= conn
;
774 #endif /* HAVE_GNUTLS */
779 * 'IsCGI()' - Is the resource a CGI script/program?
782 int /* O - 1 = CGI, 0 = file */
783 IsCGI(client_t
*con
, /* I - Client connection */
784 const char *filename
, /* I - Real filename */
785 struct stat
*filestats
, /* I - File information */
786 mime_type_t
*type
) /* I - MIME type */
788 const char *options
; /* Options on URL */
791 LogMessage(L_DEBUG2
, "IsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
792 con
, filename
, filestats
, type
? type
->super
: "unknown",
793 type
? type
->type
: "unknown");
796 * Get the options, if any...
799 if ((options
= strchr(con
->uri
, '?')) != NULL
)
803 * Check for known types...
806 if (!type
|| strcasecmp(type
->super
, "application"))
808 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
812 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
813 (filestats
->st_mode
& 0111))
816 * "application/x-httpd-cgi" is a CGI script.
819 SetString(&con
->command
, filename
);
821 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
824 SetStringf(&con
->options
, "%s %s", filename
, options
);
826 SetStringf(&con
->options
, "%s", filename
);
828 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
829 con
->command
, con
->options
);
834 else if (!strcasecmp(type
->type
, "x-httpd-java"))
837 * "application/x-httpd-java" is a Java servlet.
840 SetString(&con
->command
, CUPS_JAVA
);
843 SetStringf(&con
->options
, "java %s %s", filename
, options
);
845 SetStringf(&con
->options
, "java %s", filename
);
847 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
848 con
->command
, con
->options
);
852 #endif /* HAVE_JAVA */
854 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
857 * "application/x-httpd-perl" is a Perl page.
860 SetString(&con
->command
, CUPS_PERL
);
863 SetStringf(&con
->options
, "perl %s %s", filename
, options
);
865 SetStringf(&con
->options
, "perl %s", filename
);
867 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
868 con
->command
, con
->options
);
872 #endif /* HAVE_PERL */
874 else if (!strcasecmp(type
->type
, "x-httpd-php"))
877 * "application/x-httpd-php" is a PHP page.
880 SetString(&con
->command
, CUPS_PHP
);
883 SetStringf(&con
->options
, "php %s %s", filename
, options
);
885 SetStringf(&con
->options
, "php %s", filename
);
887 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
888 con
->command
, con
->options
);
892 #endif /* HAVE_PHP */
894 else if (!strcasecmp(type
->type
, "x-httpd-python"))
897 * "application/x-httpd-python" is a Python page.
900 SetString(&con
->command
, CUPS_PYTHON
);
903 SetStringf(&con
->options
, "python %s %s", filename
, options
);
905 SetStringf(&con
->options
, "python %s", filename
);
907 LogMessage(L_DEBUG2
, "IsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
908 con
->command
, con
->options
);
912 #endif /* HAVE_PYTHON */
914 LogMessage(L_DEBUG2
, "IsCGI: Returning 0...");
921 * 'ReadClient()' - Read data from a client.
924 int /* O - 1 on success, 0 on error */
925 ReadClient(client_t
*con
) /* I - Client to read from */
927 char line
[32768], /* Line from client... */
928 operation
[64], /* Operation code from socket */
929 version
[64], /* HTTP version number string */
930 locale
[64], /* Locale */
931 *ptr
; /* Pointer into strings */
932 int major
, minor
; /* HTTP version numbers */
933 http_status_t status
; /* Transfer status */
934 ipp_state_t ipp_state
; /* State of IPP transfer */
935 int bytes
; /* Number of bytes to POST */
936 char *filename
; /* Name of file for GET/HEAD */
937 char buf
[1024]; /* Buffer for real filename */
938 struct stat filestats
; /* File information */
939 mime_type_t
*type
; /* MIME type of file */
940 printer_t
*p
; /* Printer */
941 static unsigned request_id
= 0; /* Request ID for temp files */
944 status
= HTTP_CONTINUE
;
946 LogMessage(L_DEBUG2
, "ReadClient: %d, used=%d, file=%d", con
->http
.fd
,
947 con
->http
.used
, con
->file
);
951 LogMessage(L_DEBUG2
, "ReadClient: http error seen...");
952 return (CloseClient(con
));
959 * Automatically check for a SSL/TLS handshake...
964 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
965 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
968 * Encrypt this connection...
971 LogMessage(L_DEBUG2
, "ReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
978 #endif /* HAVE_SSL */
980 switch (con
->http
.state
)
984 * See if we've received a request line...
987 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
989 LogMessage(L_DEBUG2
, "ReadClient: httpGets returned EOF...");
990 return (CloseClient(con
));
994 * Ignore blank request lines...
1001 * Clear other state variables...
1004 httpClearFields(HTTP(con
));
1006 con
->http
.activity
= time(NULL
);
1007 con
->http
.version
= HTTP_1_0
;
1008 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1009 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
1010 con
->http
.data_remaining
= 0;
1011 con
->operation
= HTTP_WAITING
;
1014 con
->file_ready
= 0;
1016 con
->username
[0] = '\0';
1017 con
->password
[0] = '\0';
1020 ClearString(&con
->command
);
1021 ClearString(&con
->options
);
1023 if (con
->language
!= NULL
)
1025 cupsLangFree(con
->language
);
1026 con
->language
= NULL
;
1030 * Grab the request line...
1033 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
1036 LogMessage(L_ERROR
, "Bad request line \"%s\" from %s!", line
,
1037 con
->http
.hostname
);
1038 SendError(con
, HTTP_BAD_REQUEST
);
1039 return (CloseClient(con
));
1041 con
->http
.version
= HTTP_0_9
;
1044 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
1046 LogMessage(L_ERROR
, "Bad request line \"%s\" from %s!", line
,
1047 con
->http
.hostname
);
1048 SendError(con
, HTTP_BAD_REQUEST
);
1049 return (CloseClient(con
));
1054 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
1055 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
1056 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1058 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1062 SendError(con
, HTTP_NOT_SUPPORTED
);
1063 return (CloseClient(con
));
1069 * Handle full URLs in the request line...
1072 if (con
->uri
[0] != '/' && strcmp(con
->uri
, "*"))
1074 char method
[HTTP_MAX_URI
], /* Method/scheme */
1075 userpass
[HTTP_MAX_URI
], /* Username:password */
1076 hostname
[HTTP_MAX_URI
], /* Hostname */
1077 resource
[HTTP_MAX_URI
]; /* Resource path */
1078 int port
; /* Port number */
1082 * Separate the URI into its components...
1085 httpSeparate(con
->uri
, method
, userpass
, hostname
, &port
, resource
);
1088 * Only allow URIs with the servername, localhost, or an IP
1092 if (strcasecmp(hostname
, ServerName
) &&
1093 strcasecmp(hostname
, "localhost") &&
1094 !isdigit(hostname
[0]))
1097 * Nope, we don't do proxies...
1100 LogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
1101 SendError(con
, HTTP_METHOD_NOT_ALLOWED
);
1102 return (CloseClient(con
));
1106 * Copy the resource portion back into the URI; both resource and
1107 * con->uri are HTTP_MAX_URI bytes in size...
1110 strcpy(con
->uri
, resource
);
1114 * Process the request...
1117 if (strcmp(operation
, "GET") == 0)
1118 con
->http
.state
= HTTP_GET
;
1119 else if (strcmp(operation
, "PUT") == 0)
1120 con
->http
.state
= HTTP_PUT
;
1121 else if (strcmp(operation
, "POST") == 0)
1122 con
->http
.state
= HTTP_POST
;
1123 else if (strcmp(operation
, "DELETE") == 0)
1124 con
->http
.state
= HTTP_DELETE
;
1125 else if (strcmp(operation
, "TRACE") == 0)
1126 con
->http
.state
= HTTP_TRACE
;
1127 else if (strcmp(operation
, "OPTIONS") == 0)
1128 con
->http
.state
= HTTP_OPTIONS
;
1129 else if (strcmp(operation
, "HEAD") == 0)
1130 con
->http
.state
= HTTP_HEAD
;
1133 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1134 SendError(con
, HTTP_BAD_REQUEST
);
1135 return (CloseClient(con
));
1138 con
->start
= time(NULL
);
1139 con
->operation
= con
->http
.state
;
1141 LogMessage(L_DEBUG
, "ReadClient: %d %s %s HTTP/%d.%d", con
->http
.fd
,
1142 operation
, con
->uri
,
1143 con
->http
.version
/ 100, con
->http
.version
% 100);
1145 con
->http
.status
= HTTP_OK
;
1155 * Parse incoming parameters until the status changes...
1158 status
= httpUpdate(HTTP(con
));
1160 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1162 SendError(con
, HTTP_BAD_REQUEST
);
1163 return (CloseClient(con
));
1168 break; /* Anti-compiler-warning-code */
1172 * Handle new transfers...
1175 if (status
== HTTP_OK
)
1177 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1180 * Figure out the locale from the Accept-Language and Content-Type
1184 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1187 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1190 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1193 * Combine language and charset, and trim any extra params in the
1197 snprintf(locale
, sizeof(locale
), "%s.%s",
1198 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1200 if ((ptr
= strchr(locale
, ',')) != NULL
)
1204 snprintf(locale
, sizeof(locale
), "%s.%s",
1205 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1207 con
->language
= cupsLangGet(locale
);
1210 con
->language
= cupsLangGet(DefaultLocale
);
1214 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
1216 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1218 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
1219 con
->http
.version
>= HTTP_1_1
)
1222 * HTTP/1.1 and higher require the "Host:" field...
1225 if (!SendError(con
, HTTP_BAD_REQUEST
))
1226 return (CloseClient(con
));
1228 else if (con
->operation
== HTTP_OPTIONS
)
1231 * Do OPTIONS command...
1234 if ((con
->best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1235 con
->best
->type
!= AUTH_NONE
)
1237 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1238 return (CloseClient(con
));
1241 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1242 con
->http
.tls
== NULL
)
1246 * Do encryption stuff...
1249 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1250 return (CloseClient(con
));
1252 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1253 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1254 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1255 httpPrintf(HTTP(con
), "\r\n");
1259 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1260 return (CloseClient(con
));
1261 #endif /* HAVE_SSL */
1264 if (con
->http
.expect
)
1266 /**** TODO: send expected header ****/
1269 if (!SendHeader(con
, HTTP_OK
, NULL
))
1270 return (CloseClient(con
));
1272 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1273 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1274 httpPrintf(HTTP(con
), "\r\n");
1276 else if (!is_path_absolute(con
->uri
))
1279 * Protect against malicious users!
1282 if (!SendError(con
, HTTP_FORBIDDEN
))
1283 return (CloseClient(con
));
1287 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1288 con
->http
.tls
== NULL
)
1292 * Do encryption stuff...
1295 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1296 return (CloseClient(con
));
1298 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1299 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1300 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1301 httpPrintf(HTTP(con
), "\r\n");
1305 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
1306 return (CloseClient(con
));
1307 #endif /* HAVE_SSL */
1310 con
->best
= FindBest(con
->uri
, con
->http
.state
);
1312 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1314 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
1316 SendError(con
, status
);
1317 return (CloseClient(con
));
1320 if (con
->http
.expect
)
1322 /**** TODO: send expected header ****/
1325 switch (con
->http
.state
)
1327 case HTTP_GET_SEND
:
1328 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1329 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1332 * Send PPD file - get the real printer name since printer
1333 * names are not case sensitive but filenames can be...
1336 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1338 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1339 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1342 if (!SendError(con
, HTTP_NOT_FOUND
))
1343 return (CloseClient(con
));
1349 if ((!strncmp(con
->uri
, "/admin", 6) &&
1350 strncmp(con
->uri
, "/admin/conf/", 12) &&
1351 strncmp(con
->uri
, "/admin/log/", 11)) ||
1352 !strncmp(con
->uri
, "/printers", 9) ||
1353 !strncmp(con
->uri
, "/classes", 8) ||
1354 !strncmp(con
->uri
, "/help", 5) ||
1355 !strncmp(con
->uri
, "/jobs", 5))
1358 * Send CGI output...
1361 if (!strncmp(con
->uri
, "/admin", 6))
1363 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1365 if ((ptr
= strchr(con
->uri
+ 6, '?')) != NULL
)
1366 SetStringf(&con
->options
, "admin%s", ptr
);
1368 SetString(&con
->options
, "admin");
1370 else if (!strncmp(con
->uri
, "/printers", 9))
1372 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1373 SetString(&con
->options
, con
->uri
+ 9);
1375 else if (!strncmp(con
->uri
, "/classes", 8))
1377 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1378 SetString(&con
->options
, con
->uri
+ 8);
1380 else if (!strncmp(con
->uri
, "/jobs", 5))
1382 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1383 SetString(&con
->options
, con
->uri
+ 5);
1387 SetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1388 SetString(&con
->options
, con
->uri
+ 5);
1391 if (con
->options
[0] == '/')
1392 _cups_strcpy(con
->options
, con
->options
+ 1);
1394 if (!SendCommand(con
, con
->command
, con
->options
, 0))
1396 if (!SendError(con
, HTTP_NOT_FOUND
))
1397 return (CloseClient(con
));
1400 LogRequest(con
, HTTP_OK
);
1402 if (con
->http
.version
<= HTTP_1_0
)
1403 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1405 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1406 (strchr(con
->uri
+ 12, '/') ||
1407 strlen(con
->uri
) == 12)) ||
1408 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1409 (strchr(con
->uri
+ 11, '/') ||
1410 strlen(con
->uri
) == 11)))
1413 * GET can only be done to configuration files under
1417 if (!SendError(con
, HTTP_FORBIDDEN
))
1418 return (CloseClient(con
));
1428 if ((filename
= get_file(con
, &filestats
, buf
,
1429 sizeof(buf
))) == NULL
)
1431 if (!SendError(con
, HTTP_NOT_FOUND
))
1432 return (CloseClient(con
));
1437 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1439 if (IsCGI(con
, filename
, &filestats
, type
))
1442 * Note: con->command and con->options were set by
1446 if (!SendCommand(con
, con
->command
, con
->options
, 0))
1448 if (!SendError(con
, HTTP_NOT_FOUND
))
1449 return (CloseClient(con
));
1452 LogRequest(con
, HTTP_OK
);
1454 if (con
->http
.version
<= HTTP_1_0
)
1455 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1459 if (!check_if_modified(con
, &filestats
))
1461 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1462 return (CloseClient(con
));
1467 strcpy(line
, "text/plain");
1469 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1471 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1472 return (CloseClient(con
));
1477 case HTTP_POST_RECV
:
1479 * See if the POST request includes a Content-Length field, and if
1480 * so check the length against any limits that are set...
1483 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1484 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1486 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1487 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1491 * Request too large...
1494 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1495 return (CloseClient(con
));
1499 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1502 * Negative content lengths are invalid!
1505 if (!SendError(con
, HTTP_BAD_REQUEST
))
1506 return (CloseClient(con
));
1512 * See what kind of POST request this is; for IPP requests the
1513 * content-type field will be "application/ipp"...
1516 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1517 con
->request
= ippNew();
1518 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1519 strncmp(con
->uri
, "/admin/conf/", 12) &&
1520 strncmp(con
->uri
, "/admin/log/", 11)) ||
1521 !strncmp(con
->uri
, "/printers", 9) ||
1522 !strncmp(con
->uri
, "/classes", 8) ||
1523 !strncmp(con
->uri
, "/help", 5) ||
1524 !strncmp(con
->uri
, "/jobs", 5))
1530 if (!strncmp(con
->uri
, "/admin", 6))
1532 SetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1534 if ((ptr
= strchr(con
->uri
+ 6, '?')) != NULL
)
1535 SetStringf(&con
->options
, "admin%s", ptr
);
1537 SetString(&con
->options
, "admin");
1539 else if (!strncmp(con
->uri
, "/printers", 9))
1541 SetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1542 SetString(&con
->options
, con
->uri
+ 9);
1544 else if (!strncmp(con
->uri
, "/classes", 8))
1546 SetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1547 SetString(&con
->options
, con
->uri
+ 8);
1549 else if (!strncmp(con
->uri
, "/jobs", 5))
1551 SetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1552 SetString(&con
->options
, con
->uri
+ 5);
1556 SetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1557 SetString(&con
->options
, con
->uri
+ 5);
1560 if (con
->options
[0] == '/')
1561 _cups_strcpy(con
->options
, con
->options
+ 1);
1563 LogMessage(L_DEBUG2
, "ReadClient: %d command=\"%s\", options = \"%s\"",
1564 con
->http
.fd
, con
->command
, con
->options
);
1566 if (con
->http
.version
<= HTTP_1_0
)
1567 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1575 if ((filename
= get_file(con
, &filestats
, buf
,
1576 sizeof(buf
))) == NULL
)
1578 if (!SendError(con
, HTTP_NOT_FOUND
))
1579 return (CloseClient(con
));
1584 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1586 if (!IsCGI(con
, filename
, &filestats
, type
))
1589 * Only POST to CGI's...
1592 if (!SendError(con
, HTTP_UNAUTHORIZED
))
1593 return (CloseClient(con
));
1598 case HTTP_PUT_RECV
:
1600 * Validate the resource name...
1603 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1604 strchr(con
->uri
+ 12, '/') ||
1605 strlen(con
->uri
) == 12)
1608 * PUT can only be done to configuration files under
1612 if (!SendError(con
, HTTP_FORBIDDEN
))
1613 return (CloseClient(con
));
1619 * See if the PUT request includes a Content-Length field, and if
1620 * so check the length against any limits that are set...
1623 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1624 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1626 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1627 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1631 * Request too large...
1634 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1635 return (CloseClient(con
));
1639 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1642 * Negative content lengths are invalid!
1645 if (!SendError(con
, HTTP_BAD_REQUEST
))
1646 return (CloseClient(con
));
1652 * Open a temporary file to hold the request...
1655 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1656 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1658 LogMessage(L_DEBUG2
, "ReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1659 con
->filename
, con
->file
);
1663 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1664 return (CloseClient(con
));
1667 fchmod(con
->file
, 0640);
1668 fchown(con
->file
, RunUser
, Group
);
1669 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1674 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1675 return (CloseClient(con
));
1678 if (!strncmp(con
->uri
, "/printers/", 10) &&
1679 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1682 * Send PPD file - get the real printer name since printer
1683 * names are not case sensitive but filenames can be...
1686 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1688 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1689 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1692 if (!SendError(con
, HTTP_NOT_FOUND
))
1693 return (CloseClient(con
));
1699 if ((!strncmp(con
->uri
, "/admin", 6) &&
1700 strncmp(con
->uri
, "/admin/conf/", 12) &&
1701 strncmp(con
->uri
, "/admin/log/", 11)) ||
1702 !strncmp(con
->uri
, "/printers", 9) ||
1703 !strncmp(con
->uri
, "/classes", 8) ||
1704 !strncmp(con
->uri
, "/help", 5) ||
1705 !strncmp(con
->uri
, "/jobs", 5))
1711 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1712 return (CloseClient(con
));
1714 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1715 return (CloseClient(con
));
1717 LogRequest(con
, HTTP_OK
);
1719 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1720 (strchr(con
->uri
+ 12, '/') ||
1721 strlen(con
->uri
) == 12)) ||
1722 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1723 (strchr(con
->uri
+ 11, '/') ||
1724 strlen(con
->uri
) == 11)))
1727 * HEAD can only be done to configuration files under
1731 if (!SendError(con
, HTTP_FORBIDDEN
))
1732 return (CloseClient(con
));
1736 else if ((filename
= get_file(con
, &filestats
, buf
,
1737 sizeof(buf
))) == NULL
)
1739 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1740 return (CloseClient(con
));
1742 LogRequest(con
, HTTP_NOT_FOUND
);
1744 else if (!check_if_modified(con
, &filestats
))
1746 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1747 return (CloseClient(con
));
1749 LogRequest(con
, HTTP_NOT_MODIFIED
);
1757 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1759 strcpy(line
, "text/plain");
1761 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1763 if (!SendHeader(con
, HTTP_OK
, line
))
1764 return (CloseClient(con
));
1766 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1767 httpGetDateString(filestats
.st_mtime
)) < 0)
1768 return (CloseClient(con
));
1770 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1771 (unsigned long)filestats
.st_size
) < 0)
1772 return (CloseClient(con
));
1774 LogRequest(con
, HTTP_OK
);
1777 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1778 return (CloseClient(con
));
1780 con
->http
.state
= HTTP_WAITING
;
1784 break; /* Anti-compiler-warning-code */
1790 * Handle any incoming data...
1793 switch (con
->http
.state
)
1795 case HTTP_PUT_RECV
:
1796 LogMessage(L_DEBUG2
, "ReadClient: %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1798 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1799 con
->http
.data_remaining
, con
->file
);
1801 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1802 return (CloseClient(con
));
1805 con
->bytes
+= bytes
;
1807 LogMessage(L_DEBUG2
, "ReadClient: %d writing %d bytes to %d",
1808 con
->http
.fd
, bytes
, con
->file
);
1810 if (write(con
->file
, line
, bytes
) < bytes
)
1812 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1813 bytes
, con
->filename
, strerror(errno
));
1815 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1820 unlink(con
->filename
);
1821 ClearString(&con
->filename
);
1823 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1824 return (CloseClient(con
));
1828 if (con
->http
.state
== HTTP_WAITING
)
1831 * End of file, see how big it is...
1834 fstat(con
->file
, &filestats
);
1836 LogMessage(L_DEBUG2
, "ReadClient: %d Closing data file %d, size = %d.",
1837 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1842 if (filestats
.st_size
> MaxRequestSize
&&
1846 * Request is too big; remove it and send an error...
1849 LogMessage(L_DEBUG2
, "ReadClient: %d Removing temp file %s",
1850 con
->http
.fd
, con
->filename
);
1851 unlink(con
->filename
);
1852 ClearString(&con
->filename
);
1854 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1855 return (CloseClient(con
));
1859 * Install the configuration file...
1862 status
= install_conf_file(con
);
1865 * Return the status to the client...
1868 if (!SendError(con
, status
))
1869 return (CloseClient(con
));
1873 case HTTP_POST_RECV
:
1874 LogMessage(L_DEBUG2
, "ReadClient: %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1876 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1877 con
->http
.data_remaining
, con
->file
);
1879 if (con
->request
!= NULL
)
1882 * Grab any request data from the connection...
1885 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1887 LogMessage(L_ERROR
, "ReadClient: %d IPP Read Error!",
1890 SendError(con
, HTTP_BAD_REQUEST
);
1891 return (CloseClient(con
));
1893 else if (ipp_state
!= IPP_DATA
)
1895 if (con
->http
.state
== HTTP_POST_SEND
)
1897 SendError(con
, HTTP_BAD_REQUEST
);
1898 return (CloseClient(con
));
1904 con
->bytes
+= ippLength(con
->request
);
1907 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1910 * Create a file as needed for the request data...
1913 SetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1914 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1916 LogMessage(L_DEBUG2
, "ReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1917 con
->filename
, con
->file
);
1921 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1922 return (CloseClient(con
));
1925 fchmod(con
->file
, 0640);
1926 fchown(con
->file
, RunUser
, Group
);
1927 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1930 if (con
->http
.state
!= HTTP_POST_SEND
)
1932 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1933 return (CloseClient(con
));
1936 con
->bytes
+= bytes
;
1938 LogMessage(L_DEBUG2
, "ReadClient: %d writing %d bytes to %d",
1939 con
->http
.fd
, bytes
, con
->file
);
1941 if (write(con
->file
, line
, bytes
) < bytes
)
1943 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1944 bytes
, con
->filename
, strerror(errno
));
1946 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1951 unlink(con
->filename
);
1952 ClearString(&con
->filename
);
1954 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1955 return (CloseClient(con
));
1958 else if (con
->http
.state
== HTTP_POST_RECV
)
1959 return (1); /* ??? */
1960 else if (con
->http
.state
!= HTTP_POST_SEND
)
1961 return (CloseClient(con
));
1964 if (con
->http
.state
== HTTP_POST_SEND
)
1968 fstat(con
->file
, &filestats
);
1970 LogMessage(L_DEBUG2
, "ReadClient: %d Closing data file %d, size = %d.",
1971 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1976 if (filestats
.st_size
> MaxRequestSize
&&
1980 * Request is too big; remove it and send an error...
1983 LogMessage(L_DEBUG2
, "ReadClient: %d Removing temp file %s",
1984 con
->http
.fd
, con
->filename
);
1985 unlink(con
->filename
);
1986 ClearString(&con
->filename
);
1991 * Delete any IPP request data...
1994 ippDelete(con
->request
);
1995 con
->request
= NULL
;
1998 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1999 return (CloseClient(con
));
2004 if (!SendCommand(con
, con
->command
, con
->options
, 0))
2006 if (!SendError(con
, HTTP_NOT_FOUND
))
2007 return (CloseClient(con
));
2010 LogRequest(con
, HTTP_OK
);
2015 return (ProcessIPPRequest(con
));
2020 break; /* Anti-compiler-warning-code */
2023 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2024 return (CloseClient(con
));
2031 * 'SendCommand()' - Send output from a command via HTTP.
2034 int /* O - 1 on success, 0 on failure */
2035 SendCommand(client_t
*con
, /* I - Client connection */
2036 char *command
, /* I - Command to run */
2037 char *options
, /* I - Command-line options */
2038 int root
) /* I - Run as root? */
2040 int fd
; /* Standard input file descriptor */
2044 fd
= open(con
->filename
, O_RDONLY
);
2046 fd
= open("/dev/null", O_RDONLY
);
2050 LogMessage(L_ERROR
, "SendCommand: %d Unable to open \"%s\" for reading: %s",
2051 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2056 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2058 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2062 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
2064 LogMessage(L_DEBUG
, "SendCommand: %d file=%d", con
->http
.fd
, con
->file
);
2066 if (con
->pipe_pid
== 0)
2069 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2071 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
2072 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
2075 FD_SET(con
->file
, InputSet
);
2076 FD_SET(con
->http
.fd
, OutputSet
);
2078 con
->sent_header
= 0;
2079 con
->file_ready
= 0;
2080 con
->got_fields
= 0;
2088 * 'SendError()' - Send an error message via HTTP.
2091 int /* O - 1 if successful, 0 otherwise */
2092 SendError(client_t
*con
, /* I - Connection */
2093 http_status_t code
) /* I - Error code */
2095 char message
[1024]; /* Message for user */
2099 * Put the request in the access_log file...
2102 LogRequest(con
, code
);
2104 LogMessage(L_DEBUG
, "SendError: %d code=%d (%s)", con
->http
.fd
, code
,
2108 * To work around bugs in some proxies, don't use Keep-Alive for some
2112 if (code
>= HTTP_BAD_REQUEST
)
2113 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2116 * Send an error message back to the client. If the error code is a
2117 * 400 or 500 series, make sure the message contains some text, too!
2120 if (!SendHeader(con
, code
, NULL
))
2124 if (code
== HTTP_UPGRADE_REQUIRED
)
2125 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2128 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2130 #endif /* HAVE_SSL */
2132 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2133 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2135 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2139 if (code
>= HTTP_BAD_REQUEST
)
2142 * Send a human-readable error message.
2145 snprintf(message
, sizeof(message
),
2146 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
2147 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
2148 code
, httpStatus(code
), httpStatus(code
),
2149 con
->language
? con
->language
->messages
[code
] :
2152 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2154 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2155 (int)strlen(message
)) < 0)
2157 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2159 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2162 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2165 con
->http
.state
= HTTP_WAITING
;
2172 * 'SendFile()' - Send a file via HTTP.
2176 SendFile(client_t
*con
,
2180 struct stat
*filestats
)
2182 con
->file
= open(filename
, O_RDONLY
);
2184 LogMessage(L_DEBUG
, "SendFile: %d file=%d", con
->http
.fd
, con
->file
);
2189 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2193 if (!SendHeader(con
, code
, type
))
2196 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
2198 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2199 (unsigned long)filestats
->st_size
) < 0)
2201 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2204 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2206 FD_SET(con
->http
.fd
, OutputSet
);
2213 * 'SendHeader()' - Send an HTTP request.
2216 int /* O - 1 on success, 0 on failure */
2217 SendHeader(client_t
*con
, /* I - Client to send to */
2218 http_status_t code
, /* I - HTTP status code */
2219 char *type
) /* I - MIME type of document */
2221 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2222 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2224 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2227 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2229 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2231 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2233 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
2236 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2237 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2240 if (code
== HTTP_UNAUTHORIZED
)
2242 int auth_type
; /* Authentication type */
2245 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2246 auth_type
= DefaultAuthType
;
2248 auth_type
= con
->best
->type
;
2250 if (auth_type
!= AUTH_DIGEST
)
2252 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2257 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\", "
2258 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
2263 if (con
->language
!= NULL
)
2265 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2266 con
->language
->language
) < 0)
2272 if (!strcmp(type
, "text/html"))
2274 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2277 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2286 * 'UpdateCGI()' - Read status messages from CGI scripts and programs.
2292 char *ptr
, /* Pointer to end of line in buffer */
2293 message
[1024]; /* Pointer to message text */
2294 int loglevel
; /* Log level for message */
2297 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2298 message
, sizeof(message
))) != NULL
)
2299 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2305 * Fatal error on pipe - should never happen!
2308 LogMessage(L_CRIT
, "UpdateCGI: error reading from CGI error pipe - %s",
2315 * 'WriteClient()' - Write data to a client as needed.
2318 int /* O - 1 if success, 0 if fail */
2319 WriteClient(client_t
*con
) /* I - Client connection */
2321 int bytes
; /* Number of bytes written */
2322 char buf
[16385]; /* Data buffer */
2323 char *bufptr
; /* Pointer into buffer */
2324 ipp_state_t ipp_state
; /* IPP state value */
2328 LogMessage(L_DEBUG2
, "WriteClient(con=%p) %d response=%p, file=%d pipe_pid=%d",
2329 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
);
2332 if (con
->http
.state
!= HTTP_GET_SEND
&&
2333 con
->http
.state
!= HTTP_POST_SEND
)
2336 if (con
->response
!= NULL
)
2338 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2339 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2341 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2344 LogMessage(L_DEBUG2
, "WriteClient: Read %d bytes from file %d...",
2348 if (con
->pipe_pid
&& !con
->got_fields
)
2351 * Inspect the data for Content-Type and other fields.
2356 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2357 if (*bufptr
== '\n')
2360 * Send line to client...
2363 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2367 LogMessage(L_DEBUG2
, "Script header: %s", buf
);
2369 if (!con
->sent_header
)
2372 * Handle redirection and CGI status codes...
2375 if (!strncasecmp(buf
, "Location:", 9))
2376 SendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2377 else if (!strncasecmp(buf
, "Status:", 7))
2378 SendHeader(con
, atoi(buf
+ 7), NULL
);
2380 SendHeader(con
, HTTP_OK
, NULL
);
2382 if (con
->http
.version
== HTTP_1_1
)
2384 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2386 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2390 con
->sent_header
= 1;
2393 if (strncasecmp(buf
, "Status:", 7))
2394 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2396 LogMessage(L_DEBUG2
, "WriteClient: %d %s", con
->http
.fd
, buf
);
2402 bytes
-= (bufptr
- buf
);
2403 memmove(buf
, bufptr
, bytes
+ 1);
2407 * See if the line was empty...
2410 if (con
->field_col
== 0)
2411 con
->got_fields
= 1;
2415 else if (*bufptr
!= '\r')
2418 if (bytes
> 0 && !con
->got_fields
)
2421 * Remaining text needs to go out...
2424 httpPrintf(HTTP(con
), "%s", buf
);
2426 con
->http
.activity
= time(NULL
);
2429 else if (bytes
== 0)
2431 con
->http
.activity
= time(NULL
);
2436 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2442 con
->bytes
+= bytes
;
2447 LogRequest(con
, HTTP_OK
);
2449 httpFlushWrite(HTTP(con
));
2451 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2453 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2460 con
->http
.state
= HTTP_WAITING
;
2462 LogMessage(L_DEBUG2
, "WriteClient: Removing fd %d from OutputSet...",
2465 FD_CLR(con
->http
.fd
, OutputSet
);
2469 if (FD_ISSET(con
->file
, InputSet
))
2471 LogMessage(L_DEBUG2
, "WriteClient: Removing fd %d from InputSet...",
2473 FD_CLR(con
->file
, InputSet
);
2477 cupsdEndProcess(con
->pipe_pid
, 0);
2479 LogMessage(L_DEBUG2
, "WriteClient: %d Closing data file %d.",
2480 con
->http
.fd
, con
->file
);
2489 LogMessage(L_DEBUG2
, "WriteClient: %d Removing temp file %s",
2490 con
->http
.fd
, con
->filename
);
2491 unlink(con
->filename
);
2492 ClearString(&con
->filename
);
2495 if (con
->request
!= NULL
)
2497 ippDelete(con
->request
);
2498 con
->request
= NULL
;
2501 if (con
->response
!= NULL
)
2503 ippDelete(con
->response
);
2504 con
->response
= NULL
;
2507 ClearString(&con
->command
);
2508 ClearString(&con
->options
);
2510 if (!con
->http
.keep_alive
)
2518 con
->file_ready
= 0;
2520 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2522 LogMessage(L_DEBUG2
, "WriteClient: Adding fd %d to InputSet...", con
->file
);
2523 FD_SET(con
->file
, InputSet
);
2527 con
->http
.activity
= time(NULL
);
2534 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2537 static int /* O - 1 if modified since */
2538 check_if_modified(client_t
*con
, /* I - Client connection */
2539 struct stat
*filestats
) /* I - File information */
2541 char *ptr
; /* Pointer into field */
2542 time_t date
; /* Time/date value */
2543 int size
; /* Size/length value */
2548 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2553 LogMessage(L_DEBUG2
, "check_if_modified: %d If-Modified-Since=\"%s\"",
2556 while (*ptr
!= '\0')
2558 while (isspace(*ptr
) || *ptr
== ';')
2561 if (strncasecmp(ptr
, "length=", 7) == 0)
2566 while (isdigit(*ptr
))
2569 else if (isalpha(*ptr
))
2571 date
= httpGetDateTime(ptr
);
2572 while (*ptr
!= '\0' && *ptr
!= ';')
2577 LogMessage(L_DEBUG2
, "check_if_modified: %d sizes=%d,%d dates=%d,%d",
2578 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2579 (int)filestats
->st_mtime
);
2581 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2582 (date
< filestats
->st_mtime
&& date
!= 0) ||
2583 (size
== 0 && date
== 0));
2588 * 'decode_auth()' - Decode an authorization string.
2592 decode_auth(client_t
*con
) /* I - Client to decode to */
2594 char *s
, /* Authorization string */
2595 value
[1024]; /* Value string */
2596 const char *username
; /* Certificate username */
2600 * Decode the string...
2603 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2605 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2608 if (strncmp(s
, "Basic", 5) == 0)
2614 httpDecode64(value
, s
);
2617 * Pull the username and password out...
2620 if ((s
= strchr(value
, ':')) == NULL
)
2622 LogMessage(L_DEBUG
, "decode_auth: %d no colon in auth string \"%s\"",
2623 con
->http
.fd
, value
);
2629 strlcpy(con
->username
, value
, sizeof(con
->username
));
2630 strlcpy(con
->password
, s
, sizeof(con
->password
));
2632 else if (strncmp(s
, "Local", 5) == 0)
2638 if ((username
= FindCert(s
)) != NULL
)
2639 strlcpy(con
->username
, username
, sizeof(con
->username
));
2641 else if (strncmp(s
, "Digest", 5) == 0)
2644 * Get the username and password from the Digest attributes...
2647 if (httpGetSubField(&(con
->http
), HTTP_FIELD_AUTHORIZATION
, "username",
2649 strlcpy(con
->username
, value
, sizeof(con
->username
));
2651 if (httpGetSubField(&(con
->http
), HTTP_FIELD_AUTHORIZATION
, "response",
2653 strlcpy(con
->password
, value
, sizeof(con
->password
));
2656 LogMessage(L_DEBUG2
, "decode_auth: %d username=\"%s\"",
2657 con
->http
.fd
, con
->username
);
2662 * 'get_file()' - Get a filename and state info.
2665 static char * /* O - Real filename */
2666 get_file(client_t
*con
, /* I - Client connection */
2667 struct stat
*filestats
, /* O - File information */
2668 char *filename
, /* IO - Filename buffer */
2669 int len
) /* I - Buffer length */
2671 int status
; /* Status of filesystem calls */
2672 char *ptr
; /* Pointer info filename */
2673 int plen
; /* Remaining length after pointer */
2677 * Need to add DocumentRoot global...
2680 if (!strncmp(con
->uri
, "/ppd/", 5))
2681 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2682 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2683 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2684 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2686 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2687 strlcpy(filename
, AccessLog
, len
);
2688 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2689 strlcpy(filename
, ErrorLog
, len
);
2690 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2691 strlcpy(filename
, PageLog
, len
);
2695 else if (con
->language
!= NULL
)
2696 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2699 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2701 if ((ptr
= strchr(filename
, '?')) != NULL
)
2705 * Grab the status for this language; if there isn't a language-specific file
2706 * then fallback to the default one...
2709 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2712 * Drop the language prefix and try the current directory...
2715 if (strncmp(con
->uri
, "/ppd/", 5) &&
2716 strncmp(con
->uri
, "/admin/conf/", 12) &&
2717 strncmp(con
->uri
, "/admin/log/", 11))
2719 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2721 if ((ptr
= strchr(filename
, '?')) != NULL
)
2724 status
= stat(filename
, filestats
);
2729 * If we're found a directory, get the index.html file instead...
2732 if (!status
&& S_ISDIR(filestats
->st_mode
))
2734 if (filename
[strlen(filename
) - 1] != '/')
2735 strlcat(filename
, "/", len
);
2737 ptr
= filename
+ strlen(filename
);
2738 plen
= len
- (ptr
- filename
);
2740 strlcpy(ptr
, "index.html", plen
);
2741 status
= stat(filename
, filestats
);
2746 strlcpy(ptr
, "index.class", plen
);
2747 status
= stat(filename
, filestats
);
2749 #endif /* HAVE_JAVA */
2754 strlcpy(ptr
, "index.pl", plen
);
2755 status
= stat(filename
, filestats
);
2757 #endif /* HAVE_PERL */
2762 strlcpy(ptr
, "index.php", plen
);
2763 status
= stat(filename
, filestats
);
2765 #endif /* HAVE_PHP */
2770 strlcpy(ptr
, "index.pyc", plen
);
2771 status
= stat(filename
, filestats
);
2776 strlcpy(ptr
, "index.py", plen
);
2777 status
= stat(filename
, filestats
);
2779 #endif /* HAVE_PYTHON */
2782 LogMessage(L_DEBUG2
, "get_file: %d filename=%s size=%d",
2783 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2786 con
->http
.data_remaining
= (int)filestats
->st_size
;
2796 * 'install_conf_file()' - Install a configuration file.
2799 static http_status_t
/* O - Status */
2800 install_conf_file(client_t
*con
) /* I - Connection */
2802 cups_file_t
*in
, /* Input file */
2803 *out
; /* Output file */
2804 char buffer
[1024]; /* Copy buffer */
2805 int bytes
; /* Number of bytes */
2806 char conffile
[1024], /* Configuration filename */
2807 newfile
[1024], /* New config filename */
2808 oldfile
[1024]; /* Old config filename */
2809 struct stat confinfo
; /* Config file info */
2813 * First construct the filenames...
2816 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2817 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2818 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2820 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2823 * Get the owner, group, and permissions of the configuration file.
2824 * If it doesn't exist, assign it to the User and Group in the
2825 * cupsd.conf file with mode 0640 permissions.
2828 if (stat(conffile
, &confinfo
))
2830 confinfo
.st_uid
= User
;
2831 confinfo
.st_gid
= Group
;
2832 confinfo
.st_mode
= ConfigFilePerm
;
2836 * Open the request file and new config file...
2839 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2841 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2842 con
->filename
, strerror(errno
));
2843 return (HTTP_SERVER_ERROR
);
2846 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2849 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2850 newfile
, strerror(errno
));
2851 return (HTTP_SERVER_ERROR
);
2854 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2855 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2858 * Copy from the request to the new config file...
2861 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2862 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2864 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2865 newfile
, strerror(errno
));
2871 return (HTTP_SERVER_ERROR
);
2875 * Close the files...
2879 if (cupsFileClose(out
))
2881 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2882 newfile
, strerror(errno
));
2886 return (HTTP_SERVER_ERROR
);
2890 * Remove the request file...
2893 unlink(con
->filename
);
2894 ClearString(&con
->filename
);
2897 * Unlink the old backup, rename the current config file to the backup
2898 * filename, and rename the new config file to the config file name...
2901 if (unlink(oldfile
))
2902 if (errno
!= ENOENT
)
2904 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2905 oldfile
, strerror(errno
));
2909 return (HTTP_SERVER_ERROR
);
2912 if (rename(conffile
, oldfile
))
2913 if (errno
!= ENOENT
)
2915 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2916 conffile
, strerror(errno
));
2920 return (HTTP_SERVER_ERROR
);
2923 if (rename(newfile
, conffile
))
2925 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2926 newfile
, strerror(errno
));
2928 rename(oldfile
, conffile
);
2931 return (HTTP_SERVER_ERROR
);
2935 * If the cupsd.conf file was updated, set the NeedReload flag...
2938 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2939 NeedReload
= RELOAD_CUPSD
;
2941 NeedReload
= RELOAD_ALL
;
2943 ReloadTime
= time(NULL
);
2946 * Return that the file was created successfully...
2949 return (HTTP_CREATED
);
2954 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
2957 static int /* O - 0 if relative, 1 if absolute */
2958 is_path_absolute(const char *path
) /* I - Input path */
2961 * Check for a leading slash...
2968 * Check for "/.." in the path...
2971 while ((path
= strstr(path
, "/..")) != NULL
)
2973 if (!path
[3] || path
[3] == '/')
2980 * If we haven't found any relative paths, return 1 indicating an
2989 * 'pipe_command()' - Pipe the output of a command to the remote client.
2992 static int /* O - Process ID */
2993 pipe_command(client_t
*con
, /* I - Client connection */
2994 int infile
, /* I - Standard input for command */
2995 int *outfile
, /* O - Standard output for command */
2996 char *command
, /* I - Command to run */
2997 char *options
, /* I - Options for command */
2998 int root
) /* I - Run as root? */
3000 int i
; /* Looping var */
3001 int pid
; /* Process ID */
3002 char *commptr
; /* Command string pointer */
3003 char *uriptr
; /* URI string pointer */
3004 int fds
[2]; /* Pipe FDs */
3005 int argc
; /* Number of arguments */
3006 int envc
; /* Number of environment variables */
3007 char argbuf
[10240], /* Argument buffer */
3008 *argv
[100], /* Argument strings */
3009 *envp
[100]; /* Environment variables */
3010 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3011 content_type
[1024], /* CONTENT_TYPE environment variable */
3012 http_cookie
[1024], /* HTTP_COOKIE environment variable */
3013 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3014 lang
[1024], /* LANG environment variable */
3015 *query_string
, /* QUERY_STRING env variable */
3016 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3017 remote_host
[1024], /* REMOTE_HOST environment variable */
3018 remote_user
[1024], /* REMOTE_USER environment variable */
3019 script_name
[1024], /* SCRIPT_NAME environment variable */
3020 server_name
[1024], /* SERVER_NAME environment variable */
3021 server_port
[1024]; /* SERVER_PORT environment variable */
3022 static const char * const locale_encodings
[] =
3023 { /* Locale charset names */
3024 "ASCII", "ISO8859-1", "ISO8859-2", "ISO8859-3",
3025 "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7",
3026 "ISO8859-8", "ISO8859-9", "ISO8859-10", "UTF-8",
3027 "ISO8859-13", "ISO8859-14", "ISO8859-15", "CP874",
3028 "CP1250", "CP1251", "CP1252", "CP1253",
3029 "CP1254", "CP1255", "CP1256", "CP1257",
3030 "CP1258", "KOI8R", "KOI8U", "ISO8859-11",
3031 "ISO8859-16", "", "", "",
3042 "CP932", "CP936", "CP949", "CP950",
3043 "CP1361", "", "", "",
3060 "EUC-CN", "EUC-JP", "EUC-KR", "EUC-TW"
3065 * Parse a copy of the options string, which is of the form:
3067 * name argument+argument+argument
3068 * name?argument+argument+argument
3069 * name param=value¶m=value
3070 * name?param=value¶m=value
3072 * If the string contains an "=" character after the initial name,
3073 * then we treat it as a HTTP GET form request and make a copy of
3074 * the remaining string for the environment variable.
3076 * The string is always parsed out as command-line arguments, to
3077 * be consistent with Apache...
3080 LogMessage(L_DEBUG2
, "pipe_command: command=\"%s\", options=\"%s\"",
3083 strlcpy(argbuf
, options
, sizeof(argbuf
));
3086 query_string
= NULL
;
3088 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
3091 * Break arguments whenever we see a + or space...
3094 if (*commptr
== ' ' || *commptr
== '+' || (*commptr
== '?' && argc
== 1))
3097 * Terminate the current string and skip trailing whitespace...
3102 while (*commptr
== ' ')
3106 * If we don't have a blank string, save it as another argument...
3111 argv
[argc
] = commptr
;
3118 * If we see an "=" in the remaining string, make a copy of it since
3119 * it will be query data...
3122 if (argc
== 2 && strchr(commptr
, '=') && con
->operation
== HTTP_GET
)
3123 SetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3126 * Don't skip the first non-blank character...
3131 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3132 isxdigit(commptr
[2] & 255))
3135 * Convert the %xx notation to the individual character.
3138 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3139 *commptr
= (commptr
[1] - '0') << 4;
3141 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3143 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3144 *commptr
|= commptr
[2] - '0';
3146 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3148 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3151 * Check for a %00 and break if that is the case...
3161 if (argv
[0][0] == '\0')
3162 argv
[0] = strrchr(command
, '/') + 1;
3165 * Setup the environment variables as needed...
3169 snprintf(lang
, sizeof(lang
), "LANG=%s.%s", con
->language
->language
,
3170 locale_encodings
[con
->language
->encoding
]);
3172 strcpy(lang
, "LANG=C");
3174 strcpy(remote_addr
, "REMOTE_ADDR=");
3175 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3176 sizeof(remote_addr
) - 12);
3178 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3179 con
->http
.hostname
);
3181 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3182 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3185 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3187 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3190 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3192 envp
[envc
++] = lang
;
3193 envp
[envc
++] = "REDIRECT_STATUS=1";
3194 envp
[envc
++] = server_name
;
3195 envp
[envc
++] = server_port
;
3196 envp
[envc
++] = remote_addr
;
3197 envp
[envc
++] = remote_host
;
3198 envp
[envc
++] = script_name
;
3200 if (con
->username
[0])
3202 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3204 envp
[envc
++] = remote_user
;
3207 if (con
->http
.version
== HTTP_1_1
)
3208 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3209 else if (con
->http
.version
== HTTP_1_0
)
3210 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3212 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3214 if (con
->http
.cookie
)
3216 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3218 envp
[envc
++] = http_cookie
;
3221 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3223 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3224 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3225 envp
[envc
++] = http_user_agent
;
3228 if (con
->operation
== HTTP_GET
)
3230 for (i
= 0; i
< argc
; i
++)
3231 LogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3233 envp
[envc
++] = "REQUEST_METHOD=GET";
3238 * Add GET form variables after ?...
3241 envp
[envc
++] = query_string
;
3246 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3247 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3248 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3250 envp
[envc
++] = "REQUEST_METHOD=POST";
3251 envp
[envc
++] = content_length
;
3252 envp
[envc
++] = content_type
;
3256 * Tell the CGI if we are using encryption...
3259 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3260 envp
[envc
++] = "HTTPS=ON";
3263 * Terminate the environment array...
3268 if (LogLevel
== L_DEBUG2
)
3270 for (i
= 0; i
< argc
; i
++)
3271 LogMessage(L_DEBUG2
, "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
3272 for (i
= 0; i
< envc
; i
++)
3273 LogMessage(L_DEBUG2
, "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
3277 * Create a pipe for the output...
3280 if (cupsdOpenPipe(fds
))
3282 ClearString(&query_string
);
3284 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3285 argv
[0], strerror(errno
));
3290 * Then execute the command...
3293 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3294 -1, root
, &pid
) < 0)
3297 * Error - can't fork!
3300 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3303 cupsdClosePipe(fds
);
3309 * Fork successful - return the PID...
3312 if (con
->username
[0])
3313 AddCert(pid
, con
->username
);
3315 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3321 ClearString(&query_string
);
3327 #if defined(HAVE_CDSASSL)
3329 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3332 static OSStatus
/* O - -1 on error, 0 on success */
3333 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3334 void *data
, /* I - Data buffer */
3335 size_t *dataLength
) /* IO - Number of bytes */
3337 ssize_t bytes
; /* Number of bytes read */
3340 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3343 *dataLength
= bytes
;
3352 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3355 static OSStatus
/* O - -1 on error, 0 on success */
3356 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3357 const void *data
, /* I - Data buffer */
3358 size_t *dataLength
) /* IO - Number of bytes */
3363 bytes
= write((int)connection
, data
, *dataLength
);
3366 *dataLength
= bytes
;
3372 #endif /* HAVE_CDSASSL */