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 * cupsdAcceptClient() - Accept a new client.
27 * cupsdCloseAllClients() - Close all remote clients immediately.
28 * cupsdCloseClient() - Close a remote client.
29 * cupsdEncryptClient() - Enable encryption for the client...
30 * cupsdIsCGI() - Is the resource a CGI script/program?
31 * cupsdReadClient() - Read data from a client.
32 * cupsdSendCommand() - Send output from a command via HTTP.
33 * cupsdSendError() - Send an error message via HTTP.
34 * cupsdSendFile() - Send a file via HTTP.
35 * cupsdSendHeader() - Send an HTTP request.
36 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
37 * cupsdWriteClient() - 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(cupsd_client_t
*con
,
61 struct stat
*filestats
);
62 static void decode_auth(cupsd_client_t
*con
);
63 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
64 char *filename
, int len
);
65 static http_status_t
install_conf_file(cupsd_client_t
*con
);
66 static int is_path_absolute(const char *path
);
67 static int pipe_command(cupsd_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 * 'cupsdAcceptClient()' - Accept a new client.
83 cupsdAcceptClient(cupsd_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 cupsd_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 cupsdLogMessage(L_DEBUG2
, "cupsdAcceptClient(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(cupsd_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 cupsdLogMessage(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 cupsdLogMessage(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 cupsdLogMessage(L_DEBUG2
, "cupsdAcceptClient: Closing connection %d...",
209 closesocket(con
->http
.fd
);
214 cupsdLogMessage(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 cupsdLogMessage(L_DEBUG2
, "cupsdAcceptClient: Closing connection %d...",
269 closesocket(con
->http
.fd
);
274 cupsdLogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
281 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
282 cupsdLogMessage(L_DEBUG
, "cupsdAcceptClient: %d from %s:%d.", con
->http
.fd
,
283 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
285 #endif /* AF_INET6 */
286 cupsdLogMessage(L_DEBUG
, "cupsdAcceptClient: %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 cupsdLogMessage(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 cupsdLogMessage(L_DEBUG2
, "cupsdAcceptClient: %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 cupsdLogMessage(L_DEBUG2
, "cupsdAcceptClient: 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
)
356 cupsdPauseListening();
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
;
371 cupsdEncryptClient(con
);
375 #endif /* HAVE_SSL */
380 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
384 cupsdCloseAllClients(void)
386 while (NumClients
> 0)
387 cupsdCloseClient(Clients
);
392 * 'cupsdCloseClient()' - Close a remote client.
395 int /* O - 1 if partial close, 0 if fully closed */
396 cupsdCloseClient(cupsd_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 cupsdLogMessage(L_DEBUG
, "cupsdCloseClient: %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 cupsdLogMessage(L_INFO
, "cupsdCloseClient: SSL shutdown successful!");
442 cupsdLogMessage(L_ERROR
, "cupsdCloseClient: Fatal error during SSL shutdown!");
444 while ((error
= ERR_get_error()) != 0)
445 cupsdLogMessage(L_ERROR
, "cupsdCloseClient: %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 cupsdLogMessage(L_INFO
, "cupsdCloseClient: SSL shutdown successful!");
463 cupsdLogMessage(L_ERROR
, "cupsdCloseClient: %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 */
481 if (con
->pipe_pid
!= 0)
484 * Stop any CGI process...
487 cupsdLogMessage(L_DEBUG2
, "cupsdCloseClient: %d Killing process ID %d...",
488 con
->http
.fd
, con
->pipe_pid
);
489 cupsdEndProcess(con
->pipe_pid
, 1);
494 if (FD_ISSET(con
->file
, InputSet
))
496 cupsdLogMessage(L_DEBUG2
, "cupsdCloseClient: %d Removing fd %d from InputSet...",
497 con
->http
.fd
, con
->file
);
498 FD_CLR(con
->file
, InputSet
);
501 cupsdLogMessage(L_DEBUG2
, "cupsdCloseClient: %d Closing data file %d.",
502 con
->http
.fd
, con
->file
);
509 * Close the socket and clear the file from the input set for select()...
512 if (con
->http
.fd
> 0)
517 * Only do a partial close so that the encrypted client gets everything.
520 cupsdLogMessage(L_DEBUG2
, "cupsdCloseClient: Removing fd %d from OutputSet...",
522 shutdown(con
->http
.fd
, 0);
523 FD_CLR(con
->http
.fd
, OutputSet
);
528 * Shut the socket down fully...
531 cupsdLogMessage(L_DEBUG2
, "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
534 FD_CLR(con
->http
.fd
, InputSet
);
535 FD_CLR(con
->http
.fd
, OutputSet
);
546 if (con
->http
.input_set
)
547 free(con
->http
.input_set
);
549 httpClearCookie(HTTP(con
));
551 cupsdClearString(&con
->filename
);
552 cupsdClearString(&con
->command
);
553 cupsdClearString(&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
)
579 cupsdResumeListening();
582 * Compact the list of clients as necessary...
587 if (con
< (Clients
+ NumClients
))
588 memmove(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(cupsd_client_t
));
596 * 'cupsdEncryptClient()' - Enable encryption for the client...
599 int /* O - 1 on success, 0 on error */
600 cupsdEncryptClient(cupsd_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 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: Unable to encrypt connection from %s!",
626 while ((error
= ERR_get_error()) != 0)
627 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: %s", ERR_error_string(error
, NULL
));
629 SSL_CTX_free(context
);
634 cupsdLogMessage(L_DEBUG
, "cupsdEncryptClient: %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 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: Unable to encrypt connection from %s!",
661 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: %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 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: Unable to encrypt connection from %s!",
682 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: %s", gnutls_strerror(error
));
684 gnutls_deinit(conn
->session
);
685 gnutls_certificate_free_credentials(*credentials
);
691 cupsdLogMessage(L_DEBUG
, "cupsdEncryptClient: %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 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: Unable to encrypt connection from %s!",
755 cupsdLogMessage(L_ERROR
, "cupsdEncryptClient: CDSA error code is %d", error
);
757 con
->http
.error
= error
;
758 con
->http
.status
= HTTP_ERROR
;
761 SSLDisposeContext(conn
);
766 cupsdLogMessage(L_DEBUG
, "cupsdEncryptClient: %d Connection from %s now encrypted.",
767 con
->http
.fd
, con
->http
.hostname
);
769 con
->http
.tls
= conn
;
774 #endif /* HAVE_GNUTLS */
779 * 'cupsdIsCGI()' - Is the resource a CGI script/program?
782 int /* O - 1 = CGI, 0 = file */
783 cupsdIsCGI(cupsd_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 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI(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 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: 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 cupsdSetString(&con
->command
, filename
);
821 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
824 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
826 cupsdSetStringf(&con
->options
, "%s", filename
);
828 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: 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 cupsdSetString(&con
->command
, CUPS_JAVA
);
843 cupsdSetStringf(&con
->options
, "java %s %s", filename
, options
);
845 cupsdSetStringf(&con
->options
, "java %s", filename
);
847 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: 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 cupsdSetString(&con
->command
, CUPS_PERL
);
863 cupsdSetStringf(&con
->options
, "perl %s %s", filename
, options
);
865 cupsdSetStringf(&con
->options
, "perl %s", filename
);
867 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: 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 cupsdSetString(&con
->command
, CUPS_PHP
);
883 cupsdSetStringf(&con
->options
, "php %s %s", filename
, options
);
885 cupsdSetStringf(&con
->options
, "php %s", filename
);
887 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: 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 cupsdSetString(&con
->command
, CUPS_PYTHON
);
903 cupsdSetStringf(&con
->options
, "python %s %s", filename
, options
);
905 cupsdSetStringf(&con
->options
, "python %s", filename
);
907 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
908 con
->command
, con
->options
);
912 #endif /* HAVE_PYTHON */
914 cupsdLogMessage(L_DEBUG2
, "cupsdIsCGI: Returning 0...");
921 * 'cupsdReadClient()' - Read data from a client.
924 int /* O - 1 on success, 0 on error */
925 cupsdReadClient(cupsd_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 cupsd_printer_t
*p
; /* Printer */
941 static unsigned request_id
= 0; /* Request ID for temp files */
944 status
= HTTP_CONTINUE
;
946 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d, used=%d, file=%d", con
->http
.fd
,
947 con
->http
.used
, con
->file
);
951 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: http error seen...");
952 return (cupsdCloseClient(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 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
974 cupsdEncryptClient(con
);
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 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: httpGets returned EOF...");
990 return (cupsdCloseClient(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 cupsdClearString(&con
->command
);
1021 cupsdClearString(&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 cupsdLogMessage(L_ERROR
, "Bad request line \"%s\" from %s!", line
,
1037 con
->http
.hostname
);
1038 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1039 return (cupsdCloseClient(con
));
1041 con
->http
.version
= HTTP_0_9
;
1044 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
1046 cupsdLogMessage(L_ERROR
, "Bad request line \"%s\" from %s!", line
,
1047 con
->http
.hostname
);
1048 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1049 return (cupsdCloseClient(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 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
1063 return (cupsdCloseClient(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 cupsdLogMessage(L_ERROR
, "Bad URI \"%s\" in request!", con
->uri
);
1101 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
1102 return (cupsdCloseClient(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 cupsdLogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
1134 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1135 return (cupsdCloseClient(con
));
1138 con
->start
= time(NULL
);
1139 con
->operation
= con
->http
.state
;
1141 cupsdLogMessage(L_DEBUG
, "cupsdReadClient: %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 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1163 return (cupsdCloseClient(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 (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1226 return (cupsdCloseClient(con
));
1228 else if (con
->operation
== HTTP_OPTIONS
)
1231 * Do OPTIONS command...
1234 if ((con
->best
= cupsdFindBest(con
->uri
, con
->http
.state
)) != NULL
&&
1235 con
->best
->type
!= AUTH_NONE
)
1237 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1238 return (cupsdCloseClient(con
));
1241 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1242 con
->http
.tls
== NULL
)
1246 * Do encryption stuff...
1249 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1250 return (cupsdCloseClient(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");
1257 cupsdEncryptClient(con
);
1259 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1260 return (cupsdCloseClient(con
));
1261 #endif /* HAVE_SSL */
1264 if (con
->http
.expect
)
1266 /**** TODO: send expected header ****/
1269 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1270 return (cupsdCloseClient(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 (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1283 return (cupsdCloseClient(con
));
1287 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1288 con
->http
.tls
== NULL
)
1292 * Do encryption stuff...
1295 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1296 return (cupsdCloseClient(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");
1303 cupsdEncryptClient(con
);
1305 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1306 return (cupsdCloseClient(con
));
1307 #endif /* HAVE_SSL */
1310 con
->best
= cupsdFindBest(con
->uri
, con
->http
.state
);
1312 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1314 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: Unauthorized request for %s...\n",
1316 cupsdSendError(con
, status
);
1317 return (cupsdCloseClient(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
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1339 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1342 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1343 return (cupsdCloseClient(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 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1365 if ((ptr
= strchr(con
->uri
+ 6, '?')) != NULL
)
1366 cupsdSetStringf(&con
->options
, "admin%s", ptr
);
1368 cupsdSetString(&con
->options
, "admin");
1370 else if (!strncmp(con
->uri
, "/printers", 9))
1372 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1373 cupsdSetString(&con
->options
, con
->uri
+ 9);
1375 else if (!strncmp(con
->uri
, "/classes", 8))
1377 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1378 cupsdSetString(&con
->options
, con
->uri
+ 8);
1380 else if (!strncmp(con
->uri
, "/jobs", 5))
1382 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1383 cupsdSetString(&con
->options
, con
->uri
+ 5);
1387 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1388 cupsdSetString(&con
->options
, con
->uri
+ 5);
1391 if (con
->options
[0] == '/')
1392 _cups_strcpy(con
->options
, con
->options
+ 1);
1394 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1396 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1397 return (cupsdCloseClient(con
));
1400 cupsdLogRequest(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 (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1418 return (cupsdCloseClient(con
));
1428 if ((filename
= get_file(con
, &filestats
, buf
,
1429 sizeof(buf
))) == NULL
)
1431 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1432 return (cupsdCloseClient(con
));
1437 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1439 if (cupsdIsCGI(con
, filename
, &filestats
, type
))
1442 * Note: con->command and con->options were set by
1446 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1448 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1449 return (cupsdCloseClient(con
));
1452 cupsdLogRequest(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 (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1462 return (cupsdCloseClient(con
));
1467 strcpy(line
, "text/plain");
1469 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1471 if (!cupsdSendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1472 return (cupsdCloseClient(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 cupsdLogMessage(L_DEBUG2
, "POST %s", con
->uri
);
1484 cupsdLogMessage(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 (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1495 return (cupsdCloseClient(con
));
1499 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1502 * Negative content lengths are invalid!
1505 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1506 return (cupsdCloseClient(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 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi", ServerBin
);
1534 if ((ptr
= strchr(con
->uri
+ 6, '?')) != NULL
)
1535 cupsdSetStringf(&con
->options
, "admin%s", ptr
);
1537 cupsdSetString(&con
->options
, "admin");
1539 else if (!strncmp(con
->uri
, "/printers", 9))
1541 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi", ServerBin
);
1542 cupsdSetString(&con
->options
, con
->uri
+ 9);
1544 else if (!strncmp(con
->uri
, "/classes", 8))
1546 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi", ServerBin
);
1547 cupsdSetString(&con
->options
, con
->uri
+ 8);
1549 else if (!strncmp(con
->uri
, "/jobs", 5))
1551 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi", ServerBin
);
1552 cupsdSetString(&con
->options
, con
->uri
+ 5);
1556 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi", ServerBin
);
1557 cupsdSetString(&con
->options
, con
->uri
+ 5);
1560 if (con
->options
[0] == '/')
1561 _cups_strcpy(con
->options
, con
->options
+ 1);
1563 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %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 (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1579 return (cupsdCloseClient(con
));
1584 type
= mimeFileType(MimeDatabase
, filename
, NULL
);
1586 if (!cupsdIsCGI(con
, filename
, &filestats
, type
))
1589 * Only POST to CGI's...
1592 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1593 return (cupsdCloseClient(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 (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1613 return (cupsdCloseClient(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 cupsdLogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1624 cupsdLogMessage(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 (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1635 return (cupsdCloseClient(con
));
1639 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1642 * Negative content lengths are invalid!
1645 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1646 return (cupsdCloseClient(con
));
1652 * Open a temporary file to hold the request...
1655 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1656 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1658 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1659 con
->filename
, con
->file
);
1663 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1664 return (cupsdCloseClient(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 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1675 return (cupsdCloseClient(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
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1689 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1692 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1693 return (cupsdCloseClient(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 (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1712 return (cupsdCloseClient(con
));
1714 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1715 return (cupsdCloseClient(con
));
1717 cupsdLogRequest(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 (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1732 return (cupsdCloseClient(con
));
1736 else if ((filename
= get_file(con
, &filestats
, buf
,
1737 sizeof(buf
))) == NULL
)
1739 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1740 return (cupsdCloseClient(con
));
1742 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1744 else if (!check_if_modified(con
, &filestats
))
1746 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1747 return (cupsdCloseClient(con
));
1749 cupsdLogRequest(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 (!cupsdSendHeader(con
, HTTP_OK
, line
))
1764 return (cupsdCloseClient(con
));
1766 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1767 httpGetDateString(filestats
.st_mtime
)) < 0)
1768 return (cupsdCloseClient(con
));
1770 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1771 (unsigned long)filestats
.st_size
) < 0)
1772 return (cupsdCloseClient(con
));
1774 cupsdLogRequest(con
, HTTP_OK
);
1777 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1778 return (cupsdCloseClient(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 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %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 (cupsdCloseClient(con
));
1805 con
->bytes
+= bytes
;
1807 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d writing %d bytes to %d",
1808 con
->http
.fd
, bytes
, con
->file
);
1810 if (write(con
->file
, line
, bytes
) < bytes
)
1812 cupsdLogMessage(L_ERROR
, "cupsdReadClient: Unable to write %d bytes to %s: %s",
1813 bytes
, con
->filename
, strerror(errno
));
1815 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: Closing data file %d...",
1820 unlink(con
->filename
);
1821 cupsdClearString(&con
->filename
);
1823 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1824 return (cupsdCloseClient(con
));
1828 if (con
->http
.state
== HTTP_WAITING
)
1831 * End of file, see how big it is...
1834 fstat(con
->file
, &filestats
);
1836 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %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 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d Removing temp file %s",
1850 con
->http
.fd
, con
->filename
);
1851 unlink(con
->filename
);
1852 cupsdClearString(&con
->filename
);
1854 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1855 return (cupsdCloseClient(con
));
1859 * Install the configuration file...
1862 status
= install_conf_file(con
);
1865 * Return the status to the client...
1868 if (!cupsdSendError(con
, status
))
1869 return (cupsdCloseClient(con
));
1873 case HTTP_POST_RECV
:
1874 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %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 cupsdLogMessage(L_ERROR
, "cupsdReadClient: %d IPP Read Error!",
1890 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1891 return (cupsdCloseClient(con
));
1893 else if (ipp_state
!= IPP_DATA
)
1895 if (con
->http
.state
== HTTP_POST_SEND
)
1897 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1898 return (cupsdCloseClient(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 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1914 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1916 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1917 con
->filename
, con
->file
);
1921 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1922 return (cupsdCloseClient(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 (cupsdCloseClient(con
));
1936 con
->bytes
+= bytes
;
1938 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d writing %d bytes to %d",
1939 con
->http
.fd
, bytes
, con
->file
);
1941 if (write(con
->file
, line
, bytes
) < bytes
)
1943 cupsdLogMessage(L_ERROR
, "cupsdReadClient: Unable to write %d bytes to %s: %s",
1944 bytes
, con
->filename
, strerror(errno
));
1946 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: Closing file %d...",
1951 unlink(con
->filename
);
1952 cupsdClearString(&con
->filename
);
1954 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1955 return (cupsdCloseClient(con
));
1958 else if (con
->http
.state
== HTTP_POST_RECV
)
1959 return (1); /* ??? */
1960 else if (con
->http
.state
!= HTTP_POST_SEND
)
1961 return (cupsdCloseClient(con
));
1964 if (con
->http
.state
== HTTP_POST_SEND
)
1968 fstat(con
->file
, &filestats
);
1970 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %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 cupsdLogMessage(L_DEBUG2
, "cupsdReadClient: %d Removing temp file %s",
1984 con
->http
.fd
, con
->filename
);
1985 unlink(con
->filename
);
1986 cupsdClearString(&con
->filename
);
1991 * Delete any IPP request data...
1994 ippDelete(con
->request
);
1995 con
->request
= NULL
;
1998 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1999 return (cupsdCloseClient(con
));
2004 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2006 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
2007 return (cupsdCloseClient(con
));
2010 cupsdLogRequest(con
, HTTP_OK
);
2015 return (cupsdProcessIPPRequest(con
));
2020 break; /* Anti-compiler-warning-code */
2023 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2024 return (cupsdCloseClient(con
));
2031 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2034 int /* O - 1 on success, 0 on failure */
2035 cupsdSendCommand(cupsd_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 cupsdLogMessage(L_ERROR
, "cupsdSendCommand: %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 cupsdLogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
2064 cupsdLogMessage(L_DEBUG
, "cupsdSendCommand: %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 cupsdLogMessage(L_DEBUG2
, "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
2072 cupsdLogMessage(L_DEBUG2
, "cupsdSendCommand: 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 * 'cupsdSendError()' - Send an error message via HTTP.
2091 int /* O - 1 if successful, 0 otherwise */
2092 cupsdSendError(cupsd_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 cupsdLogRequest(con
, code
);
2104 cupsdLogMessage(L_DEBUG
, "cupsdSendError: %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 (!cupsdSendHeader(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 * 'cupsdSendFile()' - Send a file via HTTP.
2176 cupsdSendFile(cupsd_client_t
*con
,
2180 struct stat
*filestats
)
2182 con
->file
= open(filename
, O_RDONLY
);
2184 cupsdLogMessage(L_DEBUG
, "cupsdSendFile: %d file=%d", con
->http
.fd
, con
->file
);
2189 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2193 if (!cupsdSendHeader(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 cupsdLogMessage(L_DEBUG2
, "cupsdSendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2206 FD_SET(con
->http
.fd
, OutputSet
);
2213 * 'cupsdSendHeader()' - Send an HTTP request.
2216 int /* O - 1 on success, 0 on failure */
2217 cupsdSendHeader(cupsd_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 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2290 cupsdUpdateCGI(void)
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 cupsdLogMessage(L_CRIT
, "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2315 * 'cupsdWriteClient()' - Write data to a client as needed.
2318 int /* O - 1 if success, 0 if fail */
2319 cupsdWriteClient(cupsd_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 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient(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)
2343 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: Read %d bytes from file %d...",
2346 if (con
->pipe_pid
&& !con
->got_fields
)
2349 * Inspect the data for Content-Type and other fields.
2354 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2355 if (*bufptr
== '\n')
2358 * Send line to client...
2361 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2365 cupsdLogMessage(L_DEBUG2
, "Script header: %s", buf
);
2367 if (!con
->sent_header
)
2370 * Handle redirection and CGI status codes...
2373 if (!strncasecmp(buf
, "Location:", 9))
2374 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2375 else if (!strncasecmp(buf
, "Status:", 7))
2376 cupsdSendHeader(con
, atoi(buf
+ 7), NULL
);
2378 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2380 if (con
->http
.version
== HTTP_1_1
)
2382 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2384 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2388 con
->sent_header
= 1;
2391 if (strncasecmp(buf
, "Status:", 7))
2392 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2394 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: %d %s", con
->http
.fd
, buf
);
2400 bytes
-= (bufptr
- buf
);
2401 memmove(buf
, bufptr
, bytes
+ 1);
2405 * See if the line was empty...
2408 if (con
->field_col
== 0)
2409 con
->got_fields
= 1;
2413 else if (*bufptr
!= '\r')
2416 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2417 con
->http
.fd
, bytes
, con
->got_fields
);
2419 if (bytes
> 0 && !con
->got_fields
)
2422 * Remaining text needs to go out...
2425 httpPrintf(HTTP(con
), "%s", buf
);
2427 con
->http
.activity
= time(NULL
);
2430 else if (bytes
== 0)
2432 con
->http
.activity
= time(NULL
);
2437 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
2439 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: %d Write of %d bytes failed!",
2440 con
->http
.fd
, bytes
);
2442 cupsdCloseClient(con
);
2446 con
->bytes
+= bytes
;
2451 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: %d bytes < 0", con
->http
.fd
);
2453 cupsdLogRequest(con
, HTTP_OK
);
2455 httpFlushWrite(HTTP(con
));
2457 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2459 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2461 cupsdCloseClient(con
);
2466 con
->http
.state
= HTTP_WAITING
;
2468 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: Removing fd %d from OutputSet...",
2471 FD_CLR(con
->http
.fd
, OutputSet
);
2475 if (FD_ISSET(con
->file
, InputSet
))
2477 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: Removing fd %d from InputSet...",
2479 FD_CLR(con
->file
, InputSet
);
2483 cupsdEndProcess(con
->pipe_pid
, 0);
2485 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: %d Closing data file %d.",
2486 con
->http
.fd
, con
->file
);
2495 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: %d Removing temp file %s",
2496 con
->http
.fd
, con
->filename
);
2497 unlink(con
->filename
);
2498 cupsdClearString(&con
->filename
);
2501 if (con
->request
!= NULL
)
2503 ippDelete(con
->request
);
2504 con
->request
= NULL
;
2507 if (con
->response
!= NULL
)
2509 ippDelete(con
->response
);
2510 con
->response
= NULL
;
2513 cupsdClearString(&con
->command
);
2514 cupsdClearString(&con
->options
);
2516 if (!con
->http
.keep_alive
)
2518 cupsdCloseClient(con
);
2524 con
->file_ready
= 0;
2526 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2528 cupsdLogMessage(L_DEBUG2
, "cupsdWriteClient: Adding fd %d to InputSet...", con
->file
);
2529 FD_SET(con
->file
, InputSet
);
2533 con
->http
.activity
= time(NULL
);
2540 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2543 static int /* O - 1 if modified since */
2544 check_if_modified(cupsd_client_t
*con
, /* I - Client connection */
2545 struct stat
*filestats
) /* I - File information */
2547 char *ptr
; /* Pointer into field */
2548 time_t date
; /* Time/date value */
2549 int size
; /* Size/length value */
2554 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2559 cupsdLogMessage(L_DEBUG2
, "check_if_modified: %d If-Modified-Since=\"%s\"",
2562 while (*ptr
!= '\0')
2564 while (isspace(*ptr
) || *ptr
== ';')
2567 if (strncasecmp(ptr
, "length=", 7) == 0)
2572 while (isdigit(*ptr
))
2575 else if (isalpha(*ptr
))
2577 date
= httpGetDateTime(ptr
);
2578 while (*ptr
!= '\0' && *ptr
!= ';')
2583 cupsdLogMessage(L_DEBUG2
, "check_if_modified: %d sizes=%d,%d dates=%d,%d",
2584 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2585 (int)filestats
->st_mtime
);
2587 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2588 (date
< filestats
->st_mtime
&& date
!= 0) ||
2589 (size
== 0 && date
== 0));
2594 * 'decode_auth()' - Decode an authorization string.
2598 decode_auth(cupsd_client_t
*con
) /* I - Client to decode to */
2600 char *s
, /* Authorization string */
2601 value
[1024]; /* Value string */
2602 const char *username
; /* Certificate username */
2606 * Decode the string...
2609 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2611 cupsdLogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2614 if (strncmp(s
, "Basic", 5) == 0)
2620 httpDecode64(value
, s
);
2623 * Pull the username and password out...
2626 if ((s
= strchr(value
, ':')) == NULL
)
2628 cupsdLogMessage(L_DEBUG
, "decode_auth: %d no colon in auth string \"%s\"",
2629 con
->http
.fd
, value
);
2635 strlcpy(con
->username
, value
, sizeof(con
->username
));
2636 strlcpy(con
->password
, s
, sizeof(con
->password
));
2638 else if (strncmp(s
, "Local", 5) == 0)
2644 if ((username
= cupsdFindCert(s
)) != NULL
)
2645 strlcpy(con
->username
, username
, sizeof(con
->username
));
2647 else if (strncmp(s
, "Digest", 5) == 0)
2650 * Get the username and password from the Digest attributes...
2653 if (httpGetSubField(&(con
->http
), HTTP_FIELD_AUTHORIZATION
, "username",
2655 strlcpy(con
->username
, value
, sizeof(con
->username
));
2657 if (httpGetSubField(&(con
->http
), HTTP_FIELD_AUTHORIZATION
, "response",
2659 strlcpy(con
->password
, value
, sizeof(con
->password
));
2662 cupsdLogMessage(L_DEBUG2
, "decode_auth: %d username=\"%s\"",
2663 con
->http
.fd
, con
->username
);
2668 * 'get_file()' - Get a filename and state info.
2671 static char * /* O - Real filename */
2672 get_file(cupsd_client_t
*con
, /* I - Client connection */
2673 struct stat
*filestats
, /* O - File information */
2674 char *filename
, /* IO - Filename buffer */
2675 int len
) /* I - Buffer length */
2677 int status
; /* Status of filesystem calls */
2678 char *ptr
; /* Pointer info filename */
2679 int plen
; /* Remaining length after pointer */
2683 * Need to add DocumentRoot global...
2686 if (!strncmp(con
->uri
, "/ppd/", 5))
2687 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2688 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2689 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2690 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2692 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2693 strlcpy(filename
, AccessLog
, len
);
2694 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2695 strlcpy(filename
, ErrorLog
, len
);
2696 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2697 strlcpy(filename
, PageLog
, len
);
2701 else if (con
->language
!= NULL
)
2702 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2705 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2707 if ((ptr
= strchr(filename
, '?')) != NULL
)
2711 * Grab the status for this language; if there isn't a language-specific file
2712 * then fallback to the default one...
2715 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2718 * Drop the language prefix and try the current directory...
2721 if (strncmp(con
->uri
, "/ppd/", 5) &&
2722 strncmp(con
->uri
, "/admin/conf/", 12) &&
2723 strncmp(con
->uri
, "/admin/log/", 11))
2725 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2727 if ((ptr
= strchr(filename
, '?')) != NULL
)
2730 status
= stat(filename
, filestats
);
2735 * If we're found a directory, get the index.html file instead...
2738 if (!status
&& S_ISDIR(filestats
->st_mode
))
2740 if (filename
[strlen(filename
) - 1] != '/')
2741 strlcat(filename
, "/", len
);
2743 ptr
= filename
+ strlen(filename
);
2744 plen
= len
- (ptr
- filename
);
2746 strlcpy(ptr
, "index.html", plen
);
2747 status
= stat(filename
, filestats
);
2752 strlcpy(ptr
, "index.class", plen
);
2753 status
= stat(filename
, filestats
);
2755 #endif /* HAVE_JAVA */
2760 strlcpy(ptr
, "index.pl", plen
);
2761 status
= stat(filename
, filestats
);
2763 #endif /* HAVE_PERL */
2768 strlcpy(ptr
, "index.php", plen
);
2769 status
= stat(filename
, filestats
);
2771 #endif /* HAVE_PHP */
2776 strlcpy(ptr
, "index.pyc", plen
);
2777 status
= stat(filename
, filestats
);
2782 strlcpy(ptr
, "index.py", plen
);
2783 status
= stat(filename
, filestats
);
2785 #endif /* HAVE_PYTHON */
2788 cupsdLogMessage(L_DEBUG2
, "get_file: %d filename=%s size=%d",
2789 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2792 con
->http
.data_remaining
= (int)filestats
->st_size
;
2802 * 'install_conf_file()' - Install a configuration file.
2805 static http_status_t
/* O - Status */
2806 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
2808 cups_file_t
*in
, /* Input file */
2809 *out
; /* Output file */
2810 char buffer
[1024]; /* Copy buffer */
2811 int bytes
; /* Number of bytes */
2812 char conffile
[1024], /* Configuration filename */
2813 newfile
[1024], /* New config filename */
2814 oldfile
[1024]; /* Old config filename */
2815 struct stat confinfo
; /* Config file info */
2819 * First construct the filenames...
2822 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2823 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2824 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2826 cupsdLogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2829 * Get the owner, group, and permissions of the configuration file.
2830 * If it doesn't exist, assign it to the User and Group in the
2831 * cupsd.conf file with mode 0640 permissions.
2834 if (stat(conffile
, &confinfo
))
2836 confinfo
.st_uid
= User
;
2837 confinfo
.st_gid
= Group
;
2838 confinfo
.st_mode
= ConfigFilePerm
;
2842 * Open the request file and new config file...
2845 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2847 cupsdLogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2848 con
->filename
, strerror(errno
));
2849 return (HTTP_SERVER_ERROR
);
2852 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2855 cupsdLogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2856 newfile
, strerror(errno
));
2857 return (HTTP_SERVER_ERROR
);
2860 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2861 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2864 * Copy from the request to the new config file...
2867 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2868 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2870 cupsdLogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2871 newfile
, strerror(errno
));
2877 return (HTTP_SERVER_ERROR
);
2881 * Close the files...
2885 if (cupsFileClose(out
))
2887 cupsdLogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2888 newfile
, strerror(errno
));
2892 return (HTTP_SERVER_ERROR
);
2896 * Remove the request file...
2899 unlink(con
->filename
);
2900 cupsdClearString(&con
->filename
);
2903 * Unlink the old backup, rename the current config file to the backup
2904 * filename, and rename the new config file to the config file name...
2907 if (unlink(oldfile
))
2908 if (errno
!= ENOENT
)
2910 cupsdLogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2911 oldfile
, strerror(errno
));
2915 return (HTTP_SERVER_ERROR
);
2918 if (rename(conffile
, oldfile
))
2919 if (errno
!= ENOENT
)
2921 cupsdLogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2922 conffile
, strerror(errno
));
2926 return (HTTP_SERVER_ERROR
);
2929 if (rename(newfile
, conffile
))
2931 cupsdLogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2932 newfile
, strerror(errno
));
2934 rename(oldfile
, conffile
);
2937 return (HTTP_SERVER_ERROR
);
2941 * If the cupsd.conf file was updated, set the NeedReload flag...
2944 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
2945 NeedReload
= RELOAD_CUPSD
;
2947 NeedReload
= RELOAD_ALL
;
2949 ReloadTime
= time(NULL
);
2952 * Return that the file was created successfully...
2955 return (HTTP_CREATED
);
2960 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
2963 static int /* O - 0 if relative, 1 if absolute */
2964 is_path_absolute(const char *path
) /* I - Input path */
2967 * Check for a leading slash...
2974 * Check for "/.." in the path...
2977 while ((path
= strstr(path
, "/..")) != NULL
)
2979 if (!path
[3] || path
[3] == '/')
2986 * If we haven't found any relative paths, return 1 indicating an
2995 * 'pipe_command()' - Pipe the output of a command to the remote client.
2998 static int /* O - Process ID */
2999 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3000 int infile
, /* I - Standard input for command */
3001 int *outfile
, /* O - Standard output for command */
3002 char *command
, /* I - Command to run */
3003 char *options
, /* I - Options for command */
3004 int root
) /* I - Run as root? */
3006 int i
; /* Looping var */
3007 int pid
; /* Process ID */
3008 char *commptr
; /* Command string pointer */
3009 char *uriptr
; /* URI string pointer */
3010 int fds
[2]; /* Pipe FDs */
3011 int argc
; /* Number of arguments */
3012 int envc
; /* Number of environment variables */
3013 char argbuf
[10240], /* Argument buffer */
3014 *argv
[100], /* Argument strings */
3015 *envp
[100]; /* Environment variables */
3016 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3017 content_type
[1024], /* CONTENT_TYPE environment variable */
3018 http_cookie
[1024], /* HTTP_COOKIE environment variable */
3019 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3020 lang
[1024], /* LANG environment variable */
3021 *query_string
, /* QUERY_STRING env variable */
3022 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3023 remote_host
[1024], /* REMOTE_HOST environment variable */
3024 remote_user
[1024], /* REMOTE_USER environment variable */
3025 script_name
[1024], /* SCRIPT_NAME environment variable */
3026 server_name
[1024], /* SERVER_NAME environment variable */
3027 server_port
[1024]; /* SERVER_PORT environment variable */
3028 static const char * const locale_encodings
[] =
3029 { /* Locale charset names */
3030 "ASCII", "ISO8859-1", "ISO8859-2", "ISO8859-3",
3031 "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7",
3032 "ISO8859-8", "ISO8859-9", "ISO8859-10", "UTF-8",
3033 "ISO8859-13", "ISO8859-14", "ISO8859-15", "CP874",
3034 "CP1250", "CP1251", "CP1252", "CP1253",
3035 "CP1254", "CP1255", "CP1256", "CP1257",
3036 "CP1258", "KOI8R", "KOI8U", "ISO8859-11",
3037 "ISO8859-16", "", "", "",
3048 "CP932", "CP936", "CP949", "CP950",
3049 "CP1361", "", "", "",
3066 "EUC-CN", "EUC-JP", "EUC-KR", "EUC-TW"
3071 * Parse a copy of the options string, which is of the form:
3073 * name argument+argument+argument
3074 * name?argument+argument+argument
3075 * name param=value¶m=value
3076 * name?param=value¶m=value
3078 * If the string contains an "=" character after the initial name,
3079 * then we treat it as a HTTP GET form request and make a copy of
3080 * the remaining string for the environment variable.
3082 * The string is always parsed out as command-line arguments, to
3083 * be consistent with Apache...
3086 cupsdLogMessage(L_DEBUG2
, "pipe_command: command=\"%s\", options=\"%s\"",
3089 strlcpy(argbuf
, options
, sizeof(argbuf
));
3092 query_string
= NULL
;
3094 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
3097 * Break arguments whenever we see a + or space...
3100 if (*commptr
== ' ' || *commptr
== '+' || (*commptr
== '?' && argc
== 1))
3103 * Terminate the current string and skip trailing whitespace...
3108 while (*commptr
== ' ')
3112 * If we don't have a blank string, save it as another argument...
3117 argv
[argc
] = commptr
;
3124 * If we see an "=" in the remaining string, make a copy of it since
3125 * it will be query data...
3128 if (argc
== 2 && strchr(commptr
, '=') && con
->operation
== HTTP_GET
)
3129 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3132 * Don't skip the first non-blank character...
3137 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3138 isxdigit(commptr
[2] & 255))
3141 * Convert the %xx notation to the individual character.
3144 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3145 *commptr
= (commptr
[1] - '0') << 4;
3147 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3149 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3150 *commptr
|= commptr
[2] - '0';
3152 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3154 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3157 * Check for a %00 and break if that is the case...
3167 if (argv
[0][0] == '\0')
3168 argv
[0] = strrchr(command
, '/') + 1;
3171 * Setup the environment variables as needed...
3175 snprintf(lang
, sizeof(lang
), "LANG=%s.%s", con
->language
->language
,
3176 locale_encodings
[con
->language
->encoding
]);
3178 strcpy(lang
, "LANG=C");
3180 strcpy(remote_addr
, "REMOTE_ADDR=");
3181 httpAddrString(&(con
->http
.hostaddr
), remote_addr
+ 12,
3182 sizeof(remote_addr
) - 12);
3184 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3185 con
->http
.hostname
);
3187 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3188 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3191 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3193 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3196 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3198 envp
[envc
++] = lang
;
3199 envp
[envc
++] = "REDIRECT_STATUS=1";
3200 envp
[envc
++] = server_name
;
3201 envp
[envc
++] = server_port
;
3202 envp
[envc
++] = remote_addr
;
3203 envp
[envc
++] = remote_host
;
3204 envp
[envc
++] = script_name
;
3206 if (con
->username
[0])
3208 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3210 envp
[envc
++] = remote_user
;
3213 if (con
->http
.version
== HTTP_1_1
)
3214 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3215 else if (con
->http
.version
== HTTP_1_0
)
3216 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3218 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3220 if (con
->http
.cookie
)
3222 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3224 envp
[envc
++] = http_cookie
;
3227 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3229 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3230 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3231 envp
[envc
++] = http_user_agent
;
3234 if (con
->operation
== HTTP_GET
)
3236 for (i
= 0; i
< argc
; i
++)
3237 cupsdLogMessage(L_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3239 envp
[envc
++] = "REQUEST_METHOD=GET";
3244 * Add GET form variables after ?...
3247 envp
[envc
++] = query_string
;
3252 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
3253 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3254 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3256 envp
[envc
++] = "REQUEST_METHOD=POST";
3257 envp
[envc
++] = content_length
;
3258 envp
[envc
++] = content_type
;
3262 * Tell the CGI if we are using encryption...
3265 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3266 envp
[envc
++] = "HTTPS=ON";
3269 * Terminate the environment array...
3274 if (LogLevel
== L_DEBUG2
)
3276 for (i
= 0; i
< argc
; i
++)
3277 cupsdLogMessage(L_DEBUG2
, "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
3278 for (i
= 0; i
< envc
; i
++)
3279 cupsdLogMessage(L_DEBUG2
, "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
3283 * Create a pipe for the output...
3286 if (cupsdOpenPipe(fds
))
3288 cupsdClearString(&query_string
);
3290 cupsdLogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
3291 argv
[0], strerror(errno
));
3296 * Then execute the command...
3299 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3300 -1, root
, &pid
) < 0)
3303 * Error - can't fork!
3306 cupsdLogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3309 cupsdClosePipe(fds
);
3315 * Fork successful - return the PID...
3318 if (con
->username
[0])
3319 cupsdAddCert(pid
, con
->username
);
3321 cupsdLogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3327 cupsdClearString(&query_string
);
3333 #if defined(HAVE_CDSASSL)
3335 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
3338 static OSStatus
/* O - -1 on error, 0 on success */
3339 CDSAReadFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3340 void *data
, /* I - Data buffer */
3341 size_t *dataLength
) /* IO - Number of bytes */
3343 ssize_t bytes
; /* Number of bytes read */
3346 bytes
= recv((int)connection
, data
, *dataLength
, 0);
3349 *dataLength
= bytes
;
3358 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
3361 static OSStatus
/* O - -1 on error, 0 on success */
3362 CDSAWriteFunc(SSLConnectionRef connection
, /* I - SSL/TLS connection */
3363 const void *data
, /* I - Data buffer */
3364 size_t *dataLength
) /* IO - Number of bytes */
3369 bytes
= write((int)connection
, data
, *dataLength
);
3372 *dataLength
= bytes
;
3378 #endif /* HAVE_CDSASSL */