2 * "$Id: client.c 5225 2006-03-04 12:28:10Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2006 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 * get_cdsa_server_certs() - Convert a keychain name into the CFArrayRef
40 * required by SSLSetCertificate.
41 * get_file() - Get a filename and state info.
42 * install_conf_file() - Install a configuration file.
43 * is_path_absolute() - Is a path absolute and free of relative elements.
44 * make_certificate() - Make a self-signed SSL/TLS certificate.
45 * pipe_command() - Pipe the output of a command to the remote client.
49 * Include necessary headers...
52 #include <cups/http-private.h>
56 # include <Security/Security.h>
57 #endif /* HAVE_CDSASSL */
59 # include <gnutls/x509.h>
60 #endif /* HAVE_GNUTLS */
67 static int check_if_modified(cupsd_client_t
*con
,
68 struct stat
*filestats
);
70 static CFArrayRef
get_cdsa_server_certs(void);
71 #endif /* HAVE_CDSASSL */
72 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
73 char *filename
, int len
);
74 static http_status_t
install_conf_file(cupsd_client_t
*con
);
75 static int is_path_absolute(const char *path
);
77 static void make_certificate(void);
78 #endif /* HAVE_GNUTLS */
79 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
80 char *command
, char *options
, int root
);
84 * 'cupsdAcceptClient()' - Accept a new client.
88 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
90 int count
; /* Count of connections on a host */
91 int val
; /* Parameter value */
92 cupsd_client_t
*con
, /* New client pointer */
93 *tempcon
; /* Temporary client pointer */
94 http_addrlist_t
*addrlist
, /* List of adddresses for host */
95 *addr
; /* Current address */
96 socklen_t addrlen
; /* Length of address */
97 char *hostname
; /* Hostname for address */
98 http_addr_t temp
; /* Temporary address variable */
99 static time_t last_dos
= 0; /* Time of last DoS attack */
102 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
103 "cupsdAcceptClient(lis=%p) %d Clients = %d",
104 lis
, lis
->fd
, cupsArrayCount(Clients
));
107 * Make sure we don't have a full set of clients already...
110 if (cupsArrayCount(Clients
) == MaxClients
)
114 * Get a pointer to the next available client...
118 Clients
= cupsArrayNew(NULL
, NULL
);
123 con
= calloc(1, sizeof(cupsd_client_t
));
125 con
->http
.activity
= time(NULL
);
127 con
->http
.hostaddr
= &(con
->clientaddr
);
130 * Accept the client and get the remote address...
133 addrlen
= sizeof(http_addr_t
);
135 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
138 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
145 if (lis
->address
.addr
.sa_family
== AF_INET6
)
148 * Save the connected port number...
151 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
154 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
155 * can more easily use...
158 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
159 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
160 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
161 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
164 #endif /* AF_INET6 */
165 if (lis
->address
.addr
.sa_family
== AF_INET
)
166 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
169 * Check the number of clients on the same address...
172 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
174 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
175 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
178 if (count
>= MaxClientsPerHost
)
182 if (count
>= MaxClientsPerHost
)
184 if ((time(NULL
) - last_dos
) >= 60)
186 last_dos
= time(NULL
);
187 cupsdLogMessage(CUPSD_LOG_WARN
,
188 "Possible DoS attack - more than %d clients connecting "
190 MaxClientsPerHost
, tempcon
->http
.hostname
);
194 closesocket(con
->http
.fd
);
204 * Get the hostname or format the IP address as needed...
207 if (httpAddrLocalhost(con
->http
.hostaddr
))
210 * Map accesses from the loopback interface to "localhost"...
213 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
214 hostname
= con
->http
.hostname
;
219 * Map accesses from the same host to the server name.
222 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
223 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
228 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
229 hostname
= con
->http
.hostname
;
231 else if (HostNameLookups
)
232 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
233 sizeof(con
->http
.hostname
));
237 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
238 sizeof(con
->http
.hostname
));
242 if (hostname
== NULL
&& HostNameLookups
== 2)
245 * Can't have an unresolved IP address with double-lookups enabled...
248 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
249 "cupsdAcceptClient: Closing connection %d...",
253 closesocket(con
->http
.fd
);
258 cupsdLogMessage(CUPSD_LOG_WARN
,
259 "Name lookup failed - connection from %s closed!",
266 if (HostNameLookups
== 2)
269 * Do double lookups as needed...
272 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
275 * See if the hostname maps to the same IP address...
278 for (addr
= addrlist
; addr
; addr
= addr
->next
)
279 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
285 httpAddrFreeList(addrlist
);
290 * Can't have a hostname that doesn't resolve to the same IP address
291 * with double-lookups enabled...
294 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
295 "cupsdAcceptClient: Closing connection %d...",
299 closesocket(con
->http
.fd
);
304 cupsdLogMessage(CUPSD_LOG_WARN
,
305 "IP lookup failed - connection from %s closed!",
313 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
314 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
315 con
->http
.fd
, con
->http
.hostname
,
316 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
318 #endif /* AF_INET6 */
320 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
321 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
322 con
->http
.fd
, con
->http
.hostname
);
324 #endif /* AF_LOCAL */
325 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
326 con
->http
.fd
, con
->http
.hostname
,
327 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
330 * Get the local address the client connected to...
333 addrlen
= sizeof(temp
);
334 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
336 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
339 strcpy(con
->servername
, "localhost");
340 con
->serverport
= LocalPort
;
345 if (temp
.addr
.sa_family
== AF_INET6
)
347 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
348 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
351 #endif /* AF_INET6 */
352 if (temp
.addr
.sa_family
== AF_INET
)
354 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
355 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
359 strcpy(con
->servername
, "localhost");
360 con
->serverport
= LocalPort
;
364 cupsArrayAdd(Clients
, con
);
366 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
367 "cupsdAcceptClient: %d connected to server on %s:%d",
368 con
->http
.fd
, con
->servername
, con
->serverport
);
371 * Using TCP_NODELAY improves responsiveness, especially on systems
372 * with a slow loopback interface... Since we write large buffers
373 * when sending print files and requests, there shouldn't be any
374 * performance penalty for this...
378 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
381 * Close this file on all execs...
384 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
387 * Add the socket to the select() input mask.
390 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
391 "cupsdAcceptClient: Adding fd %d to InputSet...",
393 FD_SET(con
->http
.fd
, InputSet
);
396 * Temporarily suspend accept()'s until we lose a client...
399 if (cupsArrayCount(Clients
) == MaxClients
)
400 cupsdPauseListening();
404 * See if we are connecting on a secure port...
407 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
410 * https connection; go secure...
413 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
415 cupsdEncryptClient(con
);
419 #endif /* HAVE_SSL */
424 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
428 cupsdCloseAllClients(void)
430 cupsd_client_t
*con
; /* Current client */
433 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
435 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
436 cupsdCloseClient(con
);
441 * 'cupsdCloseClient()' - Close a remote client.
444 int /* O - 1 if partial close, 0 if fully closed */
445 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
447 int partial
; /* Do partial close for SSL? */
449 SSL_CTX
*context
; /* Context for encryption */
450 SSL
*conn
; /* Connection for encryption */
451 unsigned long error
; /* Error code */
452 #elif defined(HAVE_GNUTLS)
453 http_tls_t
*conn
; /* TLS connection information */
454 int error
; /* Error code */
455 gnutls_certificate_server_credentials
*credentials
;
456 /* TLS credentials */
457 #endif /* HAVE_LIBSSL */
460 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
463 * Flush pending writes before closing...
466 httpFlushWrite(HTTP(con
));
472 * Shutdown encryption as needed...
480 conn
= (SSL
*)(con
->http
.tls
);
481 context
= SSL_get_SSL_CTX(conn
);
483 switch (SSL_shutdown(conn
))
486 cupsdLogMessage(CUPSD_LOG_INFO
,
487 "cupsdCloseClient: SSL shutdown successful!");
490 cupsdLogMessage(CUPSD_LOG_ERROR
,
491 "cupsdCloseClient: Fatal error during SSL shutdown!");
493 while ((error
= ERR_get_error()) != 0)
494 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
495 ERR_error_string(error
, NULL
));
499 SSL_CTX_free(context
);
502 # elif defined(HAVE_GNUTLS)
503 conn
= (http_tls_t
*)(con
->http
.tls
);
504 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
506 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
509 case GNUTLS_E_SUCCESS
:
510 cupsdLogMessage(CUPSD_LOG_INFO
,
511 "cupsdCloseClient: SSL shutdown successful!");
514 cupsdLogMessage(CUPSD_LOG_ERROR
,
515 "cupsdCloseClient: %s", gnutls_strerror(error
));
519 gnutls_deinit(conn
->session
);
520 gnutls_certificate_free_credentials(*credentials
);
524 # elif defined(HAVE_CDSASSL)
525 while (SSLClose((SSLContextRef
)con
->http
.tls
) == errSSLWouldBlock
)
528 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
529 # endif /* HAVE_LIBSSL */
531 con
->http
.tls
= NULL
;
533 #endif /* HAVE_SSL */
535 if (con
->pipe_pid
!= 0)
538 * Stop any CGI process...
541 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
542 "cupsdCloseClient: %d Killing process ID %d...",
543 con
->http
.fd
, con
->pipe_pid
);
544 cupsdEndProcess(con
->pipe_pid
, 1);
550 if (FD_ISSET(con
->file
, InputSet
))
552 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
553 "cupsdCloseClient: %d Removing fd %d from InputSet...",
554 con
->http
.fd
, con
->file
);
555 FD_CLR(con
->file
, InputSet
);
558 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
559 "cupsdCloseClient: %d Closing data file %d.",
560 con
->http
.fd
, con
->file
);
567 * Close the socket and clear the file from the input set for select()...
570 if (con
->http
.fd
> 0)
575 * Only do a partial close so that the encrypted client gets everything.
578 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
579 "cupsdCloseClient: Removing fd %d from OutputSet...",
581 shutdown(con
->http
.fd
, 0);
582 FD_CLR(con
->http
.fd
, OutputSet
);
587 * Shut the socket down fully...
590 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
591 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
594 FD_CLR(con
->http
.fd
, InputSet
);
595 FD_CLR(con
->http
.fd
, OutputSet
);
606 if (con
->http
.input_set
)
607 free(con
->http
.input_set
);
609 httpClearCookie(HTTP(con
));
611 cupsdClearString(&con
->filename
);
612 cupsdClearString(&con
->command
);
613 cupsdClearString(&con
->options
);
617 ippDelete(con
->request
);
623 ippDelete(con
->response
);
624 con
->response
= NULL
;
629 cupsLangFree(con
->language
);
630 con
->language
= NULL
;
634 * Re-enable new client connections if we are going back under the
638 if (cupsArrayCount(Clients
) == MaxClients
)
639 cupsdResumeListening();
642 * Compact the list of clients as necessary...
645 cupsArrayRemove(Clients
, con
);
655 * 'cupsdEncryptClient()' - Enable encryption for the client...
658 int /* O - 1 on success, 0 on error */
659 cupsdEncryptClient(cupsd_client_t
*con
) /* I - Client to encrypt */
662 SSL_CTX
*context
; /* Context for encryption */
663 SSL
*conn
; /* Connection for encryption */
664 unsigned long error
; /* Error code */
668 * Create the SSL context and accept the connection...
671 context
= SSL_CTX_new(SSLv23_server_method());
673 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
674 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
675 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
677 conn
= SSL_new(context
);
679 SSL_set_fd(conn
, con
->http
.fd
);
680 if (SSL_accept(conn
) != 1)
682 cupsdLogMessage(CUPSD_LOG_ERROR
,
683 "cupsdEncryptClient: Unable to encrypt connection from %s!",
686 while ((error
= ERR_get_error()) != 0)
687 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdEncryptClient: %s",
688 ERR_error_string(error
, NULL
));
690 SSL_CTX_free(context
);
695 cupsdLogMessage(CUPSD_LOG_DEBUG
,
696 "cupsdEncryptClient: %d Connection from %s now encrypted.",
697 con
->http
.fd
, con
->http
.hostname
);
699 con
->http
.tls
= conn
;
702 #elif defined(HAVE_GNUTLS)
703 http_tls_t
*conn
; /* TLS session object */
704 int error
; /* Error code */
705 gnutls_certificate_server_credentials
*credentials
;
706 /* TLS credentials */
710 * Verify that we have a certificate...
713 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
716 * Nope, make a self-signed certificate...
723 * Create the SSL object and perform the SSL handshake...
726 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
731 credentials
= (gnutls_certificate_server_credentials
*)
732 malloc(sizeof(gnutls_certificate_server_credentials
));
733 if (credentials
== NULL
)
735 cupsdLogMessage(CUPSD_LOG_ERROR
,
736 "cupsdEncryptClient: Unable to encrypt connection from %s!",
738 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdEncryptClient: %s", strerror(errno
));
744 gnutls_certificate_allocate_credentials(credentials
);
745 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
746 ServerKey
, GNUTLS_X509_FMT_PEM
);
748 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
749 gnutls_set_default_priority(conn
->session
);
750 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
751 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)con
->http
.fd
);
753 error
= gnutls_handshake(conn
->session
);
755 if (error
!= GNUTLS_E_SUCCESS
)
757 cupsdLogMessage(CUPSD_LOG_ERROR
,
758 "cupsdEncryptClient: Unable to encrypt connection from %s!",
760 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdEncryptClient: %s",
761 gnutls_strerror(error
));
763 gnutls_deinit(conn
->session
);
764 gnutls_certificate_free_credentials(*credentials
);
770 cupsdLogMessage(CUPSD_LOG_DEBUG
,
771 "cupsdEncryptClient: %d Connection from %s now encrypted.",
772 con
->http
.fd
, con
->http
.hostname
);
774 conn
->credentials
= credentials
;
775 con
->http
.tls
= conn
;
778 #elif defined(HAVE_CDSASSL)
779 OSStatus error
; /* Error info */
780 SSLContextRef conn
; /* New connection */
781 CFArrayRef certificatesArray
; /* Array containing certificates */
782 int allowExpired
; /* Allow expired certificates? */
783 int allowAnyRoot
; /* Allow any root certificate? */
787 error
= SSLNewContext(true, &conn
);
791 certificatesArray
= get_cdsa_server_certs();
793 if (!certificatesArray
)
795 cupsdLogMessage(CUPSD_LOG_ERROR
,
796 "EncryptClient: Could not find signing key in keychain "
797 "\"%s\"", ServerCertificate
);
798 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
802 error
= SSLSetIOFuncs(conn
, _httpReadCDSA
, _httpWriteCDSA
);
805 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
808 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
811 error
= SSLSetPeerDomainName(conn
, ServerName
, strlen(ServerName
) + 1);
813 /* have to do these options before setting server certs */
814 if (!error
&& allowExpired
)
815 error
= SSLSetAllowsExpiredCerts(conn
, true);
817 if (!error
&& allowAnyRoot
)
818 error
= SSLSetAllowsAnyRoot(conn
, true);
821 error
= SSLSetCertificate(conn
, certificatesArray
);
823 if (certificatesArray
)
825 CFRelease(certificatesArray
);
826 certificatesArray
= NULL
;
832 * Perform SSL/TLS handshake
835 while ((error
= SSLHandshake(conn
)) == errSSLWouldBlock
)
841 cupsdLogMessage(CUPSD_LOG_ERROR
,
842 "cupsdEncryptClient: Unable to encrypt connection from %s!",
845 cupsdLogMessage(CUPSD_LOG_ERROR
,
846 "cupsdEncryptClient: CDSA error code is %d", (int)error
);
848 con
->http
.error
= error
;
849 con
->http
.status
= HTTP_ERROR
;
852 SSLDisposeContext(conn
);
857 cupsdLogMessage(CUPSD_LOG_DEBUG
,
858 "cupsdEncryptClient: %d Connection from %s now encrypted.",
859 con
->http
.fd
, con
->http
.hostname
);
861 con
->http
.tls
= conn
;
866 #endif /* HAVE_LIBSSL */
871 * 'cupsdIsCGI()' - Is the resource a CGI script/program?
874 int /* O - 1 = CGI, 0 = file */
875 cupsdIsCGI(cupsd_client_t
*con
, /* I - Client connection */
876 const char *filename
, /* I - Real filename */
877 struct stat
*filestats
, /* I - File information */
878 mime_type_t
*type
) /* I - MIME type */
880 const char *options
; /* Options on URL */
883 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
884 "cupsdIsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
885 con
, filename
, filestats
, type
? type
->super
: "unknown",
886 type
? type
->type
: "unknown");
889 * Get the options, if any...
892 if ((options
= strchr(con
->uri
, '?')) != NULL
)
896 * Check for known types...
899 if (!type
|| strcasecmp(type
->super
, "application"))
901 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdIsCGI: Returning 0...");
905 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
906 (filestats
->st_mode
& 0111))
909 * "application/x-httpd-cgi" is a CGI script.
912 cupsdSetString(&con
->command
, filename
);
914 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
916 cupsdSetString(&con
->options
, options
);
918 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
919 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
920 con
->command
, con
->options
);
925 else if (!strcasecmp(type
->type
, "x-httpd-java"))
928 * "application/x-httpd-java" is a Java servlet.
931 cupsdSetString(&con
->command
, CUPS_JAVA
);
934 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
936 cupsdSetString(&con
->options
, filename
);
938 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
939 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
940 con
->command
, con
->options
);
944 #endif /* HAVE_JAVA */
946 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
949 * "application/x-httpd-perl" is a Perl page.
952 cupsdSetString(&con
->command
, CUPS_PERL
);
955 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
957 cupsdSetString(&con
->options
, filename
);
959 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
960 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
961 con
->command
, con
->options
);
965 #endif /* HAVE_PERL */
967 else if (!strcasecmp(type
->type
, "x-httpd-php"))
970 * "application/x-httpd-php" is a PHP page.
973 cupsdSetString(&con
->command
, CUPS_PHP
);
976 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
978 cupsdSetString(&con
->options
, filename
);
980 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
981 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
982 con
->command
, con
->options
);
986 #endif /* HAVE_PHP */
988 else if (!strcasecmp(type
->type
, "x-httpd-python"))
991 * "application/x-httpd-python" is a Python page.
994 cupsdSetString(&con
->command
, CUPS_PYTHON
);
997 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
999 cupsdSetString(&con
->options
, filename
);
1001 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1002 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
1003 con
->command
, con
->options
);
1007 #endif /* HAVE_PYTHON */
1009 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdIsCGI: Returning 0...");
1016 * 'cupsdReadClient()' - Read data from a client.
1019 int /* O - 1 on success, 0 on error */
1020 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
1022 char line
[32768], /* Line from client... */
1023 operation
[64], /* Operation code from socket */
1024 version
[64], /* HTTP version number string */
1025 locale
[64], /* Locale */
1026 *ptr
; /* Pointer into strings */
1027 int major
, minor
; /* HTTP version numbers */
1028 http_status_t status
; /* Transfer status */
1029 ipp_state_t ipp_state
; /* State of IPP transfer */
1030 int bytes
; /* Number of bytes to POST */
1031 char *filename
; /* Name of file for GET/HEAD */
1032 char buf
[1024]; /* Buffer for real filename */
1033 struct stat filestats
; /* File information */
1034 mime_type_t
*type
; /* MIME type of file */
1035 cupsd_printer_t
*p
; /* Printer */
1036 static unsigned request_id
= 0; /* Request ID for temp files */
1039 status
= HTTP_CONTINUE
;
1041 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1042 "cupsdReadClient: %d, used=%d, file=%d state=%d",
1043 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
1045 if (con
->http
.error
)
1047 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
1048 return (cupsdCloseClient(con
));
1055 * Automatically check for a SSL/TLS handshake...
1060 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
1061 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
1064 * Encrypt this connection...
1067 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1068 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
1071 cupsdEncryptClient(con
);
1075 #endif /* HAVE_SSL */
1077 switch (con
->http
.state
)
1081 * See if we've received a request line...
1084 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
1086 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1087 "cupsdReadClient: httpGets returned EOF...");
1088 return (cupsdCloseClient(con
));
1092 * Ignore blank request lines...
1095 if (line
[0] == '\0')
1099 * Clear other state variables...
1102 httpClearFields(HTTP(con
));
1104 con
->http
.activity
= time(NULL
);
1105 con
->http
.version
= HTTP_1_0
;
1106 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1107 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
1108 con
->http
.data_remaining
= 0;
1109 con
->http
._data_remaining
= 0;
1110 con
->operation
= HTTP_WAITING
;
1113 con
->file_ready
= 0;
1115 con
->username
[0] = '\0';
1116 con
->password
[0] = '\0';
1119 cupsdClearString(&con
->command
);
1120 cupsdClearString(&con
->options
);
1122 if (con
->language
!= NULL
)
1124 cupsLangFree(con
->language
);
1125 con
->language
= NULL
;
1129 * Grab the request line...
1132 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
1135 cupsdLogMessage(CUPSD_LOG_ERROR
,
1136 "Bad request line \"%s\" from %s!", line
,
1137 con
->http
.hostname
);
1138 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1139 return (cupsdCloseClient(con
));
1141 con
->http
.version
= HTTP_0_9
;
1144 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
1146 cupsdLogMessage(CUPSD_LOG_ERROR
,
1147 "Bad request line \"%s\" from %s!", line
,
1148 con
->http
.hostname
);
1149 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1150 return (cupsdCloseClient(con
));
1155 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
1156 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
1157 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1159 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1163 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
1164 return (cupsdCloseClient(con
));
1170 * Handle full URLs in the request line...
1173 if (strcmp(con
->uri
, "*"))
1175 char method
[HTTP_MAX_URI
], /* Method/scheme */
1176 userpass
[HTTP_MAX_URI
], /* Username:password */
1177 hostname
[HTTP_MAX_URI
], /* Hostname */
1178 resource
[HTTP_MAX_URI
]; /* Resource path */
1179 int port
; /* Port number */
1183 * Separate the URI into its components...
1186 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
1187 method
, sizeof(method
),
1188 userpass
, sizeof(userpass
),
1189 hostname
, sizeof(hostname
), &port
,
1190 resource
, sizeof(resource
));
1193 * Only allow URIs with the servername, localhost, or an IP
1197 if (strcmp(method
, "file") &&
1198 strcasecmp(hostname
, ServerName
) &&
1199 strcasecmp(hostname
, "localhost") &&
1200 !isdigit(hostname
[0]))
1203 * Nope, we don't do proxies...
1206 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
1208 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
1209 return (cupsdCloseClient(con
));
1213 * Copy the resource portion back into the URI; both resource and
1214 * con->uri are HTTP_MAX_URI bytes in size...
1217 strcpy(con
->uri
, resource
);
1221 * Process the request...
1224 if (!strcmp(operation
, "GET"))
1225 con
->http
.state
= HTTP_GET
;
1226 else if (!strcmp(operation
, "PUT"))
1227 con
->http
.state
= HTTP_PUT
;
1228 else if (!strcmp(operation
, "POST"))
1229 con
->http
.state
= HTTP_POST
;
1230 else if (!strcmp(operation
, "DELETE"))
1231 con
->http
.state
= HTTP_DELETE
;
1232 else if (!strcmp(operation
, "TRACE"))
1233 con
->http
.state
= HTTP_TRACE
;
1234 else if (!strcmp(operation
, "OPTIONS"))
1235 con
->http
.state
= HTTP_OPTIONS
;
1236 else if (!strcmp(operation
, "HEAD"))
1237 con
->http
.state
= HTTP_HEAD
;
1240 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1241 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1242 return (cupsdCloseClient(con
));
1245 con
->start
= time(NULL
);
1246 con
->operation
= con
->http
.state
;
1248 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d", con
->http
.fd
,
1249 operation
, con
->uri
,
1250 con
->http
.version
/ 100, con
->http
.version
% 100);
1252 con
->http
.status
= HTTP_OK
;
1262 * Parse incoming parameters until the status changes...
1265 status
= httpUpdate(HTTP(con
));
1267 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1269 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1270 return (cupsdCloseClient(con
));
1275 break; /* Anti-compiler-warning-code */
1279 * Handle new transfers...
1282 if (status
== HTTP_OK
)
1284 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1287 * Figure out the locale from the Accept-Language and Content-Type
1291 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1294 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1297 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1300 * Combine language and charset, and trim any extra params in the
1304 snprintf(locale
, sizeof(locale
), "%s.%s",
1305 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1307 if ((ptr
= strchr(locale
, ',')) != NULL
)
1311 snprintf(locale
, sizeof(locale
), "%s.%s",
1312 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1314 con
->language
= cupsLangGet(locale
);
1317 con
->language
= cupsLangGet(DefaultLocale
);
1319 cupsdAuthorize(con
);
1321 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1323 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1325 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1326 con
->http
.version
>= HTTP_1_1
)
1329 * HTTP/1.1 and higher require the "Host:" field...
1332 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1333 return (cupsdCloseClient(con
));
1335 else if (con
->operation
== HTTP_OPTIONS
)
1338 * Do OPTIONS command...
1341 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1343 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1344 return (cupsdCloseClient(con
));
1347 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1348 con
->http
.tls
== NULL
)
1352 * Do encryption stuff...
1355 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1356 return (cupsdCloseClient(con
));
1358 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1359 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1360 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1361 httpPrintf(HTTP(con
), "\r\n");
1363 cupsdEncryptClient(con
);
1365 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1366 return (cupsdCloseClient(con
));
1367 #endif /* HAVE_SSL */
1370 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1371 return (cupsdCloseClient(con
));
1373 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1374 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1375 httpPrintf(HTTP(con
), "\r\n");
1377 else if (!is_path_absolute(con
->uri
))
1380 * Protect against malicious users!
1383 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1384 return (cupsdCloseClient(con
));
1388 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1389 con
->http
.tls
== NULL
)
1393 * Do encryption stuff...
1396 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1397 return (cupsdCloseClient(con
));
1399 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1400 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1401 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1402 httpPrintf(HTTP(con
), "\r\n");
1404 cupsdEncryptClient(con
);
1406 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1407 return (cupsdCloseClient(con
));
1408 #endif /* HAVE_SSL */
1411 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1413 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1414 "cupsdReadClient: Unauthorized request for %s...\n",
1416 cupsdSendError(con
, status
);
1417 return (cupsdCloseClient(con
));
1420 if (con
->http
.expect
&&
1421 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1423 if (con
->http
.expect
== HTTP_CONTINUE
)
1426 * Send 100-continue header...
1429 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1430 return (cupsdCloseClient(con
));
1435 * Send 417-expectation-failed header...
1438 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1439 return (cupsdCloseClient(con
));
1441 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1442 httpPrintf(HTTP(con
), "\r\n");
1446 switch (con
->http
.state
)
1448 case HTTP_GET_SEND
:
1449 if (!strncmp(con
->uri
, "/printers/", 10) &&
1450 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1453 * Send PPD file - get the real printer name since printer
1454 * names are not case sensitive but filenames can be...
1457 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1459 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1460 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1463 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1464 return (cupsdCloseClient(con
));
1470 if ((!strncmp(con
->uri
, "/admin", 6) &&
1471 strncmp(con
->uri
, "/admin/conf/", 12) &&
1472 strncmp(con
->uri
, "/admin/log/", 11)) ||
1473 !strncmp(con
->uri
, "/printers", 9) ||
1474 !strncmp(con
->uri
, "/classes", 8) ||
1475 !strncmp(con
->uri
, "/help", 5) ||
1476 !strncmp(con
->uri
, "/jobs", 5))
1479 * Send CGI output...
1482 if (!strncmp(con
->uri
, "/admin", 6))
1484 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1487 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1489 else if (!strncmp(con
->uri
, "/printers", 9))
1491 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1494 if (con
->uri
[9] && con
->uri
[10])
1495 cupsdSetString(&con
->options
, con
->uri
+ 9);
1497 cupsdSetString(&con
->options
, NULL
);
1499 else if (!strncmp(con
->uri
, "/classes", 8))
1501 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1504 if (con
->uri
[8] && con
->uri
[9])
1505 cupsdSetString(&con
->options
, con
->uri
+ 8);
1507 cupsdSetString(&con
->options
, NULL
);
1509 else if (!strncmp(con
->uri
, "/jobs", 5))
1511 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1514 if (con
->uri
[5] && con
->uri
[6])
1515 cupsdSetString(&con
->options
, con
->uri
+ 5);
1517 cupsdSetString(&con
->options
, NULL
);
1521 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1524 if (con
->uri
[5] && con
->uri
[6])
1525 cupsdSetString(&con
->options
, con
->uri
+ 5);
1527 cupsdSetString(&con
->options
, NULL
);
1530 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1532 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1533 return (cupsdCloseClient(con
));
1536 cupsdLogRequest(con
, HTTP_OK
);
1538 if (con
->http
.version
<= HTTP_1_0
)
1539 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1541 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1542 (strchr(con
->uri
+ 12, '/') ||
1543 strlen(con
->uri
) == 12)) ||
1544 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1545 (strchr(con
->uri
+ 11, '/') ||
1546 strlen(con
->uri
) == 11)))
1549 * GET can only be done to configuration files under
1553 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1554 return (cupsdCloseClient(con
));
1564 if ((filename
= get_file(con
, &filestats
, buf
,
1565 sizeof(buf
))) == NULL
)
1567 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1568 return (cupsdCloseClient(con
));
1573 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1575 if (cupsdIsCGI(con
, filename
, &filestats
, type
))
1578 * Note: con->command and con->options were set by
1582 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1584 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1585 return (cupsdCloseClient(con
));
1588 cupsdLogRequest(con
, HTTP_OK
);
1590 if (con
->http
.version
<= HTTP_1_0
)
1591 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1595 if (!check_if_modified(con
, &filestats
))
1597 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1598 return (cupsdCloseClient(con
));
1603 strcpy(line
, "text/plain");
1605 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1607 if (!cupsdSendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
1608 return (cupsdCloseClient(con
));
1613 case HTTP_POST_RECV
:
1615 * See if the POST request includes a Content-Length field, and if
1616 * so check the length against any limits that are set...
1619 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1620 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1621 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1623 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1624 MaxRequestSize
> 0 &&
1625 con
->http
.data_remaining
> MaxRequestSize
)
1628 * Request too large...
1631 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1632 return (cupsdCloseClient(con
));
1636 else if (con
->http
.data_remaining
< 0)
1639 * Negative content lengths are invalid!
1642 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1643 return (cupsdCloseClient(con
));
1649 * See what kind of POST request this is; for IPP requests the
1650 * content-type field will be "application/ipp"...
1653 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1655 con
->request
= ippNew();
1656 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1657 strncmp(con
->uri
, "/admin/conf/", 12) &&
1658 strncmp(con
->uri
, "/admin/log/", 11)) ||
1659 !strncmp(con
->uri
, "/printers", 9) ||
1660 !strncmp(con
->uri
, "/classes", 8) ||
1661 !strncmp(con
->uri
, "/help", 5) ||
1662 !strncmp(con
->uri
, "/jobs", 5))
1668 if (!strncmp(con
->uri
, "/admin", 6))
1670 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1673 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1675 else if (!strncmp(con
->uri
, "/printers", 9))
1677 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1680 if (con
->uri
[9] && con
->uri
[10])
1681 cupsdSetString(&con
->options
, con
->uri
+ 9);
1683 cupsdSetString(&con
->options
, NULL
);
1685 else if (!strncmp(con
->uri
, "/classes", 8))
1687 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1690 if (con
->uri
[8] && con
->uri
[9])
1691 cupsdSetString(&con
->options
, con
->uri
+ 8);
1693 cupsdSetString(&con
->options
, NULL
);
1695 else if (!strncmp(con
->uri
, "/jobs", 5))
1697 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1700 if (con
->uri
[5] && con
->uri
[6])
1701 cupsdSetString(&con
->options
, con
->uri
+ 5);
1703 cupsdSetString(&con
->options
, NULL
);
1707 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1710 if (con
->uri
[5] && con
->uri
[6])
1711 cupsdSetString(&con
->options
, con
->uri
+ 5);
1713 cupsdSetString(&con
->options
, NULL
);
1716 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1717 "cupsdReadClient: %d command=\"%s\", "
1719 con
->http
.fd
, con
->command
, con
->options
);
1721 if (con
->http
.version
<= HTTP_1_0
)
1722 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1730 if ((filename
= get_file(con
, &filestats
, buf
,
1731 sizeof(buf
))) == NULL
)
1733 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1734 return (cupsdCloseClient(con
));
1739 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1741 if (!cupsdIsCGI(con
, filename
, &filestats
, type
))
1744 * Only POST to CGI's...
1747 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1748 return (cupsdCloseClient(con
));
1753 case HTTP_PUT_RECV
:
1755 * Validate the resource name...
1758 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1759 strchr(con
->uri
+ 12, '/') ||
1760 strlen(con
->uri
) == 12)
1763 * PUT can only be done to configuration files under
1767 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1768 return (cupsdCloseClient(con
));
1774 * See if the PUT request includes a Content-Length field, and if
1775 * so check the length against any limits that are set...
1778 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1779 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1780 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1782 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1783 MaxRequestSize
> 0 &&
1784 con
->http
.data_remaining
> MaxRequestSize
)
1787 * Request too large...
1790 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1791 return (cupsdCloseClient(con
));
1795 else if (con
->http
.data_remaining
< 0)
1798 * Negative content lengths are invalid!
1801 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1802 return (cupsdCloseClient(con
));
1808 * Open a temporary file to hold the request...
1811 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1813 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1815 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1816 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1817 con
->filename
, con
->file
);
1821 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1822 return (cupsdCloseClient(con
));
1825 fchmod(con
->file
, 0640);
1826 fchown(con
->file
, RunUser
, Group
);
1827 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1832 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1833 return (cupsdCloseClient(con
));
1836 if (!strncmp(con
->uri
, "/printers/", 10) &&
1837 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1840 * Send PPD file - get the real printer name since printer
1841 * names are not case sensitive but filenames can be...
1844 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1846 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1847 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1850 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1851 return (cupsdCloseClient(con
));
1857 if ((!strncmp(con
->uri
, "/admin", 6) &&
1858 strncmp(con
->uri
, "/admin/conf/", 12) &&
1859 strncmp(con
->uri
, "/admin/log/", 11)) ||
1860 !strncmp(con
->uri
, "/printers", 9) ||
1861 !strncmp(con
->uri
, "/classes", 8) ||
1862 !strncmp(con
->uri
, "/help", 5) ||
1863 !strncmp(con
->uri
, "/jobs", 5))
1869 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1870 return (cupsdCloseClient(con
));
1872 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1873 return (cupsdCloseClient(con
));
1875 cupsdLogRequest(con
, HTTP_OK
);
1877 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1878 (strchr(con
->uri
+ 12, '/') ||
1879 strlen(con
->uri
) == 12)) ||
1880 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1881 (strchr(con
->uri
+ 11, '/') ||
1882 strlen(con
->uri
) == 11)))
1885 * HEAD can only be done to configuration files under
1889 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1890 return (cupsdCloseClient(con
));
1894 else if ((filename
= get_file(con
, &filestats
, buf
,
1895 sizeof(buf
))) == NULL
)
1897 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1898 return (cupsdCloseClient(con
));
1900 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1902 else if (!check_if_modified(con
, &filestats
))
1904 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1905 return (cupsdCloseClient(con
));
1907 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1915 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1917 strcpy(line
, "text/plain");
1919 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1921 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1922 return (cupsdCloseClient(con
));
1924 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1925 httpGetDateString(filestats
.st_mtime
)) < 0)
1926 return (cupsdCloseClient(con
));
1928 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1929 (unsigned long)filestats
.st_size
) < 0)
1930 return (cupsdCloseClient(con
));
1932 cupsdLogRequest(con
, HTTP_OK
);
1935 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1936 return (cupsdCloseClient(con
));
1938 con
->http
.state
= HTTP_WAITING
;
1942 break; /* Anti-compiler-warning-code */
1948 * Handle any incoming data...
1951 switch (con
->http
.state
)
1953 case HTTP_PUT_RECV
:
1954 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1955 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1956 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1958 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1959 "CHUNKED" : "LENGTH",
1960 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1962 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1963 return (cupsdCloseClient(con
));
1966 con
->bytes
+= bytes
;
1968 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1969 "cupsdReadClient: %d writing %d bytes to %d",
1970 con
->http
.fd
, bytes
, con
->file
);
1972 if (write(con
->file
, line
, bytes
) < bytes
)
1974 cupsdLogMessage(CUPSD_LOG_ERROR
,
1975 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1976 bytes
, con
->filename
, strerror(errno
));
1978 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1979 "cupsdReadClient: Closing data file %d...",
1984 unlink(con
->filename
);
1985 cupsdClearString(&con
->filename
);
1987 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1988 return (cupsdCloseClient(con
));
1992 if (con
->http
.state
== HTTP_WAITING
)
1995 * End of file, see how big it is...
1998 fstat(con
->file
, &filestats
);
2000 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2001 "cupsdReadClient: %d Closing data file %d, size="
2003 con
->http
.fd
, con
->file
,
2004 CUPS_LLCAST filestats
.st_size
);
2009 if (filestats
.st_size
> MaxRequestSize
&&
2013 * Request is too big; remove it and send an error...
2016 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2017 "cupsdReadClient: %d Removing temp file %s",
2018 con
->http
.fd
, con
->filename
);
2019 unlink(con
->filename
);
2020 cupsdClearString(&con
->filename
);
2022 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
2023 return (cupsdCloseClient(con
));
2027 * Install the configuration file...
2030 status
= install_conf_file(con
);
2033 * Return the status to the client...
2036 if (!cupsdSendError(con
, status
))
2037 return (cupsdCloseClient(con
));
2041 case HTTP_POST_RECV
:
2042 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2043 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2044 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2046 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2047 "CHUNKED" : "LENGTH",
2048 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2050 if (con
->request
!= NULL
)
2053 * Grab any request data from the connection...
2056 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2058 cupsdLogMessage(CUPSD_LOG_ERROR
,
2059 "cupsdReadClient: %d IPP Read Error!",
2062 cupsdSendError(con
, HTTP_BAD_REQUEST
);
2063 return (cupsdCloseClient(con
));
2065 else if (ipp_state
!= IPP_DATA
)
2067 if (con
->http
.state
== HTTP_POST_SEND
)
2069 cupsdSendError(con
, HTTP_BAD_REQUEST
);
2070 return (cupsdCloseClient(con
));
2076 con
->bytes
+= ippLength(con
->request
);
2079 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2082 * Create a file as needed for the request data...
2085 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2086 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2088 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2089 con
->filename
, con
->file
);
2093 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
2094 return (cupsdCloseClient(con
));
2097 fchmod(con
->file
, 0640);
2098 fchown(con
->file
, RunUser
, Group
);
2099 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2102 if (con
->http
.state
!= HTTP_POST_SEND
)
2104 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2105 return (cupsdCloseClient(con
));
2108 con
->bytes
+= bytes
;
2110 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2111 "cupsdReadClient: %d writing %d bytes to %d",
2112 con
->http
.fd
, bytes
, con
->file
);
2114 if (write(con
->file
, line
, bytes
) < bytes
)
2116 cupsdLogMessage(CUPSD_LOG_ERROR
,
2117 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2118 bytes
, con
->filename
, strerror(errno
));
2120 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2121 "cupsdReadClient: Closing file %d...",
2126 unlink(con
->filename
);
2127 cupsdClearString(&con
->filename
);
2129 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
2130 return (cupsdCloseClient(con
));
2133 else if (con
->http
.state
== HTTP_POST_RECV
)
2134 return (1); /* ??? */
2135 else if (con
->http
.state
!= HTTP_POST_SEND
)
2136 return (cupsdCloseClient(con
));
2139 if (con
->http
.state
== HTTP_POST_SEND
)
2143 fstat(con
->file
, &filestats
);
2145 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2146 "cupsdReadClient: %d Closing data file %d, "
2147 "size=" CUPS_LLFMT
".",
2148 con
->http
.fd
, con
->file
,
2149 CUPS_LLCAST filestats
.st_size
);
2154 if (filestats
.st_size
> MaxRequestSize
&&
2158 * Request is too big; remove it and send an error...
2161 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2162 "cupsdReadClient: %d Removing temp file %s",
2163 con
->http
.fd
, con
->filename
);
2164 unlink(con
->filename
);
2165 cupsdClearString(&con
->filename
);
2170 * Delete any IPP request data...
2173 ippDelete(con
->request
);
2174 con
->request
= NULL
;
2177 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
2178 return (cupsdCloseClient(con
));
2183 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2185 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
2186 return (cupsdCloseClient(con
));
2189 cupsdLogRequest(con
, HTTP_OK
);
2194 return (cupsdProcessIPPRequest(con
));
2199 break; /* Anti-compiler-warning-code */
2202 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2203 return (cupsdCloseClient(con
));
2210 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2213 int /* O - 1 on success, 0 on failure */
2215 cupsd_client_t
*con
, /* I - Client connection */
2216 char *command
, /* I - Command to run */
2217 char *options
, /* I - Command-line options */
2218 int root
) /* I - Run as root? */
2220 int fd
; /* Standard input file descriptor */
2224 fd
= open(con
->filename
, O_RDONLY
);
2226 fd
= open("/dev/null", O_RDONLY
);
2230 cupsdLogMessage(CUPSD_LOG_ERROR
,
2231 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2232 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2237 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2239 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2243 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2246 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2247 con
->http
.fd
, con
->file
);
2249 if (con
->pipe_pid
== 0)
2252 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2254 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2255 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
2256 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2257 "cupsdSendCommand: Adding fd %d to OutputSet...",
2260 FD_SET(con
->file
, InputSet
);
2261 FD_SET(con
->http
.fd
, OutputSet
);
2263 con
->sent_header
= 0;
2264 con
->file_ready
= 0;
2265 con
->got_fields
= 0;
2273 * 'cupsdSendError()' - Send an error message via HTTP.
2276 int /* O - 1 if successful, 0 otherwise */
2277 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2278 http_status_t code
) /* I - Error code */
2282 * Force client to upgrade for authentication if that is how the
2283 * server is configured...
2286 if (code
== HTTP_UNAUTHORIZED
&&
2287 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2288 strcasecmp(con
->http
.hostname
, "localhost") &&
2291 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2292 "cupsdSendError: Encryption before authentication!");
2293 code
= HTTP_UPGRADE_REQUIRED
;
2295 #endif /* HAVE_SSL */
2298 * Put the request in the access_log file...
2301 cupsdLogRequest(con
, code
);
2303 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2304 con
->http
.fd
, code
, httpStatus(code
));
2307 * To work around bugs in some proxies, don't use Keep-Alive for some
2311 if (code
>= HTTP_BAD_REQUEST
)
2312 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2315 * Send an error message back to the client. If the error code is a
2316 * 400 or 500 series, make sure the message contains some text, too!
2319 if (!cupsdSendHeader(con
, code
, NULL
))
2323 if (code
== HTTP_UPGRADE_REQUIRED
)
2324 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2327 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2329 #endif /* HAVE_SSL */
2331 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2332 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2334 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2338 if (code
>= HTTP_BAD_REQUEST
)
2341 * Send a human-readable error message.
2344 char message
[1024]; /* Message for user */
2345 const char *text
; /* Status-specific text */
2347 if (code
== HTTP_UNAUTHORIZED
)
2348 text
= _cupsLangString(con
->language
,
2349 _("Enter your username and password or the "
2350 "root username and password to access this "
2352 else if (code
== HTTP_UPGRADE_REQUIRED
)
2353 text
= _cupsLangString(con
->language
,
2354 _("You must use a https: URL to access this "
2359 snprintf(message
, sizeof(message
),
2360 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2361 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2364 "\t<META HTTP-EQUIV=\"Content-Type\" "
2365 "CONTENT=\"text/html; charset=utf-8\">\n"
2366 "\t<TITLE>%d %s</TITLE>\n"
2367 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2368 "HREF=\"/cups.css\">\n"
2375 code
, httpStatus(code
), code
, httpStatus(code
), text
);
2377 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2379 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2380 (int)strlen(message
)) < 0)
2382 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2384 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2387 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2390 con
->http
.state
= HTTP_WAITING
;
2397 * 'cupsdSendFile()' - Send a file via HTTP.
2400 int /* O - 0 on failure, 1 on success */
2401 cupsdSendFile(cupsd_client_t
*con
, /* I - Client connection */
2402 http_status_t code
, /* I - HTTP status */
2403 char *filename
, /* I - Filename */
2404 char *type
, /* I - File type */
2405 struct stat
*filestats
)/* O - File information */
2407 con
->file
= open(filename
, O_RDONLY
);
2409 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendFile: %d file=%d", con
->http
.fd
,
2415 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2419 if (!cupsdSendHeader(con
, code
, type
))
2422 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
2423 httpGetDateString(filestats
->st_mtime
)) < 0)
2425 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
2426 CUPS_LLCAST filestats
->st_size
) < 0)
2428 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2431 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
2432 con
->http
.data_remaining
= filestats
->st_size
;
2434 if (con
->http
.data_remaining
<= INT_MAX
)
2435 con
->http
._data_remaining
= con
->http
.data_remaining
;
2437 con
->http
._data_remaining
= INT_MAX
;
2439 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2440 "cupsdSendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
2442 FD_SET(con
->http
.fd
, OutputSet
);
2449 * 'cupsdSendHeader()' - Send an HTTP request.
2452 int /* O - 1 on success, 0 on failure */
2453 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2454 http_status_t code
, /* I - HTTP status code */
2455 char *type
) /* I - MIME type of document */
2458 * Send the HTTP status header...
2461 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2462 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2465 if (code
== HTTP_CONTINUE
)
2468 * 100-continue doesn't send any headers...
2471 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2477 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2480 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2482 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2484 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2486 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2487 KeepAliveTimeout
) < 0)
2490 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2491 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2494 if (code
== HTTP_UNAUTHORIZED
)
2496 int auth_type
; /* Authentication type */
2499 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2500 auth_type
= DefaultAuthType
;
2502 auth_type
= con
->best
->type
;
2504 if (auth_type
!= AUTH_DIGEST
)
2506 if (httpPrintf(HTTP(con
),
2507 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2512 if (httpPrintf(HTTP(con
),
2513 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2514 con
->http
.hostname
) < 0)
2519 if (con
->language
!= NULL
)
2521 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2522 con
->language
->language
) < 0)
2528 if (!strcmp(type
, "text/html"))
2530 if (httpPrintf(HTTP(con
),
2531 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2534 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2543 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2547 cupsdUpdateCGI(void)
2549 char *ptr
, /* Pointer to end of line in buffer */
2550 message
[1024]; /* Pointer to message text */
2551 int loglevel
; /* Log level for message */
2554 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2555 message
, sizeof(message
))) != NULL
)
2556 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2559 if (ptr
== NULL
&& errno
)
2562 * Fatal error on pipe - should never happen!
2565 cupsdLogMessage(CUPSD_LOG_CRIT
,
2566 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2573 * 'cupsdWriteClient()' - Write data to a client as needed.
2576 int /* O - 1 if success, 0 if fail */
2577 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2579 int bytes
; /* Number of bytes written */
2580 char buf
[16385]; /* Data buffer */
2581 char *bufptr
; /* Pointer into buffer */
2582 ipp_state_t ipp_state
; /* IPP state value */
2586 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2587 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2588 "pipe_pid=%d state=%d",
2589 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2593 if (con
->http
.state
!= HTTP_GET_SEND
&&
2594 con
->http
.state
!= HTTP_POST_SEND
)
2597 if (con
->response
!= NULL
)
2599 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2600 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2602 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2604 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2605 "cupsdWriteClient: Read %d bytes from file %d...",
2608 if (con
->pipe_pid
&& !con
->got_fields
)
2611 * Inspect the data for Content-Type and other fields.
2616 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2617 if (*bufptr
== '\n')
2620 * Send line to client...
2623 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2627 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2629 if (!con
->sent_header
)
2632 * Handle redirection and CGI status codes...
2635 if (!strncasecmp(buf
, "Location:", 9))
2636 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2637 else if (!strncasecmp(buf
, "Status:", 7))
2638 cupsdSendError(con
, atoi(buf
+ 7));
2641 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2643 if (con
->http
.version
== HTTP_1_1
)
2645 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2647 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2652 con
->sent_header
= 1;
2655 if (strncasecmp(buf
, "Status:", 7))
2656 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2658 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2665 bytes
-= (bufptr
- buf
);
2666 memmove(buf
, bufptr
, bytes
+ 1);
2670 * See if the line was empty...
2673 if (con
->field_col
== 0)
2674 con
->got_fields
= 1;
2678 else if (*bufptr
!= '\r')
2681 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2682 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2683 con
->http
.fd
, bytes
, con
->got_fields
);
2685 if (bytes
> 0 && !con
->got_fields
)
2688 * Remaining text needs to go out...
2691 httpPrintf(HTTP(con
), "%s", buf
);
2693 con
->http
.activity
= time(NULL
);
2696 else if (bytes
== 0)
2697 con
->http
.activity
= time(NULL
);
2702 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2704 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2705 "cupsdWriteClient: %d Write of %d bytes failed!",
2706 con
->http
.fd
, bytes
);
2708 cupsdCloseClient(con
);
2712 con
->bytes
+= bytes
;
2714 if (con
->http
.state
== HTTP_WAITING
)
2721 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2724 cupsdLogRequest(con
, HTTP_OK
);
2726 httpFlushWrite(HTTP(con
));
2728 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2730 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2732 cupsdCloseClient(con
);
2737 con
->http
.state
= HTTP_WAITING
;
2739 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2740 "cupsdWriteClient: Removing fd %d from OutputSet...",
2743 FD_CLR(con
->http
.fd
, OutputSet
);
2747 if (FD_ISSET(con
->file
, InputSet
))
2749 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2750 "cupsdWriteClient: Removing fd %d from InputSet...",
2752 FD_CLR(con
->file
, InputSet
);
2756 cupsdEndProcess(con
->pipe_pid
, 0);
2758 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2759 "cupsdWriteClient: %d Closing data file %d.",
2760 con
->http
.fd
, con
->file
);
2769 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2770 "cupsdWriteClient: %d Removing temp file %s",
2771 con
->http
.fd
, con
->filename
);
2772 unlink(con
->filename
);
2773 cupsdClearString(&con
->filename
);
2776 if (con
->request
!= NULL
)
2778 ippDelete(con
->request
);
2779 con
->request
= NULL
;
2782 if (con
->response
!= NULL
)
2784 ippDelete(con
->response
);
2785 con
->response
= NULL
;
2788 cupsdClearString(&con
->command
);
2789 cupsdClearString(&con
->options
);
2791 if (!con
->http
.keep_alive
)
2793 cupsdCloseClient(con
);
2799 con
->file_ready
= 0;
2801 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2803 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2804 "cupsdWriteClient: Adding fd %d to InputSet...",
2806 FD_SET(con
->file
, InputSet
);
2810 con
->http
.activity
= time(NULL
);
2817 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2820 static int /* O - 1 if modified since */
2822 cupsd_client_t
*con
, /* I - Client connection */
2823 struct stat
*filestats
) /* I - File information */
2825 char *ptr
; /* Pointer into field */
2826 time_t date
; /* Time/date value */
2827 off_t size
; /* Size/length value */
2832 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2837 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2838 "check_if_modified: %d If-Modified-Since=\"%s\"",
2841 while (*ptr
!= '\0')
2843 while (isspace(*ptr
) || *ptr
== ';')
2846 if (strncasecmp(ptr
, "length=", 7) == 0)
2849 size
= strtoll(ptr
, NULL
, 10);
2851 while (isdigit(*ptr
))
2854 else if (isalpha(*ptr
))
2856 date
= httpGetDateTime(ptr
);
2857 while (*ptr
!= '\0' && *ptr
!= ';')
2862 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2863 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2864 CUPS_LLFMT
" dates=%d,%d",
2865 con
->http
.fd
, CUPS_LLCAST size
,
2866 CUPS_LLCAST filestats
->st_size
, (int)date
,
2867 (int)filestats
->st_mtime
);
2869 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2870 (date
< filestats
->st_mtime
&& date
!= 0) ||
2871 (size
== 0 && date
== 0));
2877 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2878 * required by SSLSetCertificate.
2880 * For now we assumes that there is exactly one SecIdentity in the
2881 * keychain - i.e. there is exactly one matching cert/private key pair.
2882 * In the future we will search a keychain for a SecIdentity matching a
2883 * specific criteria. We also skip the operation of adding additional
2884 * non-signing certs from the keychain to the CFArrayRef.
2886 * To create a self-signed certificate for testing use the certtool.
2887 * Executing the following as root will do it:
2889 * certtool c k=/Library/Keychains/System.keychain
2892 static CFArrayRef
/* O - Array of certificates */
2893 get_cdsa_server_certs(void)
2895 OSStatus err
; /* Error info */
2896 SecKeychainRef kcRef
; /* Keychain reference */
2897 SecIdentitySearchRef srchRef
; /* Search reference */
2898 SecIdentityRef identity
; /* Identity */
2899 CFArrayRef ca
; /* Certificate array */
2906 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2909 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2910 ServerCertificate
, (int)err
);
2914 * Search for "any" identity matching specified key use;
2915 * in this app, we expect there to be exactly one.
2918 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2921 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2922 "Cannot find signing key in keychain \"%s\", error %d",
2923 ServerCertificate
, (int)err
);
2926 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2929 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2930 "Cannot find signing key in keychain \"%s\", error %d",
2931 ServerCertificate
, (int)err
);
2934 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2935 cupsdLogMessage(CUPSD_LOG_ERROR
,
2936 "SecIdentitySearchCopyNext CFTypeID failure!");
2940 * Found one. Place it in a CFArray.
2941 * TBD: snag other (non-identity) certs from keychain and add them
2945 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2948 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2951 CFRelease(identity
);
2962 #endif /* HAVE_CDSASSL */
2966 * 'get_file()' - Get a filename and state info.
2969 static char * /* O - Real filename */
2970 get_file(cupsd_client_t
*con
, /* I - Client connection */
2971 struct stat
*filestats
, /* O - File information */
2972 char *filename
, /* IO - Filename buffer */
2973 int len
) /* I - Buffer length */
2975 int status
; /* Status of filesystem calls */
2976 char *ptr
; /* Pointer info filename */
2977 int plen
; /* Remaining length after pointer */
2981 * Need to add DocumentRoot global...
2984 if (!strncmp(con
->uri
, "/ppd/", 5))
2985 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2986 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2987 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2988 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2990 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2991 strlcpy(filename
, AccessLog
, len
);
2992 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2993 strlcpy(filename
, ErrorLog
, len
);
2994 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2995 strlcpy(filename
, PageLog
, len
);
2999 else if (con
->language
!= NULL
)
3000 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
3003 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3005 if ((ptr
= strchr(filename
, '?')) != NULL
)
3009 * Grab the status for this language; if there isn't a language-specific file
3010 * then fallback to the default one...
3013 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
3016 * Drop the language prefix and try the current directory...
3019 if (strncmp(con
->uri
, "/ppd/", 5) &&
3020 strncmp(con
->uri
, "/admin/conf/", 12) &&
3021 strncmp(con
->uri
, "/admin/log/", 11))
3023 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3025 if ((ptr
= strchr(filename
, '?')) != NULL
)
3028 status
= stat(filename
, filestats
);
3033 * If we're found a directory, get the index.html file instead...
3036 if (!status
&& S_ISDIR(filestats
->st_mode
))
3038 if (filename
[strlen(filename
) - 1] != '/')
3039 strlcat(filename
, "/", len
);
3041 ptr
= filename
+ strlen(filename
);
3042 plen
= len
- (ptr
- filename
);
3044 strlcpy(ptr
, "index.html", plen
);
3045 status
= stat(filename
, filestats
);
3050 strlcpy(ptr
, "index.class", plen
);
3051 status
= stat(filename
, filestats
);
3053 #endif /* HAVE_JAVA */
3058 strlcpy(ptr
, "index.pl", plen
);
3059 status
= stat(filename
, filestats
);
3061 #endif /* HAVE_PERL */
3066 strlcpy(ptr
, "index.php", plen
);
3067 status
= stat(filename
, filestats
);
3069 #endif /* HAVE_PHP */
3074 strlcpy(ptr
, "index.pyc", plen
);
3075 status
= stat(filename
, filestats
);
3080 strlcpy(ptr
, "index.py", plen
);
3081 status
= stat(filename
, filestats
);
3083 #endif /* HAVE_PYTHON */
3086 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3087 con
->http
.fd
, filename
,
3088 status
? -1 : (int)filestats
->st_size
);
3091 con
->http
.data_remaining
= (int)filestats
->st_size
;
3101 * 'install_conf_file()' - Install a configuration file.
3104 static http_status_t
/* O - Status */
3105 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3107 cups_file_t
*in
, /* Input file */
3108 *out
; /* Output file */
3109 char buffer
[1024]; /* Copy buffer */
3110 int bytes
; /* Number of bytes */
3111 char conffile
[1024], /* Configuration filename */
3112 newfile
[1024], /* New config filename */
3113 oldfile
[1024]; /* Old config filename */
3114 struct stat confinfo
; /* Config file info */
3118 * First construct the filenames...
3121 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3122 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3123 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3125 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3128 * Get the owner, group, and permissions of the configuration file.
3129 * If it doesn't exist, assign it to the User and Group in the
3130 * cupsd.conf file with mode 0640 permissions.
3133 if (stat(conffile
, &confinfo
))
3135 confinfo
.st_uid
= User
;
3136 confinfo
.st_gid
= Group
;
3137 confinfo
.st_mode
= ConfigFilePerm
;
3141 * Open the request file and new config file...
3144 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3146 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3147 con
->filename
, strerror(errno
));
3148 return (HTTP_SERVER_ERROR
);
3151 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3154 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3155 newfile
, strerror(errno
));
3156 return (HTTP_SERVER_ERROR
);
3159 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3160 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3163 * Copy from the request to the new config file...
3166 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3167 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3169 cupsdLogMessage(CUPSD_LOG_ERROR
,
3170 "Unable to copy to config file \"%s\" - %s",
3171 newfile
, strerror(errno
));
3177 return (HTTP_SERVER_ERROR
);
3181 * Close the files...
3185 if (cupsFileClose(out
))
3187 cupsdLogMessage(CUPSD_LOG_ERROR
,
3188 "Error file closing config file \"%s\" - %s",
3189 newfile
, strerror(errno
));
3193 return (HTTP_SERVER_ERROR
);
3197 * Remove the request file...
3200 unlink(con
->filename
);
3201 cupsdClearString(&con
->filename
);
3204 * Unlink the old backup, rename the current config file to the backup
3205 * filename, and rename the new config file to the config file name...
3208 if (unlink(oldfile
))
3209 if (errno
!= ENOENT
)
3211 cupsdLogMessage(CUPSD_LOG_ERROR
,
3212 "Unable to remove backup config file \"%s\" - %s",
3213 oldfile
, strerror(errno
));
3217 return (HTTP_SERVER_ERROR
);
3220 if (rename(conffile
, oldfile
))
3221 if (errno
!= ENOENT
)
3223 cupsdLogMessage(CUPSD_LOG_ERROR
,
3224 "Unable to rename old config file \"%s\" - %s",
3225 conffile
, strerror(errno
));
3229 return (HTTP_SERVER_ERROR
);
3232 if (rename(newfile
, conffile
))
3234 cupsdLogMessage(CUPSD_LOG_ERROR
,
3235 "Unable to rename new config file \"%s\" - %s",
3236 newfile
, strerror(errno
));
3238 rename(oldfile
, conffile
);
3241 return (HTTP_SERVER_ERROR
);
3245 * If the cupsd.conf file was updated, set the NeedReload flag...
3248 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3249 NeedReload
= RELOAD_CUPSD
;
3251 NeedReload
= RELOAD_ALL
;
3253 ReloadTime
= time(NULL
);
3256 * Return that the file was created successfully...
3259 return (HTTP_CREATED
);
3264 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3267 static int /* O - 0 if relative, 1 if absolute */
3268 is_path_absolute(const char *path
) /* I - Input path */
3271 * Check for a leading slash...
3278 * Check for "/.." in the path...
3281 while ((path
= strstr(path
, "/..")) != NULL
)
3283 if (!path
[3] || path
[3] == '/')
3290 * If we haven't found any relative paths, return 1 indicating an
3300 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3304 make_certificate(void)
3306 gnutls_x509_crt crt
; /* Self-signed certificate */
3307 gnutls_x509_privkey key
; /* Encryption key */
3308 cups_lang_t
*language
; /* Default language info */
3309 cups_file_t
*fp
; /* Key/cert file */
3310 unsigned char buffer
[8192]; /* Buffer for x509 data */
3311 size_t bytes
; /* Number of bytes of data */
3312 unsigned char serial
[4]; /* Serial number buffer */
3313 time_t curtime
; /* Current time */
3314 int result
; /* Result of GNU TLS calls */
3318 * Create the encryption key...
3321 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating server key...");
3323 gnutls_x509_privkey_init(&key
);
3324 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3330 bytes
= sizeof(buffer
);
3332 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3333 buffer
, &bytes
)) < 0)
3335 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export server key - %s",
3336 gnutls_strerror(result
));
3337 gnutls_x509_privkey_deinit(key
);
3340 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3342 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3345 cupsdLogMessage(CUPSD_LOG_INFO
, "Created server key file \"%s\"...",
3350 cupsdLogMessage(CUPSD_LOG_ERROR
,
3351 "Unable to create server key file \"%s\" - %s",
3352 ServerKey
, strerror(errno
));
3353 gnutls_x509_privkey_deinit(key
);
3358 * Create the self-signed certificate...
3361 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed certificate...");
3363 language
= cupsLangDefault();
3364 curtime
= time(NULL
);
3365 serial
[0] = curtime
>> 24;
3366 serial
[1] = curtime
>> 16;
3367 serial
[2] = curtime
>> 8;
3368 serial
[3] = curtime
;
3370 gnutls_x509_crt_init(&crt
);
3371 if (strlen(language
->language
) == 5)
3372 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3373 language
->language
+ 3, 2);
3375 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3377 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3378 ServerName
, strlen(ServerName
));
3379 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3380 ServerName
, strlen(ServerName
));
3381 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3383 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3385 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3387 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3388 ServerAdmin
, strlen(ServerAdmin
));
3389 gnutls_x509_crt_set_key(crt
, key
);
3390 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3391 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3392 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3393 gnutls_x509_crt_set_ca_status(crt
, 0);
3394 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3396 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3397 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3398 gnutls_x509_crt_set_version(crt
, 3);
3400 bytes
= sizeof(buffer
);
3401 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3402 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3404 gnutls_x509_crt_sign(crt
, crt
, key
);
3410 bytes
= sizeof(buffer
);
3411 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3412 buffer
, &bytes
)) < 0)
3413 cupsdLogMessage(CUPSD_LOG_ERROR
,
3414 "Unable to export server certificate - %s",
3415 gnutls_strerror(result
));
3416 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3418 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3421 cupsdLogMessage(CUPSD_LOG_INFO
,
3422 "Created 10-year server certificate file \"%s\"...",
3426 cupsdLogMessage(CUPSD_LOG_ERROR
,
3427 "Unable to create server certificate file \"%s\" - %s",
3428 ServerCertificate
, strerror(errno
));
3434 gnutls_x509_crt_deinit(crt
);
3435 gnutls_x509_privkey_deinit(key
);
3437 #endif /* HAVE_GNUTLS */
3441 * 'pipe_command()' - Pipe the output of a command to the remote client.
3444 static int /* O - Process ID */
3445 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3446 int infile
, /* I - Standard input for command */
3447 int *outfile
, /* O - Standard output for command */
3448 char *command
, /* I - Command to run */
3449 char *options
, /* I - Options for command */
3450 int root
) /* I - Run as root? */
3452 int i
; /* Looping var */
3453 int pid
; /* Process ID */
3454 char *commptr
, /* Command string pointer */
3455 commch
; /* Command string character */
3456 char *uriptr
; /* URI string pointer */
3457 int fds
[2]; /* Pipe FDs */
3458 int argc
; /* Number of arguments */
3459 int envc
; /* Number of environment variables */
3460 char argbuf
[10240], /* Argument buffer */
3461 *argv
[100], /* Argument strings */
3462 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3463 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3464 content_type
[1024], /* CONTENT_TYPE environment variable */
3465 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3466 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3467 lang
[1024], /* LANG environment variable */
3468 path_info
[1024], /* PATH_INFO environment variable */
3469 *query_string
, /* QUERY_STRING env variable */
3470 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3471 remote_host
[1024], /* REMOTE_HOST environment variable */
3472 remote_user
[1024], /* REMOTE_USER environment variable */
3473 script_name
[1024], /* SCRIPT_NAME environment variable */
3474 server_name
[1024], /* SERVER_NAME environment variable */
3475 server_port
[1024]; /* SERVER_PORT environment variable */
3479 * Parse a copy of the options string, which is of the form:
3481 * argument+argument+argument
3482 * ?argument+argument+argument
3483 * param=value¶m=value
3484 * ?param=value¶m=value
3485 * /name?argument+argument+argument
3486 * /name?param=value¶m=value
3488 * If the string contains an "=" character after the initial name,
3489 * then we treat it as a HTTP GET form request and make a copy of
3490 * the remaining string for the environment variable.
3492 * The string is always parsed out as command-line arguments, to
3493 * be consistent with Apache...
3496 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3497 "pipe_command: command=\"%s\", options=\"%s\"",
3501 query_string
= NULL
;
3504 strlcpy(argbuf
, options
, sizeof(argbuf
));
3508 if (argbuf
[0] == '/')
3511 * Found some trailing path information, set PATH_INFO...
3514 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3515 commptr
= argbuf
+ strlen(argbuf
);
3519 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3525 path_info
[0] = '\0';
3528 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3531 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3538 argv
[argc
++] = commptr
;
3540 for (; *commptr
&& argc
< 99; commptr
++)
3543 * Break arguments whenever we see a + or space...
3546 if (*commptr
== ' ' || *commptr
== '+')
3548 while (*commptr
== ' ' || *commptr
== '+')
3552 * If we don't have a blank string, save it as another argument...
3557 argv
[argc
] = commptr
;
3563 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3564 isxdigit(commptr
[2] & 255))
3567 * Convert the %xx notation to the individual character.
3570 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3571 *commptr
= (commptr
[1] - '0') << 4;
3573 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3575 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3576 *commptr
|= commptr
[2] - '0';
3578 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3580 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3583 * Check for a %00 and break if that is the case...
3595 * Setup the environment variables as needed...
3599 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3601 strcpy(lang
, "LANG=C");
3603 strcpy(remote_addr
, "REMOTE_ADDR=");
3604 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3605 sizeof(remote_addr
) - 12);
3607 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3608 con
->http
.hostname
);
3610 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3611 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3614 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3616 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3619 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3621 envp
[envc
++] = lang
;
3622 envp
[envc
++] = "REDIRECT_STATUS=1";
3623 envp
[envc
++] = server_name
;
3624 envp
[envc
++] = server_port
;
3625 envp
[envc
++] = remote_addr
;
3626 envp
[envc
++] = remote_host
;
3627 envp
[envc
++] = script_name
;
3630 envp
[envc
++] = path_info
;
3632 if (con
->username
[0])
3634 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3636 envp
[envc
++] = remote_user
;
3639 if (con
->http
.version
== HTTP_1_1
)
3640 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3641 else if (con
->http
.version
== HTTP_1_0
)
3642 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3644 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3646 if (con
->http
.cookie
)
3648 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3650 envp
[envc
++] = http_cookie
;
3653 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3655 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3656 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3657 envp
[envc
++] = http_user_agent
;
3660 if (con
->operation
== HTTP_GET
)
3662 for (i
= 0; i
< argc
; i
++)
3663 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3665 envp
[envc
++] = "REQUEST_METHOD=GET";
3670 * Add GET form variables after ?...
3673 envp
[envc
++] = query_string
;
3678 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
, con
->bytes
);
3679 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3680 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3682 envp
[envc
++] = "REQUEST_METHOD=POST";
3683 envp
[envc
++] = content_length
;
3684 envp
[envc
++] = content_type
;
3688 * Tell the CGI if we are using encryption...
3691 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3692 envp
[envc
++] = "HTTPS=ON";
3695 * Terminate the environment array...
3700 if (LogLevel
== CUPSD_LOG_DEBUG2
)
3702 for (i
= 0; i
< argc
; i
++)
3703 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3704 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
3705 for (i
= 0; i
< envc
; i
++)
3706 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3707 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
3711 * Create a pipe for the output...
3714 if (cupsdOpenPipe(fds
))
3716 cupsdClearString(&query_string
);
3718 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
3719 argv
[0], strerror(errno
));
3724 * Then execute the command...
3727 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3728 -1, root
, &pid
) < 0)
3731 * Error - can't fork!
3734 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3737 cupsdClosePipe(fds
);
3743 * Fork successful - return the PID...
3746 if (con
->username
[0])
3747 cupsdAddCert(pid
, con
->username
);
3749 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3755 cupsdClearString(&query_string
);
3762 * End of "$Id: client.c 5225 2006-03-04 12:28:10Z mike $".