]> git.ipfire.org Git - thirdparty/cups.git/blame - scheduler/client.c
Merge changes from CUPS 1.5svn-r9136.
[thirdparty/cups.git] / scheduler / client.c
CommitLineData
ef416fc2 1/*
b19ccc9e 2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
ef416fc2 3 *
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
5 *
f8b3a85b 6 * Copyright 2007-2010 by Apple Inc.
f7deaa1a 7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
9 * This file contains Kerberos support code, copyright 2006 by
10 * Jelmer Vernooij.
ef416fc2 11 *
12 * These coded instructions, statements, and computer programs are the
bc44d920 13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
ef416fc2 17 *
18 * Contents:
19 *
94da7e34
MS
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and
29 * programs.
30 * cupsdWriteClient() - Write data to a client as needed.
31 * check_if_modified() - Decode an "If-Modified-Since" line.
32 * compare_clients() - Compare two client connections.
33 * data_ready() - Check whether data is available from a client.
34 * encrypt_client() - Enable encryption for the client...
35 * get_cdsa_certificate() - Get a SSL/TLS certificate from the System
36 * keychain.
37 * get_file() - Get a filename and state info.
38 * install_conf_file() - Install a configuration file.
39 * is_cgi() - Is the resource a CGI script/program?
40 * is_path_absolute() - Is a path absolute and free of relative elements
41 * (i.e. "..").
42 * make_certificate() - Make a self-signed SSL/TLS certificate.
43 * pipe_command() - Pipe the output of a command to the remote client.
e07d4801 44 * valid_host() - Is the Host: field valid?
94da7e34
MS
45 * write_file() - Send a file via HTTP.
46 * write_pipe() - Flag that data is available on the CGI pipe.
ef416fc2 47 */
48
49/*
50 * Include necessary headers...
51 */
52
ef416fc2 53#include "cupsd.h"
54
55#ifdef HAVE_CDSASSL
56# include <Security/Security.h>
b86bc4cf 57# ifdef HAVE_SECIDENTITYSEARCHPRIV_H
58# include <Security/SecIdentitySearchPriv.h>
59# else /* Declare prototype for function in that header... */
60extern OSStatus SecIdentitySearchCreateWithPolicy(SecPolicyRef policy,
61 CFStringRef idString, CSSM_KEYUSE keyUsage,
62 CFTypeRef keychainOrArray,
63 Boolean returnOnlyValidIdentities,
64 SecIdentitySearchRef* searchRef);
65# endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
66# ifdef HAVE_SECPOLICYPRIV_H
67# include <Security/SecPolicyPriv.h>
68# else /* Declare prototype for function in that header... */
69extern OSStatus SecPolicySetValue(SecPolicyRef policyRef,
70 const CSSM_DATA *value);
71# endif /* HAVE_SECPOLICYPRIV_H */
ed486911 72# ifdef HAVE_SECBASEPRIV_H
73# include <Security/SecBasePriv.h>
b86bc4cf 74# else /* Declare prototype for function in that header... */
75extern const char *cssmErrorString(int error);
ed486911 76# endif /* HAVE_SECBASEPRIV_H */
ef416fc2 77#endif /* HAVE_CDSASSL */
b86bc4cf 78
4744bd90 79#ifdef HAVE_GNUTLS
80# include <gnutls/x509.h>
81#endif /* HAVE_GNUTLS */
ef416fc2 82
749b1e90
MS
83#ifdef HAVE_TCPD_H
84# include <tcpd.h>
85#endif /* HAVE_TCPD_H */
86
ef416fc2 87
88/*
89 * Local functions...
90 */
91
92static int check_if_modified(cupsd_client_t *con,
93 struct stat *filestats);
3dfe78b3
MS
94static int compare_clients(cupsd_client_t *a, cupsd_client_t *b,
95 void *data);
ee571f26 96static int data_ready(cupsd_client_t *con);
80ca4592 97#ifdef HAVE_SSL
e1d6a774 98static int encrypt_client(cupsd_client_t *con);
80ca4592 99#endif /* HAVE_SSL */
ef416fc2 100#ifdef HAVE_CDSASSL
b86bc4cf 101static CFArrayRef get_cdsa_certificate(cupsd_client_t *con);
ef416fc2 102#endif /* HAVE_CDSASSL */
f7deaa1a 103static char *get_file(cupsd_client_t *con, struct stat *filestats,
ef416fc2 104 char *filename, int len);
105static http_status_t install_conf_file(cupsd_client_t *con);
e1d6a774 106static int is_cgi(cupsd_client_t *con, const char *filename,
107 struct stat *filestats, mime_type_t *type);
ef416fc2 108static int is_path_absolute(const char *path);
8ca02f3c 109#ifdef HAVE_SSL
b86bc4cf 110static int make_certificate(cupsd_client_t *con);
8ca02f3c 111#endif /* HAVE_SSL */
ef416fc2 112static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
113 char *command, char *options, int root);
e07d4801 114static int valid_host(cupsd_client_t *con);
a74454a7 115static int write_file(cupsd_client_t *con, http_status_t code,
116 char *filename, char *type,
117 struct stat *filestats);
f899b121 118static void write_pipe(cupsd_client_t *con);
ef416fc2 119
120
121/*
122 * 'cupsdAcceptClient()' - Accept a new client.
123 */
124
125void
126cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
127{
ef416fc2 128 int count; /* Count of connections on a host */
129 int val; /* Parameter value */
bd7854cb 130 cupsd_client_t *con, /* New client pointer */
131 *tempcon; /* Temporary client pointer */
ef416fc2 132 http_addrlist_t *addrlist, /* List of adddresses for host */
133 *addr; /* Current address */
134 socklen_t addrlen; /* Length of address */
135 char *hostname; /* Hostname for address */
136 http_addr_t temp; /* Temporary address variable */
137 static time_t last_dos = 0; /* Time of last DoS attack */
749b1e90
MS
138#ifdef HAVE_TCPD_H
139 struct request_info wrap_req; /* TCP wrappers request information */
140#endif /* HAVE_TCPD_H */
ef416fc2 141
142
143 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1 144 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
bd7854cb 145 lis, lis->fd, cupsArrayCount(Clients));
ef416fc2 146
147 /*
148 * Make sure we don't have a full set of clients already...
149 */
150
bd7854cb 151 if (cupsArrayCount(Clients) == MaxClients)
ef416fc2 152 return;
153
154 /*
155 * Get a pointer to the next available client...
156 */
157
bd7854cb 158 if (!Clients)
159 Clients = cupsArrayNew(NULL, NULL);
160
161 if (!Clients)
91c84a35
MS
162 {
163 cupsdLogMessage(CUPSD_LOG_ERROR,
3dfe78b3
MS
164 "Unable to allocate memory for clients array!");
165 cupsdPauseListening();
166 return;
167 }
168
169 if (!ActiveClients)
170 ActiveClients = cupsArrayNew((cups_array_func_t)compare_clients, NULL);
171
172 if (!ActiveClients)
173 {
174 cupsdLogMessage(CUPSD_LOG_ERROR,
175 "Unable to allocate memory for active clients array!");
91c84a35 176 cupsdPauseListening();
bd7854cb 177 return;
91c84a35 178 }
bd7854cb 179
91c84a35
MS
180 if ((con = calloc(1, sizeof(cupsd_client_t))) == NULL)
181 {
182 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to allocate memory for client!");
183 cupsdPauseListening();
184 return;
185 }
ef416fc2 186
ef416fc2 187 con->http.activity = time(NULL);
188 con->file = -1;
189 con->http.hostaddr = &(con->clientaddr);
190
191 /*
192 * Accept the client and get the remote address...
193 */
194
195 addrlen = sizeof(http_addr_t);
196
197 if ((con->http.fd = accept(lis->fd, (struct sockaddr *)con->http.hostaddr,
198 &addrlen)) < 0)
199 {
76cd9e37
MS
200 if (errno == ENFILE || errno == EMFILE)
201 cupsdPauseListening();
202
ef416fc2 203 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
204 strerror(errno));
bd7854cb 205 free(con);
76cd9e37 206
ef416fc2 207 return;
208 }
209
210#ifdef AF_INET6
211 if (lis->address.addr.sa_family == AF_INET6)
212 {
213 /*
214 * Save the connected port number...
215 */
216
217 con->http.hostaddr->ipv6.sin6_port = lis->address.ipv6.sin6_port;
218
219 /*
220 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
221 * can more easily use...
222 */
223
224 if (con->http.hostaddr->ipv6.sin6_addr.s6_addr32[0] == 0 &&
225 con->http.hostaddr->ipv6.sin6_addr.s6_addr32[1] == 0 &&
226 ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2]) == 0xffff)
227 con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2] = 0;
228 }
229 else
230#endif /* AF_INET6 */
231 if (lis->address.addr.sa_family == AF_INET)
232 con->http.hostaddr->ipv4.sin_port = lis->address.ipv4.sin_port;
233
234 /*
235 * Check the number of clients on the same address...
236 */
237
bd7854cb 238 for (count = 0, tempcon = (cupsd_client_t *)cupsArrayFirst(Clients);
239 tempcon;
240 tempcon = (cupsd_client_t *)cupsArrayNext(Clients))
241 if (httpAddrEqual(tempcon->http.hostaddr, con->http.hostaddr))
ef416fc2 242 {
243 count ++;
244 if (count >= MaxClientsPerHost)
245 break;
246 }
247
248 if (count >= MaxClientsPerHost)
249 {
250 if ((time(NULL) - last_dos) >= 60)
251 {
252 last_dos = time(NULL);
253 cupsdLogMessage(CUPSD_LOG_WARN,
bd7854cb 254 "Possible DoS attack - more than %d clients connecting "
255 "from %s!",
749b1e90
MS
256 MaxClientsPerHost,
257 httpAddrString(con->http.hostaddr, con->http.hostname,
258 sizeof(con->http.hostname)));
ef416fc2 259 }
260
261#ifdef WIN32
262 closesocket(con->http.fd);
263#else
264 close(con->http.fd);
265#endif /* WIN32 */
266
bd7854cb 267 free(con);
ef416fc2 268 return;
269 }
270
271 /*
272 * Get the hostname or format the IP address as needed...
273 */
274
275 if (httpAddrLocalhost(con->http.hostaddr))
276 {
277 /*
278 * Map accesses from the loopback interface to "localhost"...
279 */
280
281 strlcpy(con->http.hostname, "localhost", sizeof(con->http.hostname));
282 hostname = con->http.hostname;
283 }
284 else
285 {
286 /*
287 * Map accesses from the same host to the server name.
288 */
289
d1c13e16 290 if (HostNameLookups)
ef416fc2 291 hostname = httpAddrLookup(con->http.hostaddr, con->http.hostname,
292 sizeof(con->http.hostname));
293 else
294 {
295 hostname = NULL;
296 httpAddrString(con->http.hostaddr, con->http.hostname,
297 sizeof(con->http.hostname));
298 }
299 }
300
301 if (hostname == NULL && HostNameLookups == 2)
302 {
303 /*
304 * Can't have an unresolved IP address with double-lookups enabled...
305 */
306
ef416fc2 307#ifdef WIN32
308 closesocket(con->http.fd);
309#else
310 close(con->http.fd);
311#endif /* WIN32 */
312
313 cupsdLogMessage(CUPSD_LOG_WARN,
314 "Name lookup failed - connection from %s closed!",
315 con->http.hostname);
bd7854cb 316
317 free(con);
ef416fc2 318 return;
319 }
320
321 if (HostNameLookups == 2)
322 {
323 /*
324 * Do double lookups as needed...
325 */
326
749b1e90
MS
327 if ((addrlist = httpAddrGetList(con->http.hostname, AF_UNSPEC, NULL))
328 != NULL)
ef416fc2 329 {
330 /*
331 * See if the hostname maps to the same IP address...
332 */
333
334 for (addr = addrlist; addr; addr = addr->next)
335 if (httpAddrEqual(con->http.hostaddr, &(addr->addr)))
336 break;
337 }
338 else
339 addr = NULL;
340
341 httpAddrFreeList(addrlist);
342
343 if (!addr)
344 {
345 /*
346 * Can't have a hostname that doesn't resolve to the same IP address
347 * with double-lookups enabled...
348 */
349
ef416fc2 350#ifdef WIN32
351 closesocket(con->http.fd);
352#else
353 close(con->http.fd);
354#endif /* WIN32 */
355
356 cupsdLogMessage(CUPSD_LOG_WARN,
357 "IP lookup failed - connection from %s closed!",
358 con->http.hostname);
bd7854cb 359 free(con);
ef416fc2 360 return;
361 }
362 }
363
749b1e90
MS
364#ifdef HAVE_TCPD_H
365 /*
366 * See if the connection is denied by TCP wrappers...
367 */
368
369 request_init(&wrap_req, RQ_DAEMON, "cupsd", RQ_FILE, con->http.fd, NULL);
370 fromhost(&wrap_req);
371
372 if (!hosts_access(&wrap_req))
373 {
749b1e90
MS
374#ifdef WIN32
375 closesocket(con->http.fd);
376#else
377 close(con->http.fd);
378#endif /* WIN32 */
379
380 cupsdLogMessage(CUPSD_LOG_WARN,
381 "Connection from %s refused by /etc/hosts.allow and "
382 "/etc/hosts.deny rules.", con->http.hostname);
383 free(con);
384 return;
385 }
386#endif /* HAVE_TCPD_H */
387
ef416fc2 388#ifdef AF_INET6
389 if (con->http.hostaddr->addr.sa_family == AF_INET6)
390 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s:%d (IPv6)",
391 con->http.fd, con->http.hostname,
392 ntohs(con->http.hostaddr->ipv6.sin6_port));
393 else
394#endif /* AF_INET6 */
395#ifdef AF_LOCAL
396 if (con->http.hostaddr->addr.sa_family == AF_LOCAL)
397 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s (Domain)",
398 con->http.fd, con->http.hostname);
399 else
400#endif /* AF_LOCAL */
401 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s:%d (IPv4)",
402 con->http.fd, con->http.hostname,
403 ntohs(con->http.hostaddr->ipv4.sin_port));
404
405 /*
406 * Get the local address the client connected to...
407 */
408
409 addrlen = sizeof(temp);
410 if (getsockname(con->http.fd, (struct sockaddr *)&temp, &addrlen))
411 {
412 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get local address - %s",
413 strerror(errno));
414
415 strcpy(con->servername, "localhost");
416 con->serverport = LocalPort;
417 }
418 else
419 {
420#ifdef AF_INET6
421 if (temp.addr.sa_family == AF_INET6)
422 {
e07d4801 423 if (httpAddrLocalhost(&temp))
0af14961 424 strlcpy(con->servername, "localhost", sizeof(con->servername));
f11a948a 425 else if (HostNameLookups || RemotePort)
e07d4801 426 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
b19ccc9e
MS
427 else
428 httpAddrString(&temp, con->servername, sizeof(con->servername));
429
ef416fc2 430 con->serverport = ntohs(lis->address.ipv6.sin6_port);
431 }
432 else
433#endif /* AF_INET6 */
434 if (temp.addr.sa_family == AF_INET)
435 {
e07d4801 436 if (httpAddrLocalhost(&temp))
0af14961 437 strlcpy(con->servername, "localhost", sizeof(con->servername));
f11a948a 438 else if (HostNameLookups || RemotePort)
e07d4801 439 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
b19ccc9e
MS
440 else
441 httpAddrString(&temp, con->servername, sizeof(con->servername));
442
ef416fc2 443 con->serverport = ntohs(lis->address.ipv4.sin_port);
444 }
445 else
446 {
447 strcpy(con->servername, "localhost");
448 con->serverport = LocalPort;
449 }
450 }
451
bd7854cb 452 cupsArrayAdd(Clients, con);
453
ef416fc2 454 /*
b9faaae1
MS
455 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
456 * loopback interface. Since we write large buffers when sending print files
457 * and requests there shouldn't be any performance penalty for this...
ef416fc2 458 */
459
460 val = 1;
f7deaa1a 461 setsockopt(con->http.fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
ef416fc2 462
463 /*
464 * Close this file on all execs...
465 */
466
467 fcntl(con->http.fd, F_SETFD, fcntl(con->http.fd, F_GETFD) | FD_CLOEXEC);
468
469 /*
b9faaae1 470 * Add the socket to the server select.
ef416fc2 471 */
472
f7deaa1a 473 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 474
ef416fc2 475 /*
476 * Temporarily suspend accept()'s until we lose a client...
477 */
478
bd7854cb 479 if (cupsArrayCount(Clients) == MaxClients)
ef416fc2 480 cupsdPauseListening();
481
482#ifdef HAVE_SSL
483 /*
484 * See if we are connecting on a secure port...
485 */
486
487 if (lis->encryption == HTTP_ENCRYPT_ALWAYS)
488 {
489 /*
490 * https connection; go secure...
491 */
492
493 con->http.encryption = HTTP_ENCRYPT_ALWAYS;
494
411affcf 495 if (!encrypt_client(con))
496 cupsdCloseClient(con);
ef416fc2 497 }
498 else
499 con->auto_ssl = 1;
500#endif /* HAVE_SSL */
501}
502
503
504/*
505 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
506 */
507
508void
509cupsdCloseAllClients(void)
510{
bd7854cb 511 cupsd_client_t *con; /* Current client */
512
513
b9faaae1
MS
514 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCloseAllClients() Clients=%d",
515 cupsArrayCount(Clients));
516
bd7854cb 517 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
518 con;
519 con = (cupsd_client_t *)cupsArrayNext(Clients))
49d87452
MS
520 if (cupsdCloseClient(con))
521 cupsdCloseClient(con);
ef416fc2 522}
523
524
525/*
526 * 'cupsdCloseClient()' - Close a remote client.
527 */
528
529int /* O - 1 if partial close, 0 if fully closed */
530cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
531{
532 int partial; /* Do partial close for SSL? */
533#ifdef HAVE_LIBSSL
534 SSL_CTX *context; /* Context for encryption */
535 SSL *conn; /* Connection for encryption */
536 unsigned long error; /* Error code */
537#elif defined(HAVE_GNUTLS)
89d46774 538 http_tls_t *conn; /* TLS connection information */
539 int error; /* Error code */
ef416fc2 540 gnutls_certificate_server_credentials *credentials;
541 /* TLS credentials */
89d46774 542# elif defined(HAVE_CDSASSL)
543 http_tls_t *conn; /* CDSA connection information */
ef416fc2 544#endif /* HAVE_LIBSSL */
545
546
f11a948a 547 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdCloseClient: %d", con->http.fd);
ef416fc2 548
549 /*
550 * Flush pending writes before closing...
551 */
552
553 httpFlushWrite(HTTP(con));
554
555 partial = 0;
556
557#ifdef HAVE_SSL
558 /*
559 * Shutdown encryption as needed...
560 */
561
562 if (con->http.tls)
563 {
564 partial = 1;
565
566# ifdef HAVE_LIBSSL
567 conn = (SSL *)(con->http.tls);
568 context = SSL_get_SSL_CTX(conn);
569
570 switch (SSL_shutdown(conn))
571 {
572 case 1 :
c934a06c
MS
573 cupsdLogMessage(CUPSD_LOG_DEBUG,
574 "SSL shutdown successful!");
ef416fc2 575 break;
576 case -1 :
577 cupsdLogMessage(CUPSD_LOG_ERROR,
c934a06c 578 "Fatal error during SSL shutdown!");
ef416fc2 579 default :
580 while ((error = ERR_get_error()) != 0)
c934a06c 581 cupsdLogMessage(CUPSD_LOG_ERROR, "SSL shutdown failed: %s",
ef416fc2 582 ERR_error_string(error, NULL));
583 break;
584 }
585
586 SSL_CTX_free(context);
587 SSL_free(conn);
588
589# elif defined(HAVE_GNUTLS)
590 conn = (http_tls_t *)(con->http.tls);
591 credentials = (gnutls_certificate_server_credentials *)(conn->credentials);
592
593 error = gnutls_bye(conn->session, GNUTLS_SHUT_WR);
594 switch (error)
595 {
596 case GNUTLS_E_SUCCESS:
c934a06c
MS
597 cupsdLogMessage(CUPSD_LOG_DEBUG,
598 "SSL shutdown successful!");
ef416fc2 599 break;
600 default:
601 cupsdLogMessage(CUPSD_LOG_ERROR,
c934a06c 602 "SSL shutdown failed: %s", gnutls_strerror(error));
ef416fc2 603 break;
604 }
605
606 gnutls_deinit(conn->session);
607 gnutls_certificate_free_credentials(*credentials);
608 free(credentials);
609 free(conn);
610
611# elif defined(HAVE_CDSASSL)
89d46774 612 conn = (http_tls_t *)(con->http.tls);
613
614 while (SSLClose(conn->session) == errSSLWouldBlock)
b423cd4c 615 usleep(1000);
616
89d46774 617 SSLDisposeContext(conn->session);
618
619 if (conn->certsArray)
620 CFRelease(conn->certsArray);
621
622 free(conn);
ef416fc2 623# endif /* HAVE_LIBSSL */
624
625 con->http.tls = NULL;
626 }
627#endif /* HAVE_SSL */
628
629 if (con->pipe_pid != 0)
630 {
631 /*
632 * Stop any CGI process...
633 */
634
ef416fc2 635 cupsdEndProcess(con->pipe_pid, 1);
636 con->pipe_pid = 0;
637 }
638
639 if (con->file >= 0)
640 {
f7deaa1a 641 cupsdRemoveSelect(con->file);
ef416fc2 642
ef416fc2 643 close(con->file);
644 con->file = -1;
645 }
646
647 /*
648 * Close the socket and clear the file from the input set for select()...
649 */
650
3dfe78b3 651 if (con->http.fd >= 0)
ef416fc2 652 {
3dfe78b3
MS
653 cupsArrayRemove(ActiveClients, con);
654 cupsdSetBusyState();
655
ef416fc2 656 if (partial)
657 {
658 /*
659 * Only do a partial close so that the encrypted client gets everything.
660 */
661
ef416fc2 662 shutdown(con->http.fd, 0);
f7deaa1a 663 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 664 }
665 else
666 {
667 /*
668 * Shut the socket down fully...
669 */
670
f7deaa1a 671 cupsdRemoveSelect(con->http.fd);
ef416fc2 672 close(con->http.fd);
ef416fc2 673 con->http.fd = -1;
674 }
675 }
676
677 if (!partial)
678 {
679 /*
680 * Free memory...
681 */
682
683 if (con->http.input_set)
684 free(con->http.input_set);
685
686 httpClearCookie(HTTP(con));
9f5eb9be 687 httpClearFields(HTTP(con));
ef416fc2 688
689 cupsdClearString(&con->filename);
690 cupsdClearString(&con->command);
691 cupsdClearString(&con->options);
b86bc4cf 692 cupsdClearString(&con->query_string);
ef416fc2 693
694 if (con->request)
695 {
696 ippDelete(con->request);
697 con->request = NULL;
698 }
699
700 if (con->response)
701 {
702 ippDelete(con->response);
703 con->response = NULL;
704 }
705
706 if (con->language)
707 {
708 cupsLangFree(con->language);
709 con->language = NULL;
710 }
711
f7deaa1a 712#ifdef HAVE_AUTHORIZATION_H
713 if (con->authref)
714 {
715 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
716 con->authref = NULL;
717 }
718#endif /* HAVE_AUTHORIZATION_H */
719
ef416fc2 720 /*
721 * Re-enable new client connections if we are going back under the
722 * limit...
723 */
724
bd7854cb 725 if (cupsArrayCount(Clients) == MaxClients)
ef416fc2 726 cupsdResumeListening();
727
728 /*
729 * Compact the list of clients as necessary...
730 */
731
bd7854cb 732 cupsArrayRemove(Clients, con);
ef416fc2 733
bd7854cb 734 free(con);
ef416fc2 735 }
736
737 return (partial);
738}
739
740
d09495fa 741/*
742 * 'cupsdFlushHeader()' - Flush the header fields to the client.
743 */
744
07725fee 745int /* I - Bytes written or -1 on error */
d09495fa 746cupsdFlushHeader(cupsd_client_t *con) /* I - Client to flush to */
747{
07725fee 748 int bytes = httpFlushWrite(HTTP(con));
d09495fa 749
750 con->http.data_encoding = HTTP_ENCODE_LENGTH;
07725fee 751
752 return (bytes);
d09495fa 753}
754
755
ef416fc2 756/*
757 * 'cupsdReadClient()' - Read data from a client.
758 */
759
f7deaa1a 760void
ef416fc2 761cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
762{
763 char line[32768], /* Line from client... */
764 operation[64], /* Operation code from socket */
765 version[64], /* HTTP version number string */
766 locale[64], /* Locale */
767 *ptr; /* Pointer into strings */
768 int major, minor; /* HTTP version numbers */
769 http_status_t status; /* Transfer status */
770 ipp_state_t ipp_state; /* State of IPP transfer */
771 int bytes; /* Number of bytes to POST */
772 char *filename; /* Name of file for GET/HEAD */
773 char buf[1024]; /* Buffer for real filename */
774 struct stat filestats; /* File information */
775 mime_type_t *type; /* MIME type of file */
776 cupsd_printer_t *p; /* Printer */
777 static unsigned request_id = 0; /* Request ID for temp files */
778
779
780 status = HTTP_CONTINUE;
781
782 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
783 "cupsdReadClient(con=%p(%d)) "
784 "con->http.error=%d "
785 "con->http.used=%d, "
786 "con->http.state=%d "
787 "con->data_encoding=HTTP_ENCODE_%s, "
788 "con->data_remaining=" CUPS_LLFMT ", "
789 "con->file=%d",
790 con, con->http.fd, con->http.error, con->http.used,
791 con->http.state,
792 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
793 "CHUNKED" : "LENGTH",
794 CUPS_LLCAST con->http.data_remaining, con->file);
ef416fc2 795
ef416fc2 796#ifdef HAVE_SSL
797 if (con->auto_ssl)
798 {
799 /*
800 * Automatically check for a SSL/TLS handshake...
801 */
802
803 con->auto_ssl = 0;
804
805 if (recv(con->http.fd, buf, 1, MSG_PEEK) == 1 &&
806 (!buf[0] || !strchr("DGHOPT", buf[0])))
807 {
808 /*
809 * Encrypt this connection...
810 */
811
812 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
813 "cupsdReadClient: Saw first byte %02X, auto-negotiating "
814 "SSL/TLS session...", buf[0] & 255);
ef416fc2 815
411affcf 816 if (!encrypt_client(con))
f7deaa1a 817 cupsdCloseClient(con);
411affcf 818
f7deaa1a 819 return;
ef416fc2 820 }
821 }
822#endif /* HAVE_SSL */
823
824 switch (con->http.state)
825 {
826 case HTTP_WAITING :
827 /*
828 * See if we've received a request line...
829 */
830
831 if (httpGets(line, sizeof(line) - 1, HTTP(con)) == NULL)
832 {
f11a948a
MS
833 if (con->http.error && con->http.error != EPIPE)
834 cupsdLogMessage(CUPSD_LOG_DEBUG,
835 "cupsdReadClient: %d WAITING Closing for error %d "
836 "(%s)", con->http.fd, con->http.error,
837 strerror(con->http.error));
838 else
839 cupsdLogMessage(CUPSD_LOG_DEBUG,
840 "cupsdReadClient: %d WAITING Closing on EOF",
841 con->http.fd);
842
f7deaa1a 843 cupsdCloseClient(con);
844 return;
ef416fc2 845 }
846
847 /*
848 * Ignore blank request lines...
849 */
850
851 if (line[0] == '\0')
852 break;
853
854 /*
855 * Clear other state variables...
856 */
857
858 httpClearFields(HTTP(con));
859
860 con->http.activity = time(NULL);
861 con->http.version = HTTP_1_0;
862 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
863 con->http.data_encoding = HTTP_ENCODE_LENGTH;
864 con->http.data_remaining = 0;
865 con->http._data_remaining = 0;
866 con->operation = HTTP_WAITING;
867 con->bytes = 0;
868 con->file = -1;
869 con->file_ready = 0;
870 con->pipe_pid = 0;
871 con->username[0] = '\0';
872 con->password[0] = '\0';
873 con->uri[0] = '\0';
874
875 cupsdClearString(&con->command);
876 cupsdClearString(&con->options);
b86bc4cf 877 cupsdClearString(&con->query_string);
ef416fc2 878
2abf387c 879 if (con->request)
880 {
881 ippDelete(con->request);
882 con->request = NULL;
883 }
884
885 if (con->response)
886 {
887 ippDelete(con->response);
888 con->response = NULL;
889 }
890
891 if (con->language)
ef416fc2 892 {
893 cupsLangFree(con->language);
894 con->language = NULL;
895 }
896
09a101d6 897#ifdef HAVE_GSSAPI
97c9a8d7
MS
898 con->have_gss = 0;
899
900 if (con->gss_creds)
e07d4801
MS
901 {
902 OM_uint32 minor_status;
903 gss_release_cred(&minor_status, &con->gss_creds);
904 }
09a101d6 905#endif /* HAVE_GSSAPI */
906
ef416fc2 907 /*
908 * Grab the request line...
909 */
910
911 switch (sscanf(line, "%63s%1023s%63s", operation, con->uri, version))
912 {
913 case 1 :
c934a06c
MS
914 if (line[0])
915 {
916 cupsdLogMessage(CUPSD_LOG_ERROR,
917 "Bad request line \"%s\" from %s!", line,
918 con->http.hostname);
919 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
920 cupsdCloseClient(con);
921 }
f7deaa1a 922 return;
ef416fc2 923 case 2 :
924 con->http.version = HTTP_0_9;
925 break;
926 case 3 :
927 if (sscanf(version, "HTTP/%d.%d", &major, &minor) != 2)
928 {
929 cupsdLogMessage(CUPSD_LOG_ERROR,
930 "Bad request line \"%s\" from %s!", line,
931 con->http.hostname);
5bd77a73 932 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 933 cupsdCloseClient(con);
934 return;
ef416fc2 935 }
936
937 if (major < 2)
938 {
939 con->http.version = (http_version_t)(major * 100 + minor);
940 if (con->http.version == HTTP_1_1 && KeepAlive)
941 con->http.keep_alive = HTTP_KEEPALIVE_ON;
942 else
943 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
944 }
945 else
946 {
f11a948a
MS
947 cupsdLogMessage(CUPSD_LOG_ERROR,
948 "Unsupported request line \"%s\" from %s!",
949 line, con->http.hostname);
5bd77a73 950 cupsdSendError(con, HTTP_NOT_SUPPORTED, CUPSD_AUTH_NONE);
f7deaa1a 951 cupsdCloseClient(con);
952 return;
ef416fc2 953 }
954 break;
955 }
956
957 /*
958 * Handle full URLs in the request line...
959 */
960
961 if (strcmp(con->uri, "*"))
962 {
e6013cfa 963 char scheme[HTTP_MAX_URI], /* Method/scheme */
ef416fc2 964 userpass[HTTP_MAX_URI], /* Username:password */
965 hostname[HTTP_MAX_URI], /* Hostname */
966 resource[HTTP_MAX_URI]; /* Resource path */
967 int port; /* Port number */
968
969
970 /*
971 * Separate the URI into its components...
972 */
973
a4d04587 974 httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
e6013cfa 975 scheme, sizeof(scheme),
ef416fc2 976 userpass, sizeof(userpass),
977 hostname, sizeof(hostname), &port,
978 resource, sizeof(resource));
979
980 /*
981 * Only allow URIs with the servername, localhost, or an IP
982 * address...
983 */
984
e6013cfa 985 if (strcmp(scheme, "file") &&
ef416fc2 986 strcasecmp(hostname, ServerName) &&
987 strcasecmp(hostname, "localhost") &&
e6013cfa 988 !isdigit(hostname[0]) && hostname[0] != '[')
ef416fc2 989 {
990 /*
991 * Nope, we don't do proxies...
992 */
993
994 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad URI \"%s\" in request!",
995 con->uri);
5bd77a73 996 cupsdSendError(con, HTTP_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
f7deaa1a 997 cupsdCloseClient(con);
998 return;
ef416fc2 999 }
1000
1001 /*
1002 * Copy the resource portion back into the URI; both resource and
1003 * con->uri are HTTP_MAX_URI bytes in size...
1004 */
1005
1006 strcpy(con->uri, resource);
1007 }
1008
1009 /*
1010 * Process the request...
1011 */
1012
1013 if (!strcmp(operation, "GET"))
1014 con->http.state = HTTP_GET;
1015 else if (!strcmp(operation, "PUT"))
1016 con->http.state = HTTP_PUT;
1017 else if (!strcmp(operation, "POST"))
1018 con->http.state = HTTP_POST;
1019 else if (!strcmp(operation, "DELETE"))
1020 con->http.state = HTTP_DELETE;
1021 else if (!strcmp(operation, "TRACE"))
1022 con->http.state = HTTP_TRACE;
1023 else if (!strcmp(operation, "OPTIONS"))
1024 con->http.state = HTTP_OPTIONS;
1025 else if (!strcmp(operation, "HEAD"))
1026 con->http.state = HTTP_HEAD;
1027 else
1028 {
1029 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad operation \"%s\"!", operation);
5bd77a73 1030 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 1031 cupsdCloseClient(con);
1032 return;
ef416fc2 1033 }
1034
dfd5680b 1035 gettimeofday(&(con->start), NULL);
ef416fc2 1036 con->operation = con->http.state;
1037
89d46774 1038 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1039 con->http.fd, operation, con->uri,
ef416fc2 1040 con->http.version / 100, con->http.version % 100);
1041
1042 con->http.status = HTTP_OK;
1043
49d87452
MS
1044 if (!cupsArrayFind(ActiveClients, con))
1045 {
1046 cupsArrayAdd(ActiveClients, con);
1047 cupsdSetBusyState();
1048 }
3dfe78b3 1049
ef416fc2 1050 case HTTP_OPTIONS :
1051 case HTTP_DELETE :
1052 case HTTP_GET :
1053 case HTTP_HEAD :
1054 case HTTP_POST :
1055 case HTTP_PUT :
1056 case HTTP_TRACE :
1057 /*
1058 * Parse incoming parameters until the status changes...
1059 */
1060
f7deaa1a 1061 while ((status = httpUpdate(HTTP(con))) == HTTP_CONTINUE)
ee571f26 1062 if (!data_ready(con))
f7deaa1a 1063 break;
ef416fc2 1064
1065 if (status != HTTP_OK && status != HTTP_CONTINUE)
1066 {
f11a948a
MS
1067 if (con->http.error && con->http.error != EPIPE)
1068 cupsdLogMessage(CUPSD_LOG_DEBUG,
1069 "cupsdReadClient: %d FIELDS Closing for error %d "
1070 "(%s)", con->http.fd, con->http.error,
1071 strerror(con->http.error));
1072 else
1073 cupsdLogMessage(CUPSD_LOG_DEBUG,
1074 "cupsdReadClient: %d FIELDS Closing on EOF",
1075 con->http.fd);
1076
5bd77a73 1077 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 1078 cupsdCloseClient(con);
1079 return;
ef416fc2 1080 }
1081 break;
1082
1083 default :
e6013cfa
MS
1084 if (!data_ready(con) && recv(con->http.fd, buf, 1, MSG_PEEK) < 1)
1085 {
1086 /*
1087 * Connection closed...
1088 */
1089
f11a948a
MS
1090 cupsdLogMessage(CUPSD_LOG_DEBUG,
1091 "cupsdReadClient: %d Closing on EOF", con->http.fd);
e6013cfa
MS
1092 cupsdCloseClient(con);
1093 return;
1094 }
ef416fc2 1095 break; /* Anti-compiler-warning-code */
1096 }
1097
1098 /*
1099 * Handle new transfers...
1100 */
1101
1102 if (status == HTTP_OK)
1103 {
1104 if (con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE][0])
1105 {
1106 /*
1107 * Figure out the locale from the Accept-Language and Content-Type
1108 * fields...
1109 */
1110
f11a948a
MS
1111 if ((ptr = strchr(con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE],
1112 ',')) != NULL)
ef416fc2 1113 *ptr = '\0';
1114
f11a948a
MS
1115 if ((ptr = strchr(con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE],
1116 ';')) != NULL)
ef416fc2 1117 *ptr = '\0';
1118
f11a948a
MS
1119 if ((ptr = strstr(con->http.fields[HTTP_FIELD_CONTENT_TYPE],
1120 "charset=")) != NULL)
ef416fc2 1121 {
1122 /*
1123 * Combine language and charset, and trim any extra params in the
1124 * content-type.
1125 */
1126
1127 snprintf(locale, sizeof(locale), "%s.%s",
1128 con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ptr + 8);
1129
1130 if ((ptr = strchr(locale, ',')) != NULL)
1131 *ptr = '\0';
1132 }
1133 else
f8b3a85b
MS
1134 snprintf(locale, sizeof(locale), "%s.UTF-8",
1135 con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE]);
d6ae789d 1136
ef416fc2 1137 con->language = cupsLangGet(locale);
1138 }
1139 else
1140 con->language = cupsLangGet(DefaultLocale);
1141
1142 cupsdAuthorize(con);
1143
f11a948a
MS
1144 if (!strncasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Keep-Alive",
1145 10) && KeepAlive)
ef416fc2 1146 con->http.keep_alive = HTTP_KEEPALIVE_ON;
52f6f666
MS
1147 else if (!strncasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "close", 5))
1148 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
ef416fc2 1149
1150 if (!con->http.fields[HTTP_FIELD_HOST][0] &&
1151 con->http.version >= HTTP_1_1)
1152 {
1153 /*
1154 * HTTP/1.1 and higher require the "Host:" field...
1155 */
1156
5bd77a73 1157 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
f7deaa1a 1158 {
f11a948a 1159 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing Host: field in request!");
f7deaa1a 1160 cupsdCloseClient(con);
1161 return;
1162 }
ef416fc2 1163 }
e07d4801 1164 else if (!valid_host(con))
e6013cfa
MS
1165 {
1166 /*
1167 * Access to localhost must use "localhost" or the corresponding IPv4
1168 * or IPv6 values in the Host: field.
1169 */
1170
f11a948a 1171 cupsdLogMessage(CUPSD_LOG_ERROR,
e6013cfa
MS
1172 "Request from \"%s\" using invalid Host: field \"%s\"",
1173 con->http.hostname, con->http.fields[HTTP_FIELD_HOST]);
1174
1175 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
1176 {
1177 cupsdCloseClient(con);
1178 return;
1179 }
1180 }
ef416fc2 1181 else if (con->operation == HTTP_OPTIONS)
1182 {
1183 /*
1184 * Do OPTIONS command...
1185 */
1186
5bd77a73 1187 if (con->best && con->best->type != CUPSD_AUTH_NONE)
ef416fc2 1188 {
5bd77a73 1189 if (!cupsdSendHeader(con, HTTP_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1190 {
1191 cupsdCloseClient(con);
1192 return;
1193 }
ef416fc2 1194 }
1195
1196 if (!strcasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Upgrade") &&
1197 con->http.tls == NULL)
1198 {
1199#ifdef HAVE_SSL
1200 /*
1201 * Do encryption stuff...
1202 */
1203
5bd77a73 1204 if (!cupsdSendHeader(con, HTTP_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1205 {
1206 cupsdCloseClient(con);
1207 return;
1208 }
ef416fc2 1209
1210 httpPrintf(HTTP(con), "Connection: Upgrade\r\n");
1211 httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1212 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1213 httpPrintf(HTTP(con), "\r\n");
07725fee 1214
1215 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1216 {
1217 cupsdCloseClient(con);
1218 return;
1219 }
ef416fc2 1220
411affcf 1221 if (!encrypt_client(con))
f7deaa1a 1222 {
1223 cupsdCloseClient(con);
1224 return;
1225 }
ef416fc2 1226#else
5bd77a73 1227 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
f7deaa1a 1228 {
1229 cupsdCloseClient(con);
1230 return;
1231 }
ef416fc2 1232#endif /* HAVE_SSL */
1233 }
1234
5bd77a73 1235 if (!cupsdSendHeader(con, HTTP_OK, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1236 {
1237 cupsdCloseClient(con);
1238 return;
1239 }
ef416fc2 1240
1241 httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1242 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1243 httpPrintf(HTTP(con), "\r\n");
07725fee 1244
1245 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1246 {
1247 cupsdCloseClient(con);
1248 return;
1249 }
ef416fc2 1250 }
1251 else if (!is_path_absolute(con->uri))
1252 {
1253 /*
1254 * Protect against malicious users!
1255 */
1256
bf3816c7
MS
1257 cupsdLogMessage(CUPSD_LOG_ERROR,
1258 "Request for non-absolute resource \"%s\"!", con->uri);
1259
5bd77a73 1260 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1261 {
1262 cupsdCloseClient(con);
1263 return;
1264 }
ef416fc2 1265 }
1266 else
1267 {
1268 if (!strcasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Upgrade") &&
1269 con->http.tls == NULL)
1270 {
1271#ifdef HAVE_SSL
1272 /*
1273 * Do encryption stuff...
1274 */
1275
5bd77a73 1276 if (!cupsdSendHeader(con, HTTP_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1277 {
1278 cupsdCloseClient(con);
1279 return;
1280 }
ef416fc2 1281
1282 httpPrintf(HTTP(con), "Connection: Upgrade\r\n");
1283 httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1284 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1285 httpPrintf(HTTP(con), "\r\n");
07725fee 1286
1287 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1288 {
1289 cupsdCloseClient(con);
1290 return;
1291 }
ef416fc2 1292
411affcf 1293 if (!encrypt_client(con))
f7deaa1a 1294 {
1295 cupsdCloseClient(con);
1296 return;
1297 }
ef416fc2 1298#else
5bd77a73 1299 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
f7deaa1a 1300 {
1301 cupsdCloseClient(con);
1302 return;
1303 }
ef416fc2 1304#endif /* HAVE_SSL */
1305 }
1306
1307 if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_OK)
1308 {
5bd77a73 1309 cupsdSendError(con, status, CUPSD_AUTH_NONE);
f7deaa1a 1310 cupsdCloseClient(con);
1311 return;
ef416fc2 1312 }
1313
b423cd4c 1314 if (con->http.expect &&
1315 (con->operation == HTTP_POST || con->operation == HTTP_PUT))
ef416fc2 1316 {
b423cd4c 1317 if (con->http.expect == HTTP_CONTINUE)
1318 {
1319 /*
1320 * Send 100-continue header...
1321 */
1322
5bd77a73 1323 if (!cupsdSendHeader(con, HTTP_CONTINUE, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1324 {
1325 cupsdCloseClient(con);
1326 return;
1327 }
b423cd4c 1328 }
1329 else
1330 {
1331 /*
1332 * Send 417-expectation-failed header...
1333 */
1334
f11a948a
MS
1335 if (!cupsdSendHeader(con, HTTP_EXPECTATION_FAILED, NULL,
1336 CUPSD_AUTH_NONE))
f7deaa1a 1337 {
1338 cupsdCloseClient(con);
1339 return;
1340 }
b423cd4c 1341
1342 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1343 httpPrintf(HTTP(con), "\r\n");
07725fee 1344
1345 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1346 {
1347 cupsdCloseClient(con);
1348 return;
1349 }
b423cd4c 1350 }
ef416fc2 1351 }
1352
1353 switch (con->http.state)
1354 {
1355 case HTTP_GET_SEND :
1356 if (!strncmp(con->uri, "/printers/", 10) &&
1357 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1358 {
1359 /*
1360 * Send PPD file - get the real printer name since printer
1361 * names are not case sensitive but filenames can be...
1362 */
1363
1364 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1365
1366 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1367 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1368 else
1369 {
5bd77a73 1370 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1371 {
1372 cupsdCloseClient(con);
1373 return;
1374 }
ef416fc2 1375
1376 break;
1377 }
1378 }
1379
1380 if ((!strncmp(con->uri, "/admin", 6) &&
1381 strncmp(con->uri, "/admin/conf/", 12) &&
1382 strncmp(con->uri, "/admin/log/", 11)) ||
1383 !strncmp(con->uri, "/printers", 9) ||
1384 !strncmp(con->uri, "/classes", 8) ||
1385 !strncmp(con->uri, "/help", 5) ||
1386 !strncmp(con->uri, "/jobs", 5))
1387 {
1388 /*
1389 * Send CGI output...
1390 */
1391
1392 if (!strncmp(con->uri, "/admin", 6))
1393 {
1394 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1395 ServerBin);
1396
b423cd4c 1397 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
ef416fc2 1398 }
1399 else if (!strncmp(con->uri, "/printers", 9))
1400 {
1401 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1402 ServerBin);
b423cd4c 1403
1404 if (con->uri[9] && con->uri[10])
1405 cupsdSetString(&con->options, con->uri + 9);
1406 else
1407 cupsdSetString(&con->options, NULL);
ef416fc2 1408 }
1409 else if (!strncmp(con->uri, "/classes", 8))
1410 {
1411 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1412 ServerBin);
b423cd4c 1413
1414 if (con->uri[8] && con->uri[9])
1415 cupsdSetString(&con->options, con->uri + 8);
1416 else
1417 cupsdSetString(&con->options, NULL);
ef416fc2 1418 }
1419 else if (!strncmp(con->uri, "/jobs", 5))
1420 {
1421 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1422 ServerBin);
b423cd4c 1423
1424 if (con->uri[5] && con->uri[6])
1425 cupsdSetString(&con->options, con->uri + 5);
1426 else
1427 cupsdSetString(&con->options, NULL);
ef416fc2 1428 }
1429 else
1430 {
1431 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1432 ServerBin);
ef416fc2 1433
b423cd4c 1434 if (con->uri[5] && con->uri[6])
1435 cupsdSetString(&con->options, con->uri + 5);
1436 else
1437 cupsdSetString(&con->options, NULL);
1438 }
ef416fc2 1439
1440 if (!cupsdSendCommand(con, con->command, con->options, 0))
1441 {
5bd77a73 1442 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1443 {
1444 cupsdCloseClient(con);
1445 return;
1446 }
ef416fc2 1447 }
1448 else
1449 cupsdLogRequest(con, HTTP_OK);
1450
1451 if (con->http.version <= HTTP_1_0)
1452 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1453 }
1454 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1455 (strchr(con->uri + 12, '/') ||
1456 strlen(con->uri) == 12)) ||
1457 (!strncmp(con->uri, "/admin/log/", 11) &&
1458 (strchr(con->uri + 11, '/') ||
1459 strlen(con->uri) == 11)))
1460 {
1461 /*
bf3816c7 1462 * GET can only be done to configuration files directly under
ef416fc2 1463 * /admin/conf...
1464 */
1465
bf3816c7
MS
1466 cupsdLogMessage(CUPSD_LOG_ERROR,
1467 "Request for subdirectory \"%s\"!", con->uri);
1468
5bd77a73 1469 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1470 {
1471 cupsdCloseClient(con);
1472 return;
1473 }
ef416fc2 1474
1475 break;
1476 }
1477 else
1478 {
1479 /*
1480 * Serve a file...
1481 */
1482
1483 if ((filename = get_file(con, &filestats, buf,
1484 sizeof(buf))) == NULL)
1485 {
5bd77a73 1486 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1487 {
1488 cupsdCloseClient(con);
1489 return;
1490 }
ef416fc2 1491
1492 break;
1493 }
1494
4400e98d 1495 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
ef416fc2 1496
e1d6a774 1497 if (is_cgi(con, filename, &filestats, type))
ef416fc2 1498 {
1499 /*
1500 * Note: con->command and con->options were set by
e1d6a774 1501 * is_cgi()...
ef416fc2 1502 */
1503
1504 if (!cupsdSendCommand(con, con->command, con->options, 0))
1505 {
5bd77a73 1506 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1507 {
1508 cupsdCloseClient(con);
1509 return;
1510 }
ef416fc2 1511 }
1512 else
1513 cupsdLogRequest(con, HTTP_OK);
1514
1515 if (con->http.version <= HTTP_1_0)
1516 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1517 break;
1518 }
1519
1520 if (!check_if_modified(con, &filestats))
1521 {
5bd77a73 1522 if (!cupsdSendError(con, HTTP_NOT_MODIFIED, CUPSD_AUTH_NONE))
f7deaa1a 1523 {
1524 cupsdCloseClient(con);
1525 return;
1526 }
ef416fc2 1527 }
1528 else
1529 {
1530 if (type == NULL)
1531 strcpy(line, "text/plain");
1532 else
1533 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1534
a74454a7 1535 if (!write_file(con, HTTP_OK, filename, line, &filestats))
f7deaa1a 1536 {
1537 cupsdCloseClient(con);
1538 return;
1539 }
ef416fc2 1540 }
1541 }
1542 break;
1543
1544 case HTTP_POST_RECV :
1545 /*
1546 * See if the POST request includes a Content-Length field, and if
1547 * so check the length against any limits that are set...
1548 */
1549
ef416fc2 1550 if (con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1551 MaxRequestSize > 0 &&
1552 con->http.data_remaining > MaxRequestSize)
1553 {
1554 /*
1555 * Request too large...
1556 */
1557
5bd77a73 1558 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1559 {
1560 cupsdCloseClient(con);
1561 return;
1562 }
ef416fc2 1563
1564 break;
1565 }
839a51c8
MS
1566 else if (con->http.data_remaining < 0 ||
1567 (!con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1568 con->http.data_encoding == HTTP_ENCODE_LENGTH))
ef416fc2 1569 {
1570 /*
1571 * Negative content lengths are invalid!
1572 */
1573
5bd77a73 1574 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
f7deaa1a 1575 {
1576 cupsdCloseClient(con);
1577 return;
1578 }
ef416fc2 1579
1580 break;
1581 }
1582
1583 /*
1584 * See what kind of POST request this is; for IPP requests the
1585 * content-type field will be "application/ipp"...
1586 */
1587
1588 if (!strcmp(con->http.fields[HTTP_FIELD_CONTENT_TYPE],
1589 "application/ipp"))
1590 con->request = ippNew();
1591 else if ((!strncmp(con->uri, "/admin", 6) &&
1592 strncmp(con->uri, "/admin/conf/", 12) &&
1593 strncmp(con->uri, "/admin/log/", 11)) ||
1594 !strncmp(con->uri, "/printers", 9) ||
1595 !strncmp(con->uri, "/classes", 8) ||
1596 !strncmp(con->uri, "/help", 5) ||
1597 !strncmp(con->uri, "/jobs", 5))
1598 {
1599 /*
1600 * CGI request...
1601 */
1602
1603 if (!strncmp(con->uri, "/admin", 6))
1604 {
1605 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1606 ServerBin);
1607
b423cd4c 1608 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
ef416fc2 1609 }
1610 else if (!strncmp(con->uri, "/printers", 9))
1611 {
1612 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1613 ServerBin);
b423cd4c 1614
1615 if (con->uri[9] && con->uri[10])
1616 cupsdSetString(&con->options, con->uri + 9);
1617 else
1618 cupsdSetString(&con->options, NULL);
ef416fc2 1619 }
1620 else if (!strncmp(con->uri, "/classes", 8))
1621 {
1622 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1623 ServerBin);
b423cd4c 1624
1625 if (con->uri[8] && con->uri[9])
1626 cupsdSetString(&con->options, con->uri + 8);
1627 else
1628 cupsdSetString(&con->options, NULL);
ef416fc2 1629 }
1630 else if (!strncmp(con->uri, "/jobs", 5))
1631 {
1632 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1633 ServerBin);
b423cd4c 1634
1635 if (con->uri[5] && con->uri[6])
1636 cupsdSetString(&con->options, con->uri + 5);
1637 else
1638 cupsdSetString(&con->options, NULL);
ef416fc2 1639 }
1640 else
1641 {
1642 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1643 ServerBin);
ef416fc2 1644
b423cd4c 1645 if (con->uri[5] && con->uri[6])
1646 cupsdSetString(&con->options, con->uri + 5);
1647 else
1648 cupsdSetString(&con->options, NULL);
1649 }
ef416fc2 1650
ef416fc2 1651 if (con->http.version <= HTTP_1_0)
1652 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1653 }
1654 else
1655 {
1656 /*
1657 * POST to a file...
1658 */
1659
1660 if ((filename = get_file(con, &filestats, buf,
1661 sizeof(buf))) == NULL)
1662 {
5bd77a73 1663 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1664 {
1665 cupsdCloseClient(con);
1666 return;
1667 }
ef416fc2 1668
1669 break;
1670 }
1671
4400e98d 1672 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
ef416fc2 1673
e1d6a774 1674 if (!is_cgi(con, filename, &filestats, type))
ef416fc2 1675 {
1676 /*
1677 * Only POST to CGI's...
1678 */
1679
5bd77a73 1680 if (!cupsdSendError(con, HTTP_UNAUTHORIZED, CUPSD_AUTH_NONE))
f7deaa1a 1681 {
1682 cupsdCloseClient(con);
1683 return;
1684 }
ef416fc2 1685 }
1686 }
1687 break;
1688
1689 case HTTP_PUT_RECV :
1690 /*
1691 * Validate the resource name...
1692 */
1693
1694 if (strncmp(con->uri, "/admin/conf/", 12) ||
1695 strchr(con->uri + 12, '/') ||
1696 strlen(con->uri) == 12)
1697 {
1698 /*
1699 * PUT can only be done to configuration files under
1700 * /admin/conf...
1701 */
1702
bf3816c7
MS
1703 cupsdLogMessage(CUPSD_LOG_ERROR,
1704 "Request for subdirectory \"%s\"!", con->uri);
1705
5bd77a73 1706 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1707 {
1708 cupsdCloseClient(con);
1709 return;
1710 }
ef416fc2 1711
1712 break;
1713 }
1714
1715 /*
1716 * See if the PUT request includes a Content-Length field, and if
1717 * so check the length against any limits that are set...
1718 */
1719
ef416fc2 1720 if (con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1721 MaxRequestSize > 0 &&
1722 con->http.data_remaining > MaxRequestSize)
1723 {
1724 /*
1725 * Request too large...
1726 */
1727
5bd77a73 1728 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1729 {
1730 cupsdCloseClient(con);
1731 return;
1732 }
ef416fc2 1733
1734 break;
1735 }
1736 else if (con->http.data_remaining < 0)
1737 {
1738 /*
1739 * Negative content lengths are invalid!
1740 */
1741
5bd77a73 1742 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
f7deaa1a 1743 {
1744 cupsdCloseClient(con);
1745 return;
1746 }
ef416fc2 1747
1748 break;
1749 }
1750
1751 /*
1752 * Open a temporary file to hold the request...
1753 */
1754
1755 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1756 request_id ++);
1757 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1758
ef416fc2 1759 if (con->file < 0)
1760 {
a4924f6c
MS
1761 cupsdLogMessage(CUPSD_LOG_ERROR,
1762 "Unable to create request file %s: %s",
1763 con->filename, strerror(errno));
1764
5bd77a73 1765 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1766 {
1767 cupsdCloseClient(con);
1768 return;
1769 }
ef416fc2 1770 }
1771
1772 fchmod(con->file, 0640);
1773 fchown(con->file, RunUser, Group);
1774 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1775 break;
1776
1777 case HTTP_DELETE :
1778 case HTTP_TRACE :
5bd77a73 1779 cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);
f7deaa1a 1780 cupsdCloseClient(con);
1781 return;
ef416fc2 1782
1783 case HTTP_HEAD :
1784 if (!strncmp(con->uri, "/printers/", 10) &&
1785 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1786 {
1787 /*
1788 * Send PPD file - get the real printer name since printer
1789 * names are not case sensitive but filenames can be...
1790 */
1791
1792 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1793
1794 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1795 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1796 else
1797 {
5bd77a73 1798 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1799 {
1800 cupsdCloseClient(con);
1801 return;
1802 }
ef416fc2 1803
1804 break;
1805 }
1806 }
1807
1808 if ((!strncmp(con->uri, "/admin", 6) &&
1809 strncmp(con->uri, "/admin/conf/", 12) &&
1810 strncmp(con->uri, "/admin/log/", 11)) ||
1811 !strncmp(con->uri, "/printers", 9) ||
1812 !strncmp(con->uri, "/classes", 8) ||
1813 !strncmp(con->uri, "/help", 5) ||
1814 !strncmp(con->uri, "/jobs", 5))
1815 {
1816 /*
1817 * CGI output...
1818 */
1819
5bd77a73 1820 if (!cupsdSendHeader(con, HTTP_OK, "text/html", CUPSD_AUTH_NONE))
f7deaa1a 1821 {
1822 cupsdCloseClient(con);
1823 return;
1824 }
ef416fc2 1825
1826 if (httpPrintf(HTTP(con), "\r\n") < 0)
f7deaa1a 1827 {
1828 cupsdCloseClient(con);
1829 return;
1830 }
ef416fc2 1831
07725fee 1832 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1833 {
1834 cupsdCloseClient(con);
1835 return;
1836 }
d09495fa 1837
ef416fc2 1838 cupsdLogRequest(con, HTTP_OK);
1839 }
1840 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1841 (strchr(con->uri + 12, '/') ||
1842 strlen(con->uri) == 12)) ||
1843 (!strncmp(con->uri, "/admin/log/", 11) &&
1844 (strchr(con->uri + 11, '/') ||
1845 strlen(con->uri) == 11)))
1846 {
1847 /*
1848 * HEAD can only be done to configuration files under
1849 * /admin/conf...
1850 */
1851
bf3816c7
MS
1852 cupsdLogMessage(CUPSD_LOG_ERROR,
1853 "Request for subdirectory \"%s\"!", con->uri);
1854
5bd77a73 1855 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1856 {
1857 cupsdCloseClient(con);
1858 return;
1859 }
ef416fc2 1860
1861 break;
1862 }
1863 else if ((filename = get_file(con, &filestats, buf,
1864 sizeof(buf))) == NULL)
1865 {
f11a948a
MS
1866 if (!cupsdSendHeader(con, HTTP_NOT_FOUND, "text/html",
1867 CUPSD_AUTH_NONE))
f7deaa1a 1868 {
1869 cupsdCloseClient(con);
1870 return;
1871 }
ef416fc2 1872
1873 cupsdLogRequest(con, HTTP_NOT_FOUND);
1874 }
1875 else if (!check_if_modified(con, &filestats))
1876 {
5bd77a73 1877 if (!cupsdSendError(con, HTTP_NOT_MODIFIED, CUPSD_AUTH_NONE))
f7deaa1a 1878 {
1879 cupsdCloseClient(con);
1880 return;
1881 }
ef416fc2 1882
1883 cupsdLogRequest(con, HTTP_NOT_MODIFIED);
1884 }
1885 else
1886 {
1887 /*
1888 * Serve a file...
1889 */
1890
4400e98d 1891 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
ef416fc2 1892 if (type == NULL)
1893 strcpy(line, "text/plain");
1894 else
1895 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1896
5bd77a73 1897 if (!cupsdSendHeader(con, HTTP_OK, line, CUPSD_AUTH_NONE))
f7deaa1a 1898 {
1899 cupsdCloseClient(con);
1900 return;
1901 }
ef416fc2 1902
1903 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
1904 httpGetDateString(filestats.st_mtime)) < 0)
f7deaa1a 1905 {
1906 cupsdCloseClient(con);
1907 return;
1908 }
ef416fc2 1909
1910 if (httpPrintf(HTTP(con), "Content-Length: %lu\r\n",
1911 (unsigned long)filestats.st_size) < 0)
f7deaa1a 1912 {
1913 cupsdCloseClient(con);
1914 return;
1915 }
ef416fc2 1916
1917 cupsdLogRequest(con, HTTP_OK);
1918 }
1919
1920 if (httpPrintf(HTTP(con), "\r\n") < 0)
f7deaa1a 1921 {
1922 cupsdCloseClient(con);
1923 return;
1924 }
ef416fc2 1925
07725fee 1926 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1927 {
1928 cupsdCloseClient(con);
1929 return;
1930 }
d09495fa 1931
ef416fc2 1932 con->http.state = HTTP_WAITING;
1933 break;
1934
1935 default :
1936 break; /* Anti-compiler-warning-code */
1937 }
1938 }
1939 }
1940
1941 /*
1942 * Handle any incoming data...
1943 */
1944
1945 switch (con->http.state)
1946 {
1947 case HTTP_PUT_RECV :
f7deaa1a 1948 do
ef416fc2 1949 {
f7deaa1a 1950 if ((bytes = httpRead2(HTTP(con), line, sizeof(line))) < 0)
1951 {
f11a948a
MS
1952 if (con->http.error && con->http.error != EPIPE)
1953 cupsdLogMessage(CUPSD_LOG_DEBUG,
1954 "cupsdReadClient: %d PUT_RECV Closing for error "
1955 "%d (%s)", con->http.fd, con->http.error,
1956 strerror(con->http.error));
1957 else
1958 cupsdLogMessage(CUPSD_LOG_DEBUG,
1959 "cupsdReadClient: %d PUT_RECV Closing on EOF",
1960 con->http.fd);
1961
f7deaa1a 1962 cupsdCloseClient(con);
1963 return;
1964 }
1965 else if (bytes > 0)
1966 {
1967 con->bytes += bytes;
ef416fc2 1968
f7deaa1a 1969 if (write(con->file, line, bytes) < bytes)
1970 {
1971 cupsdLogMessage(CUPSD_LOG_ERROR,
1972 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1973 bytes, con->filename, strerror(errno));
ef416fc2 1974
f7deaa1a 1975 close(con->file);
1976 con->file = -1;
1977 unlink(con->filename);
1978 cupsdClearString(&con->filename);
ef416fc2 1979
5bd77a73 1980 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1981 {
1982 cupsdCloseClient(con);
1983 return;
1984 }
1985 }
ef416fc2 1986 }
f7deaa1a 1987 }
ee571f26 1988 while (con->http.state == HTTP_PUT_RECV && data_ready(con));
ef416fc2 1989
1990 if (con->http.state == HTTP_WAITING)
1991 {
1992 /*
1993 * End of file, see how big it is...
1994 */
1995
1996 fstat(con->file, &filestats);
1997
ef416fc2 1998 close(con->file);
1999 con->file = -1;
2000
2001 if (filestats.st_size > MaxRequestSize &&
2002 MaxRequestSize > 0)
2003 {
2004 /*
2005 * Request is too big; remove it and send an error...
2006 */
2007
ef416fc2 2008 unlink(con->filename);
2009 cupsdClearString(&con->filename);
2010
5bd77a73 2011 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2012 {
2013 cupsdCloseClient(con);
2014 return;
2015 }
ef416fc2 2016 }
2017
2018 /*
2019 * Install the configuration file...
2020 */
2021
2022 status = install_conf_file(con);
2023
2024 /*
2025 * Return the status to the client...
2026 */
2027
5bd77a73 2028 if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))
f7deaa1a 2029 {
2030 cupsdCloseClient(con);
2031 return;
2032 }
ef416fc2 2033 }
2034 break;
2035
2036 case HTTP_POST_RECV :
f7deaa1a 2037 do
ef416fc2 2038 {
f11a948a 2039 if (con->request && con->file < 0)
ef416fc2 2040 {
f7deaa1a 2041 /*
2042 * Grab any request data from the connection...
2043 */
ef416fc2 2044
f7deaa1a 2045 if ((ipp_state = ippRead(&(con->http), con->request)) == IPP_ERROR)
ef416fc2 2046 {
f7deaa1a 2047 cupsdLogMessage(CUPSD_LOG_ERROR,
2048 "cupsdReadClient: %d IPP Read Error!",
2049 con->http.fd);
2050
5bd77a73 2051 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 2052 cupsdCloseClient(con);
2053 return;
ef416fc2 2054 }
f7deaa1a 2055 else if (ipp_state != IPP_DATA)
2056 {
2057 if (con->http.state == HTTP_POST_SEND)
2058 {
5bd77a73 2059 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 2060 cupsdCloseClient(con);
2061 return;
2062 }
ef416fc2 2063
f7deaa1a 2064 break;
2065 }
2066 else
f11a948a
MS
2067 {
2068 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdReadClient: %d %d.%d %s %d",
2069 con->http.fd, con->request->request.op.version[0],
2070 con->request->request.op.version[1],
2071 ippOpString(con->request->request.op.operation_id),
2072 con->request->request.op.request_id);
f7deaa1a 2073 con->bytes += ippLength(con->request);
f11a948a 2074 }
f7deaa1a 2075 }
ef416fc2 2076
f7deaa1a 2077 if (con->file < 0 && con->http.state != HTTP_POST_SEND)
2078 {
2079 /*
2080 * Create a file as needed for the request data...
2081 */
ef416fc2 2082
f11a948a
MS
2083 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
2084 request_id ++);
f7deaa1a 2085 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
ef416fc2 2086
f7deaa1a 2087 if (con->file < 0)
2088 {
a4924f6c
MS
2089 cupsdLogMessage(CUPSD_LOG_ERROR,
2090 "Unable to create request file %s: %s",
2091 con->filename, strerror(errno));
2092
5bd77a73 2093 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2094 {
2095 cupsdCloseClient(con);
2096 return;
2097 }
2098 }
ef416fc2 2099
f7deaa1a 2100 fchmod(con->file, 0640);
2101 fchown(con->file, RunUser, Group);
2102 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2103 }
ef416fc2 2104
f7deaa1a 2105 if (con->http.state != HTTP_POST_SEND)
ef416fc2 2106 {
f7deaa1a 2107 if ((bytes = httpRead2(HTTP(con), line, sizeof(line))) < 0)
2108 {
f11a948a
MS
2109 if (con->http.error && con->http.error != EPIPE)
2110 cupsdLogMessage(CUPSD_LOG_DEBUG,
2111 "cupsdReadClient: %d POST_SEND Closing for "
2112 "error %d (%s)", con->http.fd, con->http.error,
2113 strerror(con->http.error));
2114 else
2115 cupsdLogMessage(CUPSD_LOG_DEBUG,
2116 "cupsdReadClient: %d POST_SEND Closing on EOF",
2117 con->http.fd);
2118
f7deaa1a 2119 cupsdCloseClient(con);
2120 return;
2121 }
2122 else if (bytes > 0)
2123 {
2124 con->bytes += bytes;
ef416fc2 2125
f7deaa1a 2126 if (write(con->file, line, bytes) < bytes)
2127 {
2128 cupsdLogMessage(CUPSD_LOG_ERROR,
f11a948a
MS
2129 "cupsdReadClient: Unable to write %d bytes to "
2130 "%s: %s", bytes, con->filename,
2131 strerror(errno));
ef416fc2 2132
f7deaa1a 2133 close(con->file);
2134 con->file = -1;
2135 unlink(con->filename);
2136 cupsdClearString(&con->filename);
ef416fc2 2137
f11a948a
MS
2138 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE,
2139 CUPSD_AUTH_NONE))
f7deaa1a 2140 {
2141 cupsdCloseClient(con);
2142 return;
2143 }
2144 }
2145 }
2146 else if (con->http.state == HTTP_POST_RECV)
2147 return;
2148 else if (con->http.state != HTTP_POST_SEND)
2149 {
f11a948a
MS
2150 cupsdLogMessage(CUPSD_LOG_DEBUG,
2151 "cupsdReadClient: %d Closing on unknown HTTP "
2152 "state %d", con->http.fd, con->http.state);
f7deaa1a 2153 cupsdCloseClient(con);
2154 return;
ef416fc2 2155 }
2156 }
f7deaa1a 2157 }
ee571f26 2158 while (con->http.state == HTTP_POST_RECV && data_ready(con));
ef416fc2 2159
2160 if (con->http.state == HTTP_POST_SEND)
2161 {
2162 if (con->file >= 0)
2163 {
2164 fstat(con->file, &filestats);
2165
ef416fc2 2166 close(con->file);
2167 con->file = -1;
2168
2169 if (filestats.st_size > MaxRequestSize &&
2170 MaxRequestSize > 0)
2171 {
2172 /*
2173 * Request is too big; remove it and send an error...
2174 */
2175
ef416fc2 2176 unlink(con->filename);
2177 cupsdClearString(&con->filename);
2178
2179 if (con->request)
2180 {
2181 /*
2182 * Delete any IPP request data...
2183 */
2184
2185 ippDelete(con->request);
2186 con->request = NULL;
2187 }
2188
5bd77a73 2189 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2190 {
2191 cupsdCloseClient(con);
2192 return;
2193 }
ef416fc2 2194 }
f8b3a85b
MS
2195 else if (filestats.st_size == 0)
2196 {
2197 /*
2198 * Don't allow empty file...
2199 */
2200
2201 unlink(con->filename);
2202 cupsdClearString(&con->filename);
2203 }
ef416fc2 2204
2205 if (con->command)
2206 {
2207 if (!cupsdSendCommand(con, con->command, con->options, 0))
2208 {
5bd77a73 2209 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 2210 {
2211 cupsdCloseClient(con);
2212 return;
2213 }
ef416fc2 2214 }
2215 else
2216 cupsdLogRequest(con, HTTP_OK);
2217 }
2218 }
2219
2220 if (con->request)
f7deaa1a 2221 {
2222 cupsdProcessIPPRequest(con);
bc44d920 2223
2224 if (con->filename)
2225 {
bc44d920 2226 unlink(con->filename);
2227 cupsdClearString(&con->filename);
2228 }
2229
f7deaa1a 2230 return;
2231 }
ef416fc2 2232 }
2233 break;
2234
2235 default :
2236 break; /* Anti-compiler-warning-code */
2237 }
2238
3dfe78b3
MS
2239 if (con->http.state == HTTP_WAITING)
2240 {
2241 if (!con->http.keep_alive)
f11a948a
MS
2242 {
2243 cupsdLogMessage(CUPSD_LOG_DEBUG,
2244 "cupsdReadClient: %d Closing because Keep-Alive disabled",
2245 con->http.fd);
3dfe78b3 2246 cupsdCloseClient(con);
f11a948a 2247 }
3dfe78b3
MS
2248 else
2249 {
2250 cupsArrayRemove(ActiveClients, con);
2251 cupsdSetBusyState();
2252 }
2253 }
ef416fc2 2254}
2255
2256
2257/*
2258 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2259 */
2260
2261int /* O - 1 on success, 0 on failure */
2262cupsdSendCommand(
2263 cupsd_client_t *con, /* I - Client connection */
2264 char *command, /* I - Command to run */
2265 char *options, /* I - Command-line options */
2266 int root) /* I - Run as root? */
2267{
2268 int fd; /* Standard input file descriptor */
2269
2270
2271 if (con->filename)
ed486911 2272 {
ef416fc2 2273 fd = open(con->filename, O_RDONLY);
ef416fc2 2274
ed486911 2275 if (fd < 0)
2276 {
2277 cupsdLogMessage(CUPSD_LOG_ERROR,
2278 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2279 con->http.fd, con->filename ? con->filename : "/dev/null",
2280 strerror(errno));
2281 return (0);
2282 }
ef416fc2 2283
ed486911 2284 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
2285 }
2286 else
2287 fd = -1;
ef416fc2 2288
2289 con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
2290
ed486911 2291 if (fd >= 0)
2292 close(fd);
ef416fc2 2293
2294 cupsdLogMessage(CUPSD_LOG_INFO, "Started \"%s\" (pid=%d)", command,
2295 con->pipe_pid);
2296
2297 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendCommand: %d file=%d",
2298 con->http.fd, con->file);
2299
2300 if (con->pipe_pid == 0)
2301 return (0);
2302
2303 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2304
f899b121 2305 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
ef416fc2 2306
2307 con->sent_header = 0;
2308 con->file_ready = 0;
2309 con->got_fields = 0;
68b10830 2310 con->header_used = 0;
ef416fc2 2311
2312 return (1);
2313}
2314
2315
2316/*
2317 * 'cupsdSendError()' - Send an error message via HTTP.
2318 */
2319
2320int /* O - 1 if successful, 0 otherwise */
2321cupsdSendError(cupsd_client_t *con, /* I - Connection */
f899b121 2322 http_status_t code, /* I - Error code */
2323 int auth_type)/* I - Authentication type */
ef416fc2 2324{
b9faaae1
MS
2325 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2326 "cupsdSendError(con=%p(%d), code=%d, auth_type=%d", con,
2327 con->http.fd, code, auth_type);
2328
4744bd90 2329#ifdef HAVE_SSL
2330 /*
2331 * Force client to upgrade for authentication if that is how the
2332 * server is configured...
2333 */
2334
2335 if (code == HTTP_UNAUTHORIZED &&
2336 DefaultEncryption == HTTP_ENCRYPT_REQUIRED &&
2337 strcasecmp(con->http.hostname, "localhost") &&
2338 !con->http.tls)
2339 {
4744bd90 2340 code = HTTP_UPGRADE_REQUIRED;
2341 }
2342#endif /* HAVE_SSL */
2343
ef416fc2 2344 /*
2345 * Put the request in the access_log file...
2346 */
2347
2348 cupsdLogRequest(con, code);
2349
ef416fc2 2350 /*
2351 * To work around bugs in some proxies, don't use Keep-Alive for some
2352 * error messages...
f7deaa1a 2353 *
2354 * Kerberos authentication doesn't work without Keep-Alive, so
2355 * never disable it in that case.
ef416fc2 2356 */
2357
5bd77a73 2358 if (code >= HTTP_BAD_REQUEST && con->http.auth_type != CUPSD_AUTH_NEGOTIATE)
ef416fc2 2359 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
2360
2361 /*
2362 * Send an error message back to the client. If the error code is a
2363 * 400 or 500 series, make sure the message contains some text, too!
2364 */
2365
f899b121 2366 if (!cupsdSendHeader(con, code, NULL, auth_type))
ef416fc2 2367 return (0);
2368
2369#ifdef HAVE_SSL
2370 if (code == HTTP_UPGRADE_REQUIRED)
2371 if (httpPrintf(HTTP(con), "Connection: Upgrade\r\n") < 0)
2372 return (0);
2373
2374 if (httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2375 return (0);
2376#endif /* HAVE_SSL */
2377
f7deaa1a 2378 if (con->http.version >= HTTP_1_1 &&
2379 con->http.keep_alive == HTTP_KEEPALIVE_OFF)
ef416fc2 2380 {
2381 if (httpPrintf(HTTP(con), "Connection: close\r\n") < 0)
2382 return (0);
2383 }
2384
2385 if (code >= HTTP_BAD_REQUEST)
2386 {
2387 /*
2388 * Send a human-readable error message.
2389 */
2390
80ca4592 2391 char message[4096], /* Message for user */
2392 urltext[1024], /* URL redirection text */
2393 redirect[1024]; /* Redirection link */
ef416fc2 2394 const char *text; /* Status-specific text */
2395
80ca4592 2396
2397 redirect[0] = '\0';
2398
ef416fc2 2399 if (code == HTTP_UNAUTHORIZED)
2400 text = _cupsLangString(con->language,
2401 _("Enter your username and password or the "
2402 "root username and password to access this "
f7deaa1a 2403 "page. If you are using Kerberos authentication, "
2404 "make sure you have a valid Kerberos ticket."));
ef416fc2 2405 else if (code == HTTP_UPGRADE_REQUIRED)
80ca4592 2406 {
2407 text = urltext;
2408
2409 snprintf(urltext, sizeof(urltext),
2410 _cupsLangString(con->language,
2411 _("You must access this page using the URL "
2412 "<A HREF=\"https://%s:%d%s\">"
2413 "https://%s:%d%s</A>.")),
2414 con->servername, con->serverport, con->uri,
2415 con->servername, con->serverport, con->uri);
2416
2417 snprintf(redirect, sizeof(redirect),
b86bc4cf 2418 "<META HTTP-EQUIV=\"Refresh\" "
2419 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
80ca4592 2420 con->servername, con->serverport, con->uri);
2421 }
ef416fc2 2422 else
2423 text = "";
2424
2425 snprintf(message, sizeof(message),
745129be
MS
2426 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2427 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
ef416fc2 2428 "<HTML>\n"
2429 "<HEAD>\n"
2430 "\t<META HTTP-EQUIV=\"Content-Type\" "
2431 "CONTENT=\"text/html; charset=utf-8\">\n"
2432 "\t<TITLE>%d %s</TITLE>\n"
2433 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2434 "HREF=\"/cups.css\">\n"
80ca4592 2435 "%s"
ef416fc2 2436 "</HEAD>\n"
2437 "<BODY>\n"
2438 "<H1>%d %s</H1>\n"
2439 "<P>%s</P>\n"
2440 "</BODY>\n"
2441 "</HTML>\n",
80ca4592 2442 code, httpStatus(code), redirect, code, httpStatus(code), text);
ef416fc2 2443
2444 if (httpPrintf(HTTP(con), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2445 return (0);
2446 if (httpPrintf(HTTP(con), "Content-Length: %d\r\n",
2447 (int)strlen(message)) < 0)
2448 return (0);
2449 if (httpPrintf(HTTP(con), "\r\n") < 0)
2450 return (0);
2451 if (httpPrintf(HTTP(con), "%s", message) < 0)
2452 return (0);
2453 }
2454 else if (httpPrintf(HTTP(con), "\r\n") < 0)
2455 return (0);
2456
07725fee 2457 if (cupsdFlushHeader(con) < 0)
2458 return (0);
d09495fa 2459
ef416fc2 2460 con->http.state = HTTP_WAITING;
2461
2462 return (1);
2463}
2464
2465
ef416fc2 2466/*
2467 * 'cupsdSendHeader()' - Send an HTTP request.
2468 */
2469
2470int /* O - 1 on success, 0 on failure */
f899b121 2471cupsdSendHeader(
2472 cupsd_client_t *con, /* I - Client to send to */
2473 http_status_t code, /* I - HTTP status code */
2474 char *type, /* I - MIME type of document */
2475 int auth_type) /* I - Type of authentication */
ef416fc2 2476{
5a738aea
MS
2477 char auth_str[1024]; /* Authorization string */
2478#ifdef HAVE_GSSAPI
2479 static char *gss_buf = NULL; /* Kerberos auth data buffer */
2480 static int gss_bufsize = 0; /* Size of Kerberos auth data buffer */
2481#endif /* HAVE_GSSAPI */
f7deaa1a 2482
2483
4744bd90 2484 /*
2485 * Send the HTTP status header...
2486 */
2487
b423cd4c 2488 if (code == HTTP_CONTINUE)
2489 {
4744bd90 2490 /*
2491 * 100-continue doesn't send any headers...
2492 */
2493
07725fee 2494 return (httpPrintf(HTTP(con), "HTTP/%d.%d 100 Continue\r\n\r\n",
2495 con->http.version / 100, con->http.version % 100) > 0);
b423cd4c 2496 }
2497
07725fee 2498 httpFlushWrite(HTTP(con));
2499
2500 con->http.data_encoding = HTTP_ENCODE_FIELDS;
2501
2502 if (httpPrintf(HTTP(con), "HTTP/%d.%d %d %s\r\n", con->http.version / 100,
2503 con->http.version % 100, code, httpStatus(code)) < 0)
2504 return (0);
ef416fc2 2505 if (httpPrintf(HTTP(con), "Date: %s\r\n", httpGetDateString(time(NULL))) < 0)
2506 return (0);
2507 if (ServerHeader)
2508 if (httpPrintf(HTTP(con), "Server: %s\r\n", ServerHeader) < 0)
2509 return (0);
2510 if (con->http.keep_alive && con->http.version >= HTTP_1_0)
2511 {
2512 if (httpPrintf(HTTP(con), "Connection: Keep-Alive\r\n") < 0)
2513 return (0);
2514 if (httpPrintf(HTTP(con), "Keep-Alive: timeout=%d\r\n",
2515 KeepAliveTimeout) < 0)
2516 return (0);
2517 }
2518 if (code == HTTP_METHOD_NOT_ALLOWED)
e6013cfa 2519 if (httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
ef416fc2 2520 return (0);
2521
2522 if (code == HTTP_UNAUTHORIZED)
2523 {
5bd77a73 2524 if (auth_type == CUPSD_AUTH_NONE)
f899b121 2525 {
5bd77a73 2526 if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
f899b121 2527 auth_type = DefaultAuthType;
2528 else
2529 auth_type = con->best->type;
2530 }
f7deaa1a 2531
2532 auth_str[0] = '\0';
2533
5bd77a73 2534 if (auth_type == CUPSD_AUTH_BASIC || auth_type == CUPSD_AUTH_BASICDIGEST)
f7deaa1a 2535 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
5bd77a73 2536 else if (auth_type == CUPSD_AUTH_DIGEST)
f7deaa1a 2537 snprintf(auth_str, sizeof(auth_str), "Digest realm=\"CUPS\", nonce=\"%s\"",
2538 con->http.hostname);
2539#ifdef HAVE_GSSAPI
5bd77a73 2540 else if (auth_type == CUPSD_AUTH_NEGOTIATE && con->gss_output_token.length == 0)
f7deaa1a 2541 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2542#endif /* HAVE_GSSAPI */
2543
e07d4801
MS
2544 if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
2545 !strcasecmp(con->http.hostname, "localhost"))
ef416fc2 2546 {
e07d4801
MS
2547 /*
2548 * Add a "trc" (try root certification) parameter for local non-Kerberos
2549 * requests when the request requires system group membership - then the
2550 * client knows the root certificate can/should be used.
2551 *
2552 * Also, for Mac OS X we also look for @AUTHKEY and add an "authkey"
2553 * parameter as needed...
2554 */
2555
2556 int i; /* Looping var */
f7deaa1a 2557 char *auth_key; /* Auth key buffer */
2558 size_t auth_size; /* Size of remaining buffer */
2559
f7deaa1a 2560 auth_key = auth_str + strlen(auth_str);
2561 auth_size = sizeof(auth_str) - (auth_key - auth_str);
2562
2563 for (i = 0; i < con->best->num_names; i ++)
2564 {
e07d4801 2565#ifdef HAVE_AUTHORIZATION_H
f7deaa1a 2566 if (!strncasecmp(con->best->names[i], "@AUTHKEY(", 9))
2567 {
2568 snprintf(auth_key, auth_size, ", authkey=\"%s\"",
2569 con->best->names[i] + 9);
2570 /* end parenthesis is stripped in conf.c */
2571 break;
2572 }
e07d4801
MS
2573 else
2574#endif /* HAVE_AUTHORIZATION_H */
2575 if (!strcasecmp(con->best->names[i], "@SYSTEM"))
f7deaa1a 2576 {
e07d4801
MS
2577#ifdef HAVE_AUTHORIZATION_H
2578 if (SystemGroupAuthKey)
2579 snprintf(auth_key, auth_size,
2580 ", authkey=\"%s\", trc=\"y\"",
2581 SystemGroupAuthKey);
2582 else
2583#else
f11a948a 2584 strlcpy(auth_key, ", trc=\"y\"", auth_size);
e07d4801 2585#endif /* HAVE_AUTHORIZATION_H */
f7deaa1a 2586 break;
2587 }
2588 }
ef416fc2 2589 }
f7deaa1a 2590
bc44d920 2591 if (auth_str[0])
2592 {
68b10830
MS
2593 cupsdLogMessage(CUPSD_LOG_DEBUG,
2594 "cupsdSendHeader: %d WWW-Authenticate: %s", con->http.fd,
bc44d920 2595 auth_str);
2596
2597 if (httpPrintf(HTTP(con), "WWW-Authenticate: %s\r\n", auth_str) < 0)
2598 return (0);
2599 }
ef416fc2 2600 }
2601
f7deaa1a 2602#ifdef HAVE_GSSAPI
2603 /*
2604 * WWW-Authenticate: Negotiate can be included even for
2605 * non-401 replies...
2606 */
2607
5a738aea 2608 if (con->gss_output_token.length > 0 && con->gss_output_token.length <= 65536)
f7deaa1a 2609 {
f7deaa1a 2610 OM_uint32 minor_status; /* Minor status code */
5a738aea
MS
2611 int bufsize; /* Size of output token buffer */
2612
2613
2614 bufsize = con->gss_output_token.length * 4 / 3 + 2;
2615
2616 if (bufsize > gss_bufsize)
2617 {
2618 char *buf; /* New buffer */
2619
f7deaa1a 2620
5a738aea 2621 bufsize = (bufsize + 1023) & 1023;/* Round up */
f7deaa1a 2622
5a738aea
MS
2623 if (gss_buf)
2624 buf = realloc(gss_buf, bufsize);
2625 else
2626 buf = malloc(bufsize);
2627
2628 if (!buf)
2629 {
2630 cupsdLogMessage(CUPSD_LOG_ERROR,
2631 "Unable to allocate %d bytes for Kerberos credentials!",
2632 bufsize);
2633 return (0);
2634 }
2635
2636 gss_buf = buf;
2637 gss_bufsize = bufsize;
2638 }
2639
2640 httpEncode64_2(gss_buf, gss_bufsize,
2641 con->gss_output_token.value,
f7deaa1a 2642 con->gss_output_token.length);
2643 gss_release_buffer(&minor_status, &con->gss_output_token);
2644
355e94dc 2645 cupsdLogMessage(CUPSD_LOG_DEBUG,
5a738aea 2646 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf);
355e94dc 2647
5a738aea
MS
2648 if (httpPrintf(HTTP(con), "WWW-Authenticate: Negotiate %s\r\n",
2649 gss_buf) < 0)
f7deaa1a 2650 return (0);
2651 }
5a738aea
MS
2652 else if (con->gss_output_token.length > 65536)
2653 {
2654 cupsdLogMessage(CUPSD_LOG_ERROR,
2655 "Kerberos credentials larger than 64k (%d)!",
ac884b6a 2656 (int)con->gss_output_token.length);
5a738aea
MS
2657 return (0);
2658 }
f7deaa1a 2659#endif /* HAVE_GSSAPI */
2660
e1d6a774 2661 if (con->language && strcmp(con->language->language, "C"))
ef416fc2 2662 {
2663 if (httpPrintf(HTTP(con), "Content-Language: %s\r\n",
2664 con->language->language) < 0)
2665 return (0);
2666 }
2667
e1d6a774 2668 if (type)
ef416fc2 2669 {
2670 if (!strcmp(type, "text/html"))
2671 {
2672 if (httpPrintf(HTTP(con),
2673 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2674 return (0);
2675 }
2676 else if (httpPrintf(HTTP(con), "Content-Type: %s\r\n", type) < 0)
2677 return (0);
2678 }
2679
2680 return (1);
2681}
2682
2683
2684/*
2685 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2686 */
2687
2688void
2689cupsdUpdateCGI(void)
2690{
2691 char *ptr, /* Pointer to end of line in buffer */
2692 message[1024]; /* Pointer to message text */
2693 int loglevel; /* Log level for message */
2694
2695
2696 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2697 message, sizeof(message))) != NULL)
f0ab5bff
MS
2698 {
2699 if (loglevel == CUPSD_LOG_INFO)
2700 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
2701
ef416fc2 2702 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2703 break;
f0ab5bff 2704 }
ef416fc2 2705
d09495fa 2706 if (ptr == NULL && !CGIStatusBuffer->bufused)
ef416fc2 2707 {
2708 /*
2709 * Fatal error on pipe - should never happen!
2710 */
2711
2712 cupsdLogMessage(CUPSD_LOG_CRIT,
2713 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2714 strerror(errno));
2715 }
2716}
2717
2718
2719/*
2720 * 'cupsdWriteClient()' - Write data to a client as needed.
2721 */
2722
f7deaa1a 2723void
ef416fc2 2724cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2725{
68b10830
MS
2726 int bytes, /* Number of bytes written */
2727 field_col; /* Current column */
2728 char *bufptr, /* Pointer into buffer */
2729 *bufend; /* Pointer to end of buffer */
ef416fc2 2730 ipp_state_t ipp_state; /* IPP state value */
2731
2732
ef416fc2 2733 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1 2734 "cupsdWriteClient(con=%p(%d)) response=%p(%d), file=%d "
ef416fc2 2735 "pipe_pid=%d state=%d",
ae71f5de
MS
2736 con, con->http.fd, con->response,
2737 con->response ? con->response->state : -1,
b94498cf 2738 con->file, con->pipe_pid, con->http.state);
ef416fc2 2739
2740 if (con->http.state != HTTP_GET_SEND &&
2741 con->http.state != HTTP_POST_SEND)
8b116e60
MS
2742 {
2743 /*
2744 * If we get called in the wrong state, then something went wrong with the
2745 * connection and we need to shut it down...
2746 */
2747
f11a948a
MS
2748 cupsdLogMessage(CUPSD_LOG_DEBUG,
2749 "cupsdWriteClient: %d Closing on unknown HTTP state %d",
2750 con->http.fd, con->http.state);
8b116e60 2751 cupsdCloseClient(con);
f7deaa1a 2752 return;
8b116e60 2753 }
f7deaa1a 2754
2755 if (con->pipe_pid)
2756 {
2757 /*
2758 * Make sure we select on the CGI output...
2759 */
2760
f899b121 2761 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
f7deaa1a 2762
2763 if (!con->file_ready)
2764 {
2765 /*
2766 * Try again later when there is CGI output available...
2767 */
2768
2769 cupsdRemoveSelect(con->http.fd);
2770 return;
2771 }
2772
2773 con->file_ready = 0;
2774 }
ef416fc2 2775
b94498cf 2776 if (con->response && con->response->state != IPP_DATA)
ef416fc2 2777 {
07725fee 2778 ipp_state = ippWrite(HTTP(con), con->response);
b94498cf 2779 bytes = ipp_state != IPP_ERROR &&
2780 (con->file >= 0 || ipp_state != IPP_DATA);
ef416fc2 2781 }
68b10830
MS
2782 else if ((bytes = read(con->file, con->header,
2783 sizeof(con->header) - con->header_used)) > 0)
ef416fc2 2784 {
68b10830
MS
2785 con->header_used += bytes;
2786
ef416fc2 2787 if (con->pipe_pid && !con->got_fields)
2788 {
2789 /*
2790 * Inspect the data for Content-Type and other fields.
2791 */
2792
68b10830
MS
2793 for (bufptr = con->header, bufend = con->header + con->header_used,
2794 field_col = 0;
2795 !con->got_fields && bufptr < bufend;
2796 bufptr ++)
d1c13e16 2797 {
ef416fc2 2798 if (*bufptr == '\n')
2799 {
2800 /*
2801 * Send line to client...
2802 */
2803
68b10830 2804 if (bufptr > con->header && bufptr[-1] == '\r')
ef416fc2 2805 bufptr[-1] = '\0';
2806 *bufptr++ = '\0';
2807
68b10830 2808 cupsdLogMessage(CUPSD_LOG_DEBUG, "Script header: %s", con->header);
ef416fc2 2809
2810 if (!con->sent_header)
2811 {
2812 /*
2813 * Handle redirection and CGI status codes...
2814 */
2815
68b10830 2816 if (!strncasecmp(con->header, "Location:", 9))
d6ae789d 2817 {
5bd77a73 2818 cupsdSendHeader(con, HTTP_SEE_OTHER, NULL, CUPSD_AUTH_NONE);
07725fee 2819 con->sent_header = 2;
2820
d6ae789d 2821 if (httpPrintf(HTTP(con), "Content-Length: 0\r\n") < 0)
f7deaa1a 2822 return;
d6ae789d 2823 }
68b10830 2824 else if (!strncasecmp(con->header, "Status:", 7))
07725fee 2825 {
68b10830
MS
2826 cupsdSendError(con, (http_status_t)atoi(con->header + 7),
2827 CUPSD_AUTH_NONE);
07725fee 2828 con->sent_header = 2;
2829 }
ef416fc2 2830 else
4744bd90 2831 {
5bd77a73 2832 cupsdSendHeader(con, HTTP_OK, NULL, CUPSD_AUTH_NONE);
07725fee 2833 con->sent_header = 1;
ef416fc2 2834
4744bd90 2835 if (con->http.version == HTTP_1_1)
2836 {
4744bd90 2837 if (httpPrintf(HTTP(con), "Transfer-Encoding: chunked\r\n") < 0)
f7deaa1a 2838 return;
4744bd90 2839 }
2840 }
ef416fc2 2841 }
2842
68b10830
MS
2843 if (strncasecmp(con->header, "Status:", 7))
2844 httpPrintf(HTTP(con), "%s\r\n", con->header);
ef416fc2 2845
ef416fc2 2846 /*
2847 * Update buffer...
2848 */
2849
68b10830 2850 con->header_used -= bufptr - con->header;
d1c13e16 2851
68b10830
MS
2852 if (con->header_used > 0)
2853 memmove(con->header, bufptr, con->header_used);
d1c13e16 2854
68b10830 2855 bufptr = con->header - 1;
ef416fc2 2856
2857 /*
2858 * See if the line was empty...
2859 */
2860
68b10830 2861 if (field_col == 0)
d09495fa 2862 {
ef416fc2 2863 con->got_fields = 1;
d09495fa 2864
07725fee 2865 if (cupsdFlushHeader(con) < 0)
2866 {
2867 cupsdCloseClient(con);
f7deaa1a 2868 return;
07725fee 2869 }
d09495fa 2870
2871 if (con->http.version == HTTP_1_1)
2872 con->http.data_encoding = HTTP_ENCODE_CHUNKED;
2873 }
ef416fc2 2874 else
68b10830 2875 field_col = 0;
ef416fc2 2876 }
2877 else if (*bufptr != '\r')
68b10830 2878 field_col ++;
d1c13e16 2879 }
ef416fc2 2880
68b10830 2881 if (!con->got_fields)
47879b8b 2882 {
ef416fc2 2883 con->http.activity = time(NULL);
47879b8b
MS
2884 return;
2885 }
ef416fc2 2886 }
2887
68b10830 2888 if (con->header_used > 0)
ef416fc2 2889 {
68b10830 2890 if (httpWrite2(HTTP(con), con->header, con->header_used) < 0)
4744bd90 2891 {
f11a948a
MS
2892 cupsdLogMessage(CUPSD_LOG_DEBUG,
2893 "cupsdWriteClient: %d Closing for error %d (%s)",
2894 con->http.fd, con->http.error,
2895 strerror(con->http.error));
4744bd90 2896 cupsdCloseClient(con);
f7deaa1a 2897 return;
4744bd90 2898 }
ef416fc2 2899
01ce6322
MS
2900 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED)
2901 httpFlushWrite(HTTP(con));
ae71f5de 2902
68b10830 2903 con->bytes += con->header_used;
ef416fc2 2904
4744bd90 2905 if (con->http.state == HTTP_WAITING)
2906 bytes = 0;
68b10830
MS
2907 else
2908 bytes = con->header_used;
2909
2910 con->header_used = 0;
4744bd90 2911 }
ef416fc2 2912 }
2913
8b116e60
MS
2914 if (bytes <= 0 ||
2915 (con->http.state != HTTP_GET_SEND && con->http.state != HTTP_POST_SEND))
ef416fc2 2916 {
38e73f87 2917 if (!con->sent_header && con->pipe_pid)
94da7e34
MS
2918 cupsdSendError(con, HTTP_SERVER_ERROR, CUPSD_AUTH_NONE);
2919 else
2920 {
2921 cupsdLogRequest(con, HTTP_OK);
ef416fc2 2922
94da7e34 2923 httpFlushWrite(HTTP(con));
ef416fc2 2924
94da7e34 2925 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED && con->sent_header == 1)
ef416fc2 2926 {
94da7e34
MS
2927 if (httpWrite2(HTTP(con), "", 0) < 0)
2928 {
f11a948a
MS
2929 cupsdLogMessage(CUPSD_LOG_DEBUG,
2930 "cupsdWriteClient: %d Closing for error %d (%s)",
2931 con->http.fd, con->http.error,
2932 strerror(con->http.error));
94da7e34
MS
2933 cupsdCloseClient(con);
2934 return;
2935 }
ef416fc2 2936 }
2937 }
2938
2939 con->http.state = HTTP_WAITING;
2940
f7deaa1a 2941 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 2942
2943 if (con->file >= 0)
2944 {
f7deaa1a 2945 cupsdRemoveSelect(con->file);
ef416fc2 2946
2947 if (con->pipe_pid)
2948 cupsdEndProcess(con->pipe_pid, 0);
2949
ef416fc2 2950 close(con->file);
2951 con->file = -1;
2952 con->pipe_pid = 0;
2953 }
2954
2955 if (con->filename)
2956 {
ef416fc2 2957 unlink(con->filename);
2958 cupsdClearString(&con->filename);
2959 }
2960
2abf387c 2961 if (con->request)
ef416fc2 2962 {
2963 ippDelete(con->request);
2964 con->request = NULL;
2965 }
2966
2abf387c 2967 if (con->response)
ef416fc2 2968 {
2969 ippDelete(con->response);
2970 con->response = NULL;
2971 }
2972
2973 cupsdClearString(&con->command);
2974 cupsdClearString(&con->options);
b86bc4cf 2975 cupsdClearString(&con->query_string);
ef416fc2 2976
2977 if (!con->http.keep_alive)
2978 {
f11a948a
MS
2979 cupsdLogMessage(CUPSD_LOG_DEBUG,
2980 "cupsdWriteClient: %d Closing because Keep-Alive disabled",
2981 con->http.fd);
ef416fc2 2982 cupsdCloseClient(con);
f7deaa1a 2983 return;
ef416fc2 2984 }
f11a948a
MS
2985 else
2986 {
2987 cupsArrayRemove(ActiveClients, con);
2988 cupsdSetBusyState();
2989 }
ef416fc2 2990 }
2991
2992 con->http.activity = time(NULL);
f7deaa1a 2993}
ef416fc2 2994
f7deaa1a 2995
e1d6a774 2996/*
2997 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2998 */
2999
3000static int /* O - 1 if modified since */
3001check_if_modified(
3002 cupsd_client_t *con, /* I - Client connection */
3003 struct stat *filestats) /* I - File information */
3004{
3005 char *ptr; /* Pointer into field */
3006 time_t date; /* Time/date value */
3007 off_t size; /* Size/length value */
3008
3009
3010 size = 0;
3011 date = 0;
3012 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
3013
3014 if (*ptr == '\0')
3015 return (1);
3016
3017 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
3018 "check_if_modified(con=%p(%d), "
3019 "filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"",
3020 con, con->http.fd, filestats, CUPS_LLCAST filestats->st_size,
3021 (int)filestats->st_mtime, ptr);
e1d6a774 3022
3023 while (*ptr != '\0')
3024 {
3025 while (isspace(*ptr) || *ptr == ';')
3026 ptr ++;
3027
3028 if (strncasecmp(ptr, "length=", 7) == 0)
3029 {
3030 ptr += 7;
3031 size = strtoll(ptr, NULL, 10);
3032
3033 while (isdigit(*ptr))
3034 ptr ++;
3035 }
3036 else if (isalpha(*ptr))
3037 {
3038 date = httpGetDateTime(ptr);
3039 while (*ptr != '\0' && *ptr != ';')
3040 ptr ++;
3041 }
e53920b9 3042 else
3043 ptr ++;
e1d6a774 3044 }
3045
e1d6a774 3046 return ((size != filestats->st_size && size != 0) ||
3047 (date < filestats->st_mtime && date != 0) ||
3048 (size == 0 && date == 0));
3049}
3050
3051
3dfe78b3
MS
3052/*
3053 * 'compare_clients()' - Compare two client connections.
3054 */
3055
3056static int /* O - Result of comparison */
3057compare_clients(cupsd_client_t *a, /* I - First client */
3058 cupsd_client_t *b, /* I - Second client */
3059 void *data) /* I - User data (not used) */
3060{
3061 (void)data;
3062
3063 if (a == b)
3064 return (0);
3065 else if (a < b)
3066 return (-1);
3067 else
3068 return (1);
3069}
3070
3071
ee571f26
MS
3072/*
3073 * 'data_ready()' - Check whether data is available from a client.
3074 */
3075
3076static int /* O - 1 if data is ready, 0 otherwise */
3077data_ready(cupsd_client_t *con) /* I - Client */
3078{
3079 if (con->http.used > 0)
3080 return (1);
3081#ifdef HAVE_SSL
3082 else if (con->http.tls)
3083 {
3084# ifdef HAVE_LIBSSL
3085 if (SSL_pending((SSL *)(con->http.tls)))
3086 return (1);
3087# elif defined(HAVE_GNUTLS)
3088 if (gnutls_record_check_pending(((http_tls_t *)(con->http.tls))->session))
3089 return (1);
3090# elif defined(HAVE_CDSASSL)
3091 size_t bytes; /* Bytes that are available */
3092
3093 if (!SSLGetBufferedReadSize(((http_tls_t *)(con->http.tls))->session,
3094 &bytes) && bytes > 0)
3095 return (1);
3096# endif /* HAVE_LIBSSL */
3097 }
3098#endif /* HAVE_SSL */
3099
3100 return (0);
3101}
3102
3103
80ca4592 3104#ifdef HAVE_SSL
e1d6a774 3105/*
3106 * 'encrypt_client()' - Enable encryption for the client...
3107 */
3108
3109static int /* O - 1 on success, 0 on error */
3110encrypt_client(cupsd_client_t *con) /* I - Client to encrypt */
3111{
80ca4592 3112# ifdef HAVE_LIBSSL
e1d6a774 3113 SSL_CTX *context; /* Context for encryption */
3114 SSL *conn; /* Connection for encryption */
411affcf 3115 BIO *bio; /* BIO data */
e1d6a774 3116 unsigned long error; /* Error code */
3117
3118
b9faaae1
MS
3119 cupsdLogMessage(CUPSD_LOG_DEBUG2, "encrypt_client(con=%p(%d))", con,
3120 con->http.fd);
3121
8ca02f3c 3122 /*
3123 * Verify that we have a certificate...
3124 */
3125
3126 if (access(ServerKey, 0) || access(ServerCertificate, 0))
3127 {
3128 /*
3129 * Nope, make a self-signed certificate...
3130 */
3131
b86bc4cf 3132 if (!make_certificate(con))
8ca02f3c 3133 return (0);
3134 }
3135
e1d6a774 3136 /*
3137 * Create the SSL context and accept the connection...
3138 */
3139
3140 context = SSL_CTX_new(SSLv23_server_method());
3141
3142 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
b19ccc9e 3143 if (SSLOptions & CUPSD_SSL_NOEMPTY)
58dc1933 3144 SSL_CTX_set_options(context, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
e1d6a774 3145 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
58dc1933 3146 SSL_CTX_use_certificate_chain_file(context, ServerCertificate);
e1d6a774 3147
411affcf 3148 bio = BIO_new(_httpBIOMethods());
3149 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)HTTP(con));
3150
e1d6a774 3151 conn = SSL_new(context);
411affcf 3152 SSL_set_bio(conn, bio, bio);
e1d6a774 3153
e1d6a774 3154 if (SSL_accept(conn) != 1)
3155 {
b9faaae1 3156 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to encrypt connection from %s!",
e1d6a774 3157 con->http.hostname);
3158
3159 while ((error = ERR_get_error()) != 0)
b9faaae1 3160 cupsdLogMessage(CUPSD_LOG_ERROR, "%s", ERR_error_string(error, NULL));
e1d6a774 3161
3162 SSL_CTX_free(context);
3163 SSL_free(conn);
3164 return (0);
3165 }
3166
b9faaae1
MS
3167 cupsdLogMessage(CUPSD_LOG_DEBUG, "Connection from %s now encrypted.",
3168 con->http.hostname);
e1d6a774 3169
3170 con->http.tls = conn;
3171 return (1);
f7deaa1a 3172
80ca4592 3173# elif defined(HAVE_GNUTLS)
e1d6a774 3174 http_tls_t *conn; /* TLS session object */
3175 int error; /* Error code */
3176 gnutls_certificate_server_credentials *credentials;
3177 /* TLS credentials */
3178
3179
b9faaae1
MS
3180 cupsdLogMessage(CUPSD_LOG_DEBUG2, "encrypt_client(con=%p(%d))", con,
3181 con->http.fd);
3182
e1d6a774 3183 /*
3184 * Verify that we have a certificate...
3185 */
3186
3187 if (access(ServerKey, 0) || access(ServerCertificate, 0))
3188 {
3189 /*
3190 * Nope, make a self-signed certificate...
3191 */
3192
b86bc4cf 3193 if (!make_certificate(con))
8ca02f3c 3194 return (0);
e1d6a774 3195 }
3196
3197 /*
3198 * Create the SSL object and perform the SSL handshake...
3199 */
3200
89d46774 3201 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
e1d6a774 3202
3203 if (conn == NULL)
3204 return (0);
3205
3206 credentials = (gnutls_certificate_server_credentials *)
3207 malloc(sizeof(gnutls_certificate_server_credentials));
3208 if (credentials == NULL)
3209 {
3210 cupsdLogMessage(CUPSD_LOG_ERROR,
b9faaae1
MS
3211 "Unable to encrypt connection from %s - %s",
3212 con->http.hostname, strerror(errno));
e1d6a774 3213
3214 free(conn);
3215 return (0);
3216 }
3217
3218 gnutls_certificate_allocate_credentials(credentials);
f7deaa1a 3219 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
e1d6a774 3220 ServerKey, GNUTLS_X509_FMT_PEM);
3221
3222 gnutls_init(&(conn->session), GNUTLS_SERVER);
3223 gnutls_set_default_priority(conn->session);
3224 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
411affcf 3225 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)HTTP(con));
3226 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
3227 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
e1d6a774 3228
3229 error = gnutls_handshake(conn->session);
3230
3231 if (error != GNUTLS_E_SUCCESS)
3232 {
3233 cupsdLogMessage(CUPSD_LOG_ERROR,
b9faaae1
MS
3234 "Unable to encrypt connection from %s - %s",
3235 con->http.hostname, gnutls_strerror(error));
e1d6a774 3236
3237 gnutls_deinit(conn->session);
3238 gnutls_certificate_free_credentials(*credentials);
3239 free(conn);
3240 free(credentials);
3241 return (0);
3242 }
3243
b9faaae1
MS
3244 cupsdLogMessage(CUPSD_LOG_DEBUG, "Connection from %s now encrypted.",
3245 con->http.hostname);
e1d6a774 3246
3247 conn->credentials = credentials;
3248 con->http.tls = conn;
3249 return (1);
3250
80ca4592 3251# elif defined(HAVE_CDSASSL)
89d46774 3252 OSStatus error; /* Error code */
3253 http_tls_t *conn; /* CDSA connection information */
e1d6a774 3254
3255
b9faaae1
MS
3256 cupsdLogMessage(CUPSD_LOG_DEBUG2, "encrypt_client(con=%p(%d))", con,
3257 con->http.fd);
3258
89d46774 3259 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
3260 return (0);
e1d6a774 3261
89d46774 3262 error = 0;
3263 conn->session = NULL;
b86bc4cf 3264 conn->certsArray = get_cdsa_certificate(con);
e1d6a774 3265
8ca02f3c 3266 if (!conn->certsArray)
3267 {
3268 /*
3269 * No keychain (yet), make a self-signed certificate...
3270 */
3271
b86bc4cf 3272 if (make_certificate(con))
3273 conn->certsArray = get_cdsa_certificate(con);
8ca02f3c 3274 }
3275
89d46774 3276 if (!conn->certsArray)
e1d6a774 3277 {
3278 cupsdLogMessage(CUPSD_LOG_ERROR,
b9faaae1
MS
3279 "Could not find signing key in keychain \"%s\"",
3280 ServerCertificate);
e1d6a774 3281 error = errSSLBadCert; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3282 }
3283
3284 if (!error)
89d46774 3285 error = SSLNewContext(true, &conn->session);
e1d6a774 3286
3287 if (!error)
89d46774 3288 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
3289
3290 if (!error)
ed486911 3291 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
e1d6a774 3292
3293 if (!error)
411affcf 3294 error = SSLSetConnection(conn->session, HTTP(con));
e1d6a774 3295
3296 if (!error)
89d46774 3297 error = SSLSetAllowsExpiredCerts(conn->session, true);
e1d6a774 3298
3299 if (!error)
89d46774 3300 error = SSLSetAllowsAnyRoot(conn->session, true);
ef416fc2 3301
89d46774 3302 if (!error)
3303 error = SSLSetCertificate(conn->session, conn->certsArray);
ef416fc2 3304
e1d6a774 3305 if (!error)
3306 {
3307 /*
3308 * Perform SSL/TLS handshake
3309 */
ef416fc2 3310
89d46774 3311 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
e1d6a774 3312 usleep(1000);
3313 }
ef416fc2 3314
e1d6a774 3315 if (error)
3316 {
3317 cupsdLogMessage(CUPSD_LOG_ERROR,
b9faaae1
MS
3318 "Unable to encrypt connection from %s - %s (%d)",
3319 con->http.hostname, cssmErrorString(error), (int)error);
ef416fc2 3320
e1d6a774 3321 con->http.error = error;
3322 con->http.status = HTTP_ERROR;
ef416fc2 3323
89d46774 3324 if (conn->session)
3325 SSLDisposeContext(conn->session);
3326
3327 if (conn->certsArray)
3328 CFRelease(conn->certsArray);
3329
3330 free(conn);
ef416fc2 3331
e1d6a774 3332 return (0);
ef416fc2 3333 }
3334
b9faaae1
MS
3335 cupsdLogMessage(CUPSD_LOG_DEBUG, "Connection from %s now encrypted.",
3336 con->http.hostname);
ef416fc2 3337
e1d6a774 3338 con->http.tls = conn;
3339 return (1);
3340
80ca4592 3341# endif /* HAVE_LIBSSL */
ef416fc2 3342}
80ca4592 3343#endif /* HAVE_SSL */
ef416fc2 3344
3345
3346#ifdef HAVE_CDSASSL
3347/*
b86bc4cf 3348 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
ef416fc2 3349 */
3350
4a4b4f99
MS
3351static CFArrayRef /* O - Array of certificates */
3352get_cdsa_certificate(
3353 cupsd_client_t *con) /* I - Client connection */
ef416fc2 3354{
3355 OSStatus err; /* Error info */
b86bc4cf 3356 SecKeychainRef keychain; /* Keychain reference */
3357 SecIdentitySearchRef search; /* Search reference */
ef416fc2 3358 SecIdentityRef identity; /* Identity */
b86bc4cf 3359 CFArrayRef certificates = NULL;
3360 /* Certificate array */
ef416fc2 3361
3362
b86bc4cf 3363 if ((err = SecKeychainOpen(ServerCertificate, &keychain)))
3364 {
b9faaae1
MS
3365 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\" - %s (%d)",
3366 ServerCertificate, cssmErrorString(err), (int)err);
b86bc4cf 3367 return (NULL);
3368 }
ef416fc2 3369
b86bc4cf 3370# if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3371 /*
3372 * Use a policy to search for valid certificates who's common name matches the
3373 * servername...
3374 */
3375
3376 SecPolicySearchRef policy_search; /* Policy search ref */
3377 SecPolicyRef policy; /* Policy ref */
3378 CSSM_DATA options; /* Policy options */
3379 CSSM_APPLE_TP_SSL_OPTIONS
3380 ssl_options; /* SSL Option for hostname */
4a4b4f99 3381 char localname[1024];/* Local hostname */
b86bc4cf 3382
3383
1f0275e3
MS
3384 if (SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL,
3385 NULL, &policy_search))
ef416fc2 3386 {
b86bc4cf 3387 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create a policy search reference");
3388 CFRelease(keychain);
3389 return (NULL);
3390 }
ef416fc2 3391
1f0275e3 3392 if (SecPolicySearchCopyNext(policy_search, &policy))
b86bc4cf 3393 {
b9faaae1 3394 cupsdLogMessage(CUPSD_LOG_ERROR,
b86bc4cf 3395 "Cannot find a policy to use for searching");
3396 CFRelease(keychain);
3397 CFRelease(policy_search);
3398 return (NULL);
3399 }
ef416fc2 3400
b86bc4cf 3401 memset(&ssl_options, 0, sizeof(ssl_options));
3402 ssl_options.Version = CSSM_APPLE_TP_SSL_OPTS_VERSION;
3403 ssl_options.ServerName = con->servername;
3404 ssl_options.ServerNameLen = strlen(con->servername);
ef416fc2 3405
e07d4801
MS
3406 cupsdLogMessage(CUPSD_LOG_DEBUG,
3407 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3408 con->servername);
3409
b86bc4cf 3410 options.Data = (uint8 *)&ssl_options;
3411 options.Length = sizeof(ssl_options);
3412
1f0275e3 3413 if (SecPolicySetValue(policy, &options))
b86bc4cf 3414 {
b9faaae1 3415 cupsdLogMessage(CUPSD_LOG_ERROR,
b86bc4cf 3416 "Cannot set policy value to use for searching");
3417 CFRelease(keychain);
3418 CFRelease(policy_search);
3419 return (NULL);
3420 }
3421
3422 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3423 keychain, FALSE, &search);
4a4b4f99
MS
3424 if (err && DNSSDHostName)
3425 {
3426 /*
3427 * Search for the connection server name failed; try the DNS-SD .local
3428 * hostname instead...
3429 */
3430
3431 snprintf(localname, sizeof(localname), "%s.local", DNSSDHostName);
3432
3433 ssl_options.ServerName = localname;
3434 ssl_options.ServerNameLen = strlen(localname);
3435
3436 cupsdLogMessage(CUPSD_LOG_DEBUG,
3437 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3438 localname);
3439
3440 if (SecPolicySetValue(policy, &options))
3441 {
3442 cupsdLogMessage(CUPSD_LOG_ERROR,
3443 "Cannot set policy value to use for searching");
3444 CFRelease(keychain);
3445 CFRelease(policy_search);
3446 return (NULL);
3447 }
3448
3449 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3450 keychain, FALSE, &search);
3451 }
3452
b86bc4cf 3453# else
3454 /*
3455 * Assume there is exactly one SecIdentity in the keychain...
3456 */
3457
3458 err = SecIdentitySearchCreate(keychain, CSSM_KEYUSE_SIGN, &search);
3459# endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3460
3461 if (err)
3462 cupsdLogMessage(CUPSD_LOG_DEBUG,
b9faaae1
MS
3463 "Cannot create keychain search reference: %s (%d)",
3464 cssmErrorString(err), (int)err);
b86bc4cf 3465 else
3466 {
3467 if ((err = SecIdentitySearchCopyNext(search, &identity)))
3468 {
3469 cupsdLogMessage(CUPSD_LOG_DEBUG,
b9faaae1
MS
3470 "Cannot find signing key in keychain \"%s\": %s (%d)",
3471 ServerCertificate, cssmErrorString(err), (int)err);
b86bc4cf 3472 }
3473 else
3474 {
3475 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3476 cupsdLogMessage(CUPSD_LOG_ERROR,
3477 "SecIdentitySearchCopyNext CFTypeID failure!");
ef416fc2 3478 else
3479 {
b86bc4cf 3480 if ((certificates = CFArrayCreate(NULL, (const void **)&identity,
3481 1, &kCFTypeArrayCallBacks)) == NULL)
3482 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create certificate array");
ef416fc2 3483 }
3484
b86bc4cf 3485 CFRelease(identity);
ef416fc2 3486 }
3487
b86bc4cf 3488 CFRelease(search);
ef416fc2 3489 }
3490
b86bc4cf 3491# if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3492 CFRelease(policy);
3493 CFRelease(policy_search);
3494# endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3495
3496 return (certificates);
ef416fc2 3497}
3498#endif /* HAVE_CDSASSL */
3499
3500
3501/*
3502 * 'get_file()' - Get a filename and state info.
3503 */
3504
3505static char * /* O - Real filename */
3506get_file(cupsd_client_t *con, /* I - Client connection */
3507 struct stat *filestats, /* O - File information */
3508 char *filename, /* IO - Filename buffer */
3509 int len) /* I - Buffer length */
3510{
3511 int status; /* Status of filesystem calls */
3512 char *ptr; /* Pointer info filename */
3513 int plen; /* Remaining length after pointer */
db1f069b 3514 char language[7]; /* Language subdirectory, if any */
ef416fc2 3515
3516
3517 /*
f7deaa1a 3518 * Figure out the real filename...
ef416fc2 3519 */
3520
db1f069b
MS
3521 language[0] = '\0';
3522
ef416fc2 3523 if (!strncmp(con->uri, "/ppd/", 5))
3524 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
f7deaa1a 3525 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3526 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
ef416fc2 3527 else if (!strncmp(con->uri, "/admin/conf/", 12))
3528 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3529 else if (!strncmp(con->uri, "/admin/log/", 11))
3530 {
2e4ff8af 3531 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
ef416fc2 3532 strlcpy(filename, AccessLog, len);
2e4ff8af 3533 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
ef416fc2 3534 strlcpy(filename, ErrorLog, len);
2e4ff8af 3535 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
ef416fc2 3536 strlcpy(filename, PageLog, len);
3537 else
3538 return (NULL);
3539 }
d6ae789d 3540 else if (con->language)
db1f069b
MS
3541 {
3542 snprintf(language, sizeof(language), "/%s", con->language->language);
3543 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3544 }
ef416fc2 3545 else
3546 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3547
3548 if ((ptr = strchr(filename, '?')) != NULL)
3549 *ptr = '\0';
3550
3551 /*
3552 * Grab the status for this language; if there isn't a language-specific file
3553 * then fallback to the default one...
3554 */
3555
db1f069b 3556 if ((status = stat(filename, filestats)) != 0 && language[0] &&
d6ae789d 3557 strncmp(con->uri, "/ppd/", 5) &&
3558 strncmp(con->uri, "/admin/conf/", 12) &&
3559 strncmp(con->uri, "/admin/log/", 11))
ef416fc2 3560 {
3561 /*
d6ae789d 3562 * Drop the country code...
ef416fc2 3563 */
3564
db1f069b
MS
3565 language[3] = '\0';
3566 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
d6ae789d 3567
3568 if ((ptr = strchr(filename, '?')) != NULL)
3569 *ptr = '\0';
3570
3571 if ((status = stat(filename, filestats)) != 0)
ef416fc2 3572 {
d6ae789d 3573 /*
3574 * Drop the language prefix and try the root directory...
3575 */
3576
db1f069b 3577 language[0] = '\0';
ef416fc2 3578 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3579
3580 if ((ptr = strchr(filename, '?')) != NULL)
3581 *ptr = '\0';
3582
3583 status = stat(filename, filestats);
3584 }
3585 }
3586
3587 /*
3588 * If we're found a directory, get the index.html file instead...
3589 */
3590
3591 if (!status && S_ISDIR(filestats->st_mode))
3592 {
db1f069b
MS
3593 /*
3594 * Make sure the URI ends with a slash...
3595 */
ef416fc2 3596
db1f069b
MS
3597 if (con->uri[strlen(con->uri) - 1] != '/')
3598 strlcat(con->uri, "/", sizeof(con->uri));
ef416fc2 3599
db1f069b
MS
3600 /*
3601 * Find the directory index file, trying every language...
3602 */
ef416fc2 3603
db1f069b 3604 do
ef416fc2 3605 {
db1f069b
MS
3606 if (status && language[0])
3607 {
3608 /*
3609 * Try a different language subset...
3610 */
3611
3612 if (language[3])
3613 language[0] = '\0'; /* Strip country code */
3614 else
3615 language[0] = '\0'; /* Strip language */
3616 }
3617
3618 /*
3619 * Look for the index file...
3620 */
3621
3622 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3623
3624 if ((ptr = strchr(filename, '?')) != NULL)
3625 *ptr = '\0';
3626
3627 ptr = filename + strlen(filename);
3628 plen = len - (ptr - filename);
3629
3630 strlcpy(ptr, "index.html", plen);
ef416fc2 3631 status = stat(filename, filestats);
db1f069b
MS
3632
3633#ifdef HAVE_JAVA
3634 if (status)
3635 {
3636 strlcpy(ptr, "index.class", plen);
3637 status = stat(filename, filestats);
3638 }
ef416fc2 3639#endif /* HAVE_JAVA */
3640
3641#ifdef HAVE_PERL
db1f069b
MS
3642 if (status)
3643 {
3644 strlcpy(ptr, "index.pl", plen);
3645 status = stat(filename, filestats);
3646 }
ef416fc2 3647#endif /* HAVE_PERL */
3648
3649#ifdef HAVE_PHP
db1f069b
MS
3650 if (status)
3651 {
3652 strlcpy(ptr, "index.php", plen);
3653 status = stat(filename, filestats);
3654 }
ef416fc2 3655#endif /* HAVE_PHP */
3656
3657#ifdef HAVE_PYTHON
db1f069b
MS
3658 if (status)
3659 {
3660 strlcpy(ptr, "index.pyc", plen);
3661 status = stat(filename, filestats);
3662 }
ef416fc2 3663
db1f069b
MS
3664 if (status)
3665 {
3666 strlcpy(ptr, "index.py", plen);
3667 status = stat(filename, filestats);
3668 }
ef416fc2 3669#endif /* HAVE_PYTHON */
db1f069b
MS
3670
3671 }
3672 while (status && language[0]);
ef416fc2 3673 }
3674
b9faaae1
MS
3675 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3676 "get_file(con=%p(%d), filestats=%p, filename=%p, len=%d) = "
3677 "%s", con, con->http.fd, filestats, filename, len,
3678 status ? "(null)" : filename);
ef416fc2 3679
ef416fc2 3680 if (status)
3681 return (NULL);
3682 else
3683 return (filename);
3684}
3685
3686
3687/*
3688 * 'install_conf_file()' - Install a configuration file.
3689 */
3690
3691static http_status_t /* O - Status */
3692install_conf_file(cupsd_client_t *con) /* I - Connection */
3693{
3694 cups_file_t *in, /* Input file */
3695 *out; /* Output file */
3696 char buffer[1024]; /* Copy buffer */
3697 int bytes; /* Number of bytes */
3698 char conffile[1024], /* Configuration filename */
3699 newfile[1024], /* New config filename */
3700 oldfile[1024]; /* Old config filename */
3701 struct stat confinfo; /* Config file info */
3702
3703
3704 /*
3705 * First construct the filenames...
3706 */
3707
3708 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3709 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3710 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3711
3712 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3713
3714 /*
3715 * Get the owner, group, and permissions of the configuration file.
3716 * If it doesn't exist, assign it to the User and Group in the
3717 * cupsd.conf file with mode 0640 permissions.
3718 */
3719
3720 if (stat(conffile, &confinfo))
3721 {
3722 confinfo.st_uid = User;
3723 confinfo.st_gid = Group;
3724 confinfo.st_mode = ConfigFilePerm;
3725 }
3726
3727 /*
3728 * Open the request file and new config file...
3729 */
3730
3731 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3732 {
3733 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3734 con->filename, strerror(errno));
3735 return (HTTP_SERVER_ERROR);
3736 }
3737
3738 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3739 {
3740 cupsFileClose(in);
3741 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3742 newfile, strerror(errno));
3743 return (HTTP_SERVER_ERROR);
3744 }
3745
3746 fchmod(cupsFileNumber(out), confinfo.st_mode);
3747 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3748
3749 /*
3750 * Copy from the request to the new config file...
3751 */
3752
3753 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3754 if (cupsFileWrite(out, buffer, bytes) < bytes)
3755 {
3756 cupsdLogMessage(CUPSD_LOG_ERROR,
3757 "Unable to copy to config file \"%s\" - %s",
3758 newfile, strerror(errno));
3759
3760 cupsFileClose(in);
3761 cupsFileClose(out);
3762 unlink(newfile);
3763
3764 return (HTTP_SERVER_ERROR);
3765 }
3766
3767 /*
3768 * Close the files...
3769 */
3770
3771 cupsFileClose(in);
3772 if (cupsFileClose(out))
3773 {
3774 cupsdLogMessage(CUPSD_LOG_ERROR,
3775 "Error file closing config file \"%s\" - %s",
3776 newfile, strerror(errno));
3777
3778 unlink(newfile);
3779
3780 return (HTTP_SERVER_ERROR);
3781 }
3782
3783 /*
3784 * Remove the request file...
3785 */
3786
3787 unlink(con->filename);
3788 cupsdClearString(&con->filename);
3789
3790 /*
3791 * Unlink the old backup, rename the current config file to the backup
3792 * filename, and rename the new config file to the config file name...
3793 */
3794
3795 if (unlink(oldfile))
3796 if (errno != ENOENT)
3797 {
3798 cupsdLogMessage(CUPSD_LOG_ERROR,
3799 "Unable to remove backup config file \"%s\" - %s",
3800 oldfile, strerror(errno));
3801
3802 unlink(newfile);
3803
3804 return (HTTP_SERVER_ERROR);
3805 }
3806
3807 if (rename(conffile, oldfile))
3808 if (errno != ENOENT)
3809 {
3810 cupsdLogMessage(CUPSD_LOG_ERROR,
3811 "Unable to rename old config file \"%s\" - %s",
3812 conffile, strerror(errno));
3813
3814 unlink(newfile);
3815
3816 return (HTTP_SERVER_ERROR);
3817 }
3818
3819 if (rename(newfile, conffile))
3820 {
3821 cupsdLogMessage(CUPSD_LOG_ERROR,
3822 "Unable to rename new config file \"%s\" - %s",
3823 newfile, strerror(errno));
3824
3825 rename(oldfile, conffile);
3826 unlink(newfile);
3827
3828 return (HTTP_SERVER_ERROR);
3829 }
3830
3831 /*
3832 * If the cupsd.conf file was updated, set the NeedReload flag...
3833 */
3834
3835 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3836 NeedReload = RELOAD_CUPSD;
3837 else
3838 NeedReload = RELOAD_ALL;
3839
3840 ReloadTime = time(NULL);
3841
3842 /*
3843 * Return that the file was created successfully...
3844 */
3845
3846 return (HTTP_CREATED);
3847}
3848
3849
e1d6a774 3850/*
3851 * 'is_cgi()' - Is the resource a CGI script/program?
3852 */
3853
3854static int /* O - 1 = CGI, 0 = file */
3855is_cgi(cupsd_client_t *con, /* I - Client connection */
3856 const char *filename, /* I - Real filename */
3857 struct stat *filestats, /* I - File information */
3858 mime_type_t *type) /* I - MIME type */
3859{
3860 const char *options; /* Options on URL */
3861
3862
e1d6a774 3863 /*
3864 * Get the options, if any...
3865 */
3866
3867 if ((options = strchr(con->uri, '?')) != NULL)
a0f6818e
MS
3868 {
3869 options ++;
3870 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3871 }
b86bc4cf 3872
e1d6a774 3873 /*
3874 * Check for known types...
3875 */
3876
3877 if (!type || strcasecmp(type->super, "application"))
3878 {
b9faaae1
MS
3879 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3880 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3881 "type=%s/%s) = 0", con, con->http.fd, filename, filestats,
3882 type ? type->super : "unknown",
3883 type ? type->type : "unknown");
e1d6a774 3884 return (0);
3885 }
3886
3887 if (!strcasecmp(type->type, "x-httpd-cgi") &&
3888 (filestats->st_mode & 0111))
3889 {
3890 /*
3891 * "application/x-httpd-cgi" is a CGI script.
3892 */
3893
3894 cupsdSetString(&con->command, filename);
3895
a0f6818e
MS
3896 if (options)
3897 cupsdSetStringf(&con->options, " %s", options);
e1d6a774 3898
3899 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
3900 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3901 "type=%s/%s) = 1", con, con->http.fd, filename, filestats,
3902 type ? type->super : "unknown",
3903 type ? type->type : "unknown");
e1d6a774 3904 return (1);
3905 }
3906#ifdef HAVE_JAVA
3907 else if (!strcasecmp(type->type, "x-httpd-java"))
3908 {
3909 /*
3910 * "application/x-httpd-java" is a Java servlet.
3911 */
3912
3913 cupsdSetString(&con->command, CUPS_JAVA);
3914
3915 if (options)
b94498cf 3916 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3917 else
b94498cf 3918 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3919
3920 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
3921 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3922 "type=%s/%s) = 1", con, con->http.fd, filename, filestats,
3923 type ? type->super : "unknown",
3924 type ? type->type : "unknown");
e1d6a774 3925 return (1);
3926 }
3927#endif /* HAVE_JAVA */
3928#ifdef HAVE_PERL
3929 else if (!strcasecmp(type->type, "x-httpd-perl"))
3930 {
3931 /*
3932 * "application/x-httpd-perl" is a Perl page.
3933 */
3934
3935 cupsdSetString(&con->command, CUPS_PERL);
3936
3937 if (options)
b94498cf 3938 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3939 else
b94498cf 3940 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3941
3942 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
3943 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3944 "type=%s/%s) = 1", con, con->http.fd, filename, filestats,
3945 type ? type->super : "unknown",
3946 type ? type->type : "unknown");
e1d6a774 3947 return (1);
3948 }
3949#endif /* HAVE_PERL */
3950#ifdef HAVE_PHP
3951 else if (!strcasecmp(type->type, "x-httpd-php"))
3952 {
3953 /*
3954 * "application/x-httpd-php" is a PHP page.
3955 */
3956
3957 cupsdSetString(&con->command, CUPS_PHP);
3958
3959 if (options)
b94498cf 3960 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3961 else
b94498cf 3962 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3963
3964 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
3965 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3966 "type=%s/%s) = 1", con, con->http.fd, filename, filestats,
3967 type ? type->super : "unknown",
3968 type ? type->type : "unknown");
e1d6a774 3969 return (1);
3970 }
3971#endif /* HAVE_PHP */
3972#ifdef HAVE_PYTHON
3973 else if (!strcasecmp(type->type, "x-httpd-python"))
3974 {
3975 /*
3976 * "application/x-httpd-python" is a Python page.
3977 */
3978
3979 cupsdSetString(&con->command, CUPS_PYTHON);
3980
3981 if (options)
b94498cf 3982 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3983 else
b94498cf 3984 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3985
3986 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
3987 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3988 "type=%s/%s) = 1", con, con->http.fd, filename, filestats,
3989 type ? type->super : "unknown",
3990 type ? type->type : "unknown");
e1d6a774 3991 return (1);
3992 }
3993#endif /* HAVE_PYTHON */
3994
b9faaae1
MS
3995 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3996 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3997 "type=%s/%s) = 0", con, con->http.fd, filename, filestats,
3998 type ? type->super : "unknown",
3999 type ? type->type : "unknown");
e1d6a774 4000 return (0);
4001}
4002
4003
ef416fc2 4004/*
4005 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
4006 */
4007
4008static int /* O - 0 if relative, 1 if absolute */
4009is_path_absolute(const char *path) /* I - Input path */
4010{
4011 /*
4012 * Check for a leading slash...
4013 */
4014
4015 if (path[0] != '/')
4016 return (0);
4017
4018 /*
4019 * Check for "/.." in the path...
4020 */
4021
4022 while ((path = strstr(path, "/..")) != NULL)
4023 {
4024 if (!path[3] || path[3] == '/')
4025 return (0);
4026
4027 path ++;
4028 }
4029
4030 /*
4031 * If we haven't found any relative paths, return 1 indicating an
4032 * absolute path...
4033 */
4034
4035 return (1);
4036}
4037
4038
8ca02f3c 4039#ifdef HAVE_SSL
4744bd90 4040/*
4041 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
4042 */
4043
8ca02f3c 4044static int /* O - 1 on success, 0 on failure */
b86bc4cf 4045make_certificate(cupsd_client_t *con) /* I - Client connection */
4744bd90 4046{
8ca02f3c 4047#if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
d09495fa 4048 int pid, /* Process ID of command */
4049 status; /* Status of command */
4050 char command[1024], /* Command */
f7deaa1a 4051 *argv[12], /* Command-line arguments */
d09495fa 4052 *envp[MAX_ENV + 1], /* Environment variables */
d09495fa 4053 infofile[1024], /* Type-in information for cert */
4054 seedfile[1024]; /* Random number seed file */
4055 int envc, /* Number of environment variables */
4056 bytes; /* Bytes written */
4057 cups_file_t *fp; /* Seed/info file */
4058 int infofd; /* Info file descriptor */
8ca02f3c 4059
4060
4061 /*
d09495fa 4062 * Run the "openssl" command to seed the random number generator and
4063 * generate a self-signed certificate that is good for 10 years:
4064 *
4065 * openssl rand -rand seedfile 1
8ca02f3c 4066 *
4067 * openssl req -new -x509 -keyout ServerKey \
4068 * -out ServerCertificate -days 3650 -nodes
d09495fa 4069 *
4070 * The seeding step is crucial in ensuring that the openssl command
4071 * does not block on systems without sufficient entropy...
8ca02f3c 4072 */
4073
4074 if (!cupsFileFind("openssl", getenv("PATH"), 1, command, sizeof(command)))
4075 {
4076 cupsdLogMessage(CUPSD_LOG_ERROR,
4077 "No SSL certificate and openssl command not found!");
4078 return (0);
4079 }
4080
d09495fa 4081 if (access("/dev/urandom", 0))
4082 {
4083 /*
4084 * If the system doesn't provide /dev/urandom, then any random source
4085 * will probably be blocking-style, so generate some random data to
4086 * use as a seed for the certificate. Note that we have already
4087 * seeded the random number generator in cupsdInitCerts()...
4088 */
4089
4090 cupsdLogMessage(CUPSD_LOG_INFO,
4091 "Seeding the random number generator...");
4092
d09495fa 4093 /*
4094 * Write the seed file...
4095 */
4096
4097 if ((fp = cupsTempFile2(seedfile, sizeof(seedfile))) == NULL)
4098 {
4099 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create seed file %s - %s",
4100 seedfile, strerror(errno));
4101 return (0);
4102 }
4103
4104 for (bytes = 0; bytes < 262144; bytes ++)
4105 cupsFilePutChar(fp, random());
4106
4107 cupsFileClose(fp);
4108
4109 /*
4110 * Run the openssl command to seed its random number generator...
4111 */
4112
4113 argv[0] = "openssl";
4114 argv[1] = "rand";
4115 argv[2] = "-rand";
4116 argv[3] = seedfile;
4117 argv[4] = "1";
4118 argv[5] = NULL;
4119
4120 envc = cupsdLoadEnv(envp, MAX_ENV);
acb056cb 4121 envp[envc] = NULL;
d09495fa 4122
f11a948a 4123 if (!cupsdStartProcess(command, argv, envp, -1, -1, -1, -1, -1, 1, NULL,
38e73f87 4124 NULL, &pid))
d09495fa 4125 {
4126 unlink(seedfile);
4127 return (0);
4128 }
4129
4130 while (waitpid(pid, &status, 0) < 0)
4131 if (errno != EINTR)
4132 {
4133 status = 1;
4134 break;
4135 }
4136
b9faaae1 4137 cupsdFinishProcess(pid, command, sizeof(command), NULL);
d09495fa 4138
4139 /*
4140 * Remove the seed file, as it is no longer needed...
4141 */
4142
4143 unlink(seedfile);
4144
4145 if (status)
4146 {
4147 if (WIFEXITED(status))
4148 cupsdLogMessage(CUPSD_LOG_ERROR,
4149 "Unable to seed random number generator - "
4150 "the openssl command stopped with status %d!",
4151 WEXITSTATUS(status));
4152 else
4153 cupsdLogMessage(CUPSD_LOG_ERROR,
4154 "Unable to seed random number generator - "
4155 "the openssl command crashed on signal %d!",
4156 WTERMSIG(status));
4157
4158 return (0);
4159 }
4160 }
4161
4162 /*
4163 * Create a file with the certificate information fields...
4164 *
4165 * Note: This assumes that the default questions are asked by the openssl
4166 * command...
4167 */
4168
4169 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4170 {
4171 cupsdLogMessage(CUPSD_LOG_ERROR,
4172 "Unable to create certificate information file %s - %s",
4173 infofile, strerror(errno));
4174 return (0);
4175 }
4176
4177 cupsFilePrintf(fp, ".\n.\n.\n%s\n.\n%s\n%s\n",
4178 ServerName, ServerName, ServerAdmin);
4179 cupsFileClose(fp);
4180
8ca02f3c 4181 cupsdLogMessage(CUPSD_LOG_INFO,
4182 "Generating SSL server key and certificate...");
4183
4184 argv[0] = "openssl";
4185 argv[1] = "req";
4186 argv[2] = "-new";
4187 argv[3] = "-x509";
4188 argv[4] = "-keyout";
4189 argv[5] = ServerKey;
4190 argv[6] = "-out";
4191 argv[7] = ServerCertificate;
4192 argv[8] = "-days";
4193 argv[9] = "3650";
4194 argv[10] = "-nodes";
4195 argv[11] = NULL;
4196
4197 cupsdLoadEnv(envp, MAX_ENV);
4198
d09495fa 4199 infofd = open(infofile, O_RDONLY);
4200
a4924f6c 4201 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
38e73f87 4202 NULL, &pid))
d09495fa 4203 {
4204 close(infofd);
4205 unlink(infofile);
8ca02f3c 4206 return (0);
d09495fa 4207 }
4208
4209 close(infofd);
4210 unlink(infofile);
8ca02f3c 4211
4212 while (waitpid(pid, &status, 0) < 0)
4213 if (errno != EINTR)
4214 {
4215 status = 1;
4216 break;
4217 }
4218
b9faaae1 4219 cupsdFinishProcess(pid, command, sizeof(command), NULL);
8ca02f3c 4220
4221 if (status)
4222 {
4223 if (WIFEXITED(status))
4224 cupsdLogMessage(CUPSD_LOG_ERROR,
4225 "Unable to create SSL server key and certificate - "
4226 "the openssl command stopped with status %d!",
4227 WEXITSTATUS(status));
4228 else
4229 cupsdLogMessage(CUPSD_LOG_ERROR,
4230 "Unable to create SSL server key and certificate - "
4231 "the openssl command crashed on signal %d!",
4232 WTERMSIG(status));
4233 }
4234 else
4235 {
4236 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4237 ServerKey);
4238 cupsdLogMessage(CUPSD_LOG_INFO,
4239 "Created SSL server certificate file \"%s\"...",
4240 ServerCertificate);
4241 }
4242
4243 return (!status);
4244
4245#elif defined(HAVE_GNUTLS)
4744bd90 4246 gnutls_x509_crt crt; /* Self-signed certificate */
4247 gnutls_x509_privkey key; /* Encryption key */
4248 cups_lang_t *language; /* Default language info */
4249 cups_file_t *fp; /* Key/cert file */
4250 unsigned char buffer[8192]; /* Buffer for x509 data */
4251 size_t bytes; /* Number of bytes of data */
4252 unsigned char serial[4]; /* Serial number buffer */
4253 time_t curtime; /* Current time */
4254 int result; /* Result of GNU TLS calls */
4255
4256
4257 /*
4258 * Create the encryption key...
4259 */
4260
8ca02f3c 4261 cupsdLogMessage(CUPSD_LOG_INFO, "Generating SSL server key...");
4744bd90 4262
4263 gnutls_x509_privkey_init(&key);
4264 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
4265
4266 /*
4267 * Save it...
4268 */
4269
4270 bytes = sizeof(buffer);
4271
4272 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM,
4273 buffer, &bytes)) < 0)
4274 {
8ca02f3c 4275 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to export SSL server key - %s",
4744bd90 4276 gnutls_strerror(result));
4277 gnutls_x509_privkey_deinit(key);
8ca02f3c 4278 return (0);
4744bd90 4279 }
4280 else if ((fp = cupsFileOpen(ServerKey, "w")) != NULL)
4281 {
4282 cupsFileWrite(fp, (char *)buffer, bytes);
4283 cupsFileClose(fp);
4284
8ca02f3c 4285 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4744bd90 4286 ServerKey);
4287 }
4288 else
4289 {
4290 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4291 "Unable to create SSL server key file \"%s\" - %s",
4744bd90 4292 ServerKey, strerror(errno));
4293 gnutls_x509_privkey_deinit(key);
8ca02f3c 4294 return (0);
4744bd90 4295 }
4296
4297 /*
4298 * Create the self-signed certificate...
4299 */
4300
8ca02f3c 4301 cupsdLogMessage(CUPSD_LOG_INFO, "Generating self-signed SSL certificate...");
4744bd90 4302
4303 language = cupsLangDefault();
4304 curtime = time(NULL);
4305 serial[0] = curtime >> 24;
4306 serial[1] = curtime >> 16;
4307 serial[2] = curtime >> 8;
4308 serial[3] = curtime;
4309
4310 gnutls_x509_crt_init(&crt);
4311 if (strlen(language->language) == 5)
4312 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4313 language->language + 3, 2);
4314 else
4315 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4316 "US", 2);
4317 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
4318 ServerName, strlen(ServerName));
4319 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
4320 ServerName, strlen(ServerName));
4321 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
4322 0, "Unknown", 7);
4323 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
4324 "Unknown", 7);
4325 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
4326 "Unknown", 7);
4327 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
4328 ServerAdmin, strlen(ServerAdmin));
4329 gnutls_x509_crt_set_key(crt, key);
4330 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
4331 gnutls_x509_crt_set_activation_time(crt, curtime);
4332 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
4333 gnutls_x509_crt_set_ca_status(crt, 0);
4334 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME,
4335 ServerName);
4336 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
4337 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
4338 gnutls_x509_crt_set_version(crt, 3);
4339
4340 bytes = sizeof(buffer);
4341 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
4342 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
4343
4344 gnutls_x509_crt_sign(crt, crt, key);
4345
4346 /*
4347 * Save it...
4348 */
4349
4350 bytes = sizeof(buffer);
4351 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM,
4352 buffer, &bytes)) < 0)
4353 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4354 "Unable to export SSL server certificate - %s",
4744bd90 4355 gnutls_strerror(result));
4356 else if ((fp = cupsFileOpen(ServerCertificate, "w")) != NULL)
4357 {
4358 cupsFileWrite(fp, (char *)buffer, bytes);
4359 cupsFileClose(fp);
4360
4361 cupsdLogMessage(CUPSD_LOG_INFO,
8ca02f3c 4362 "Created SSL server certificate file \"%s\"...",
4744bd90 4363 ServerCertificate);
4364 }
4365 else
4366 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4367 "Unable to create SSL server certificate file \"%s\" - %s",
4744bd90 4368 ServerCertificate, strerror(errno));
4369
4370 /*
4371 * Cleanup...
4372 */
4373
4374 gnutls_x509_crt_deinit(crt);
4375 gnutls_x509_privkey_deinit(key);
8ca02f3c 4376
4377 return (1);
4378
4379#elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
b86bc4cf 4380 int pid, /* Process ID of command */
4381 status; /* Status of command */
4382 char command[1024], /* Command */
4383 *argv[4], /* Command-line arguments */
4384 *envp[MAX_ENV + 1], /* Environment variables */
4385 keychain[1024], /* Keychain argument */
4386 infofile[1024]; /* Type-in information for cert */
4387 cups_file_t *fp; /* Seed/info file */
4388 int infofd; /* Info file descriptor */
8ca02f3c 4389
4390
4391 /*
b86bc4cf 4392 * Run the "certtool" command to generate a self-signed certificate...
8ca02f3c 4393 */
4394
4395 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
4396 {
4397 cupsdLogMessage(CUPSD_LOG_ERROR,
4398 "No SSL certificate and certtool command not found!");
4399 return (0);
4400 }
4401
b86bc4cf 4402 /*
4403 * Create a file with the certificate information fields...
4404 *
4405 * Note: This assumes that the default questions are asked by the certtool
4406 * command...
4407 */
4408
4409 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4410 {
4411 cupsdLogMessage(CUPSD_LOG_ERROR,
4412 "Unable to create certificate information file %s - %s",
4413 infofile, strerror(errno));
4414 return (0);
4415 }
4416
4417 cupsFilePrintf(fp, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4418 con->servername, con->servername, ServerAdmin);
4419 cupsFileClose(fp);
4420
8ca02f3c 4421 cupsdLogMessage(CUPSD_LOG_INFO,
4422 "Generating SSL server key and certificate...");
4423
4424 snprintf(keychain, sizeof(keychain), "k=%s", ServerCertificate);
4425
4426 argv[0] = "certtool";
4427 argv[1] = "c";
b86bc4cf 4428 argv[2] = keychain;
4429 argv[3] = NULL;
8ca02f3c 4430
4431 cupsdLoadEnv(envp, MAX_ENV);
4432
b86bc4cf 4433 infofd = open(infofile, O_RDONLY);
4434
a4924f6c 4435 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
38e73f87 4436 NULL, &pid))
b86bc4cf 4437 {
4438 close(infofd);
4439 unlink(infofile);
8ca02f3c 4440 return (0);
b86bc4cf 4441 }
4442
4443 close(infofd);
4444 unlink(infofile);
8ca02f3c 4445
4446 while (waitpid(pid, &status, 0) < 0)
4447 if (errno != EINTR)
4448 {
4449 status = 1;
4450 break;
4451 }
4452
b9faaae1 4453 cupsdFinishProcess(pid, command, sizeof(command), NULL);
8ca02f3c 4454
4455 if (status)
4456 {
4457 if (WIFEXITED(status))
4458 cupsdLogMessage(CUPSD_LOG_ERROR,
4459 "Unable to create SSL server key and certificate - "
4460 "the certtool command stopped with status %d!",
4461 WEXITSTATUS(status));
4462 else
4463 cupsdLogMessage(CUPSD_LOG_ERROR,
4464 "Unable to create SSL server key and certificate - "
4465 "the certtool command crashed on signal %d!",
4466 WTERMSIG(status));
4467 }
4468 else
4469 {
4470 cupsdLogMessage(CUPSD_LOG_INFO,
4471 "Created SSL server certificate file \"%s\"...",
4472 ServerCertificate);
4473 }
4474
4475 return (!status);
4476
4477#else
4478 return (0);
4479#endif /* HAVE_LIBSSL && HAVE_WAITPID */
4744bd90 4480}
8ca02f3c 4481#endif /* HAVE_SSL */
4744bd90 4482
4483
ef416fc2 4484/*
4485 * 'pipe_command()' - Pipe the output of a command to the remote client.
4486 */
4487
4488static int /* O - Process ID */
4489pipe_command(cupsd_client_t *con, /* I - Client connection */
4490 int infile, /* I - Standard input for command */
4491 int *outfile, /* O - Standard output for command */
4492 char *command, /* I - Command to run */
4493 char *options, /* I - Options for command */
4494 int root) /* I - Run as root? */
4495{
4496 int i; /* Looping var */
4497 int pid; /* Process ID */
b423cd4c 4498 char *commptr, /* Command string pointer */
4499 commch; /* Command string character */
ef416fc2 4500 char *uriptr; /* URI string pointer */
4501 int fds[2]; /* Pipe FDs */
4502 int argc; /* Number of arguments */
4503 int envc; /* Number of environment variables */
4504 char argbuf[10240], /* Argument buffer */
4505 *argv[100], /* Argument strings */
b94498cf 4506 *envp[MAX_ENV + 20]; /* Environment variables */
5bd77a73 4507 char auth_type[256], /* CUPSD_AUTH_TYPE environment variable */
b94498cf 4508 content_length[1024], /* CONTENT_LENGTH environment variable */
ef416fc2 4509 content_type[1024], /* CONTENT_TYPE environment variable */
4510 http_cookie[32768], /* HTTP_COOKIE environment variable */
f7deaa1a 4511 http_referer[1024], /* HTTP_REFERER environment variable */
ef416fc2 4512 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
4513 lang[1024], /* LANG environment variable */
b423cd4c 4514 path_info[1024], /* PATH_INFO environment variable */
ef416fc2 4515 remote_addr[1024], /* REMOTE_ADDR environment variable */
4516 remote_host[1024], /* REMOTE_HOST environment variable */
4517 remote_user[1024], /* REMOTE_USER environment variable */
b94498cf 4518 script_filename[1024], /* SCRIPT_FILENAME environment variable */
ef416fc2 4519 script_name[1024], /* SCRIPT_NAME environment variable */
4520 server_name[1024], /* SERVER_NAME environment variable */
4521 server_port[1024]; /* SERVER_PORT environment variable */
7dfedb92 4522 ipp_attribute_t *attr; /* attributes-natural-language attribute */
e07d4801 4523 void *ccache = NULL; /* Kerberos credentials */
ef416fc2 4524
4525
4526 /*
4527 * Parse a copy of the options string, which is of the form:
4528 *
b423cd4c 4529 * argument+argument+argument
4530 * ?argument+argument+argument
4531 * param=value&param=value
4532 * ?param=value&param=value
4533 * /name?argument+argument+argument
4534 * /name?param=value&param=value
ef416fc2 4535 *
4536 * If the string contains an "=" character after the initial name,
4537 * then we treat it as a HTTP GET form request and make a copy of
4538 * the remaining string for the environment variable.
4539 *
4540 * The string is always parsed out as command-line arguments, to
4541 * be consistent with Apache...
4542 */
4543
4544 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b9faaae1
MS
4545 "pipe_command(con=%p(%d), infile=%d, outfile=%p, "
4546 "command=\"%s\", options=\"%s\", root=%d)",
4547 con, con->http.fd, infile, outfile, command,
4548 options ? options : "(null)", root);
ef416fc2 4549
b86bc4cf 4550 argv[0] = command;
ef416fc2 4551
b423cd4c 4552 if (options)
4553 strlcpy(argbuf, options, sizeof(argbuf));
4554 else
4555 argbuf[0] = '\0';
4556
4557 if (argbuf[0] == '/')
ef416fc2 4558 {
4559 /*
b423cd4c 4560 * Found some trailing path information, set PATH_INFO...
ef416fc2 4561 */
4562
b423cd4c 4563 if ((commptr = strchr(argbuf, '?')) == NULL)
4564 commptr = argbuf + strlen(argbuf);
ef416fc2 4565
b423cd4c 4566 commch = *commptr;
4567 *commptr = '\0';
4568 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
4569 *commptr = commch;
4570 }
4571 else
4572 {
4573 commptr = argbuf;
4574 path_info[0] = '\0';
b94498cf 4575
4576 if (*commptr == ' ')
4577 commptr ++;
b423cd4c 4578 }
ef416fc2 4579
b86bc4cf 4580 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
b423cd4c 4581 {
4582 commptr ++;
b86bc4cf 4583 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
b423cd4c 4584 }
ef416fc2 4585
b423cd4c 4586 argc = 1;
ef416fc2 4587
b423cd4c 4588 if (*commptr)
4589 {
4590 argv[argc ++] = commptr;
ef416fc2 4591
b423cd4c 4592 for (; *commptr && argc < 99; commptr ++)
4593 {
ef416fc2 4594 /*
b423cd4c 4595 * Break arguments whenever we see a + or space...
ef416fc2 4596 */
4597
b423cd4c 4598 if (*commptr == ' ' || *commptr == '+')
4599 {
4600 while (*commptr == ' ' || *commptr == '+')
4601 *commptr++ = '\0';
ef416fc2 4602
b423cd4c 4603 /*
4604 * If we don't have a blank string, save it as another argument...
4605 */
ef416fc2 4606
b423cd4c 4607 if (*commptr)
4608 {
4609 argv[argc] = commptr;
4610 argc ++;
4611 }
4612 else
4613 break;
4614 }
4615 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
4616 isxdigit(commptr[2] & 255))
4617 {
4618 /*
4619 * Convert the %xx notation to the individual character.
4620 */
ef416fc2 4621
b423cd4c 4622 if (commptr[1] >= '0' && commptr[1] <= '9')
4623 *commptr = (commptr[1] - '0') << 4;
4624 else
4625 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
ef416fc2 4626
b423cd4c 4627 if (commptr[2] >= '0' && commptr[2] <= '9')
4628 *commptr |= commptr[2] - '0';
4629 else
4630 *commptr |= tolower(commptr[2]) - 'a' + 10;
ef416fc2 4631
b423cd4c 4632 _cups_strcpy(commptr + 1, commptr + 3);
ef416fc2 4633
b423cd4c 4634 /*
4635 * Check for a %00 and break if that is the case...
4636 */
ef416fc2 4637
b423cd4c 4638 if (!*commptr)
4639 break;
4640 }
ef416fc2 4641 }
4642 }
4643
4644 argv[argc] = NULL;
4645
ef416fc2 4646 /*
4647 * Setup the environment variables as needed...
4648 */
4649
b94498cf 4650 if (con->username[0])
4651 {
5bd77a73 4652 snprintf(auth_type, sizeof(auth_type), "CUPSD_AUTH_TYPE=%s",
b94498cf 4653 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
4654
4655 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
4656 *uriptr = '\0';
4657 }
4658 else
4659 auth_type[0] = '\0';
4660
7dfedb92
MS
4661 if (con->request &&
4662 (attr = ippFindAttribute(con->request, "attributes-natural-language",
4663 IPP_TAG_LANGUAGE)) != NULL)
4664 {
4665 switch (strlen(attr->values[0].string.text))
4666 {
4667 default :
4668 /*
4669 * This is an unknown or badly formatted language code; use
4670 * the POSIX locale...
4671 */
4672
4673 strcpy(lang, "LANG=C");
4674 break;
4675
4676 case 2 :
4677 /*
4678 * Just the language code (ll)...
4679 */
4680
4681 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
4682 attr->values[0].string.text);
4683 break;
4684
4685 case 5 :
4686 /*
4687 * Language and country code (ll-cc)...
4688 */
4689
4690 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
4691 attr->values[0].string.text[0],
4692 attr->values[0].string.text[1],
4693 toupper(attr->values[0].string.text[3] & 255),
4694 toupper(attr->values[0].string.text[4] & 255));
4695 break;
4696 }
4697 }
4698 else if (con->language)
4699 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
ef416fc2 4700 else
4701 strcpy(lang, "LANG=C");
4702
4703 strcpy(remote_addr, "REMOTE_ADDR=");
4704 httpAddrString(con->http.hostaddr, remote_addr + 12,
4705 sizeof(remote_addr) - 12);
4706
4707 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
4708 con->http.hostname);
4709
4710 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
4711 if ((uriptr = strchr(script_name, '?')) != NULL)
4712 *uriptr = '\0';
4713
b94498cf 4714 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
4715 DocumentRoot, script_name + 12);
4716
ef416fc2 4717 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
4718
4719 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
4720 con->servername);
4721
4722 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
4723
b94498cf 4724 if (auth_type[0])
4725 envp[envc ++] = auth_type;
4726
ef416fc2 4727 envp[envc ++] = lang;
4728 envp[envc ++] = "REDIRECT_STATUS=1";
b94498cf 4729 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
ef416fc2 4730 envp[envc ++] = server_name;
4731 envp[envc ++] = server_port;
4732 envp[envc ++] = remote_addr;
4733 envp[envc ++] = remote_host;
4734 envp[envc ++] = script_name;
b94498cf 4735 envp[envc ++] = script_filename;
ef416fc2 4736
b423cd4c 4737 if (path_info[0])
4738 envp[envc ++] = path_info;
4739
ef416fc2 4740 if (con->username[0])
4741 {
4742 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
4743
4744 envp[envc ++] = remote_user;
5bd77a73
MS
4745
4746 /*
4747 * Save Kerberos credentials, if any...
4748 */
4749
4750#ifdef HAVE_GSSAPI
e07d4801
MS
4751 if (con->gss_creds)
4752 ccache = cupsdCopyKrb5Creds(con);
5bd77a73 4753#endif /* HAVE_GSSAPI */
ef416fc2 4754 }
4755
4756 if (con->http.version == HTTP_1_1)
4757 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
4758 else if (con->http.version == HTTP_1_0)
4759 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
4760 else
4761 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
4762
4763 if (con->http.cookie)
4764 {
4765 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
4766 con->http.cookie);
4767 envp[envc ++] = http_cookie;
4768 }
4769
4770 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
4771 {
4772 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
4773 con->http.fields[HTTP_FIELD_USER_AGENT]);
4774 envp[envc ++] = http_user_agent;
4775 }
4776
f7deaa1a 4777 if (con->http.fields[HTTP_FIELD_REFERER][0])
4778 {
4779 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
4780 con->http.fields[HTTP_FIELD_REFERER]);
4781 envp[envc ++] = http_referer;
4782 }
4783
ef416fc2 4784 if (con->operation == HTTP_GET)
4785 {
ef416fc2 4786 envp[envc ++] = "REQUEST_METHOD=GET";
4787
b86bc4cf 4788 if (con->query_string)
ef416fc2 4789 {
4790 /*
4791 * Add GET form variables after ?...
4792 */
4793
b86bc4cf 4794 envp[envc ++] = con->query_string;
ef416fc2 4795 }
3dfe78b3
MS
4796 else
4797 envp[envc ++] = "QUERY_STRING=";
ef416fc2 4798 }
4799 else
4800 {
e1d6a774 4801 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
4802 CUPS_LLCAST con->bytes);
ef416fc2 4803 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
4804 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
4805
4806 envp[envc ++] = "REQUEST_METHOD=POST";
4807 envp[envc ++] = content_length;
4808 envp[envc ++] = content_type;
4809 }
4810
4811 /*
4812 * Tell the CGI if we are using encryption...
4813 */
4814
a74454a7 4815 if (con->http.tls)
ef416fc2 4816 envp[envc ++] = "HTTPS=ON";
4817
4818 /*
4819 * Terminate the environment array...
4820 */
4821
4822 envp[envc] = NULL;
4823
38e73f87 4824 if (LogLevel >= CUPSD_LOG_DEBUG)
ef416fc2 4825 {
4826 for (i = 0; i < argc; i ++)
38e73f87
MS
4827 cupsdLogMessage(CUPSD_LOG_DEBUG,
4828 "[CGI] argv[%d] = \"%s\"", i, argv[i]);
ef416fc2 4829 for (i = 0; i < envc; i ++)
38e73f87
MS
4830 cupsdLogMessage(CUPSD_LOG_DEBUG,
4831 "[CGI] envp[%d] = \"%s\"", i, envp[i]);
ef416fc2 4832 }
4833
4834 /*
4835 * Create a pipe for the output...
4836 */
4837
4838 if (cupsdOpenPipe(fds))
4839 {
38e73f87 4840 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
ef416fc2 4841 argv[0], strerror(errno));
4842 return (0);
4843 }
4844
4845 /*
4846 * Then execute the command...
4847 */
4848
4849 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
38e73f87 4850 -1, -1, root, DefaultProfile, NULL, &pid) < 0)
ef416fc2 4851 {
4852 /*
4853 * Error - can't fork!
4854 */
4855
38e73f87 4856 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
ef416fc2 4857 strerror(errno));
4858
4859 cupsdClosePipe(fds);
4860 pid = 0;
4861 }
4862 else
4863 {
4864 /*
4865 * Fork successful - return the PID...
4866 */
4867
4868 if (con->username[0])
5bd77a73 4869 cupsdAddCert(pid, con->username, ccache);
ef416fc2 4870
38e73f87 4871 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
ef416fc2 4872
4873 *outfile = fds[0];
4874 close(fds[1]);
4875 }
4876
ef416fc2 4877 return (pid);
4878}
4879
4880
e07d4801
MS
4881/*
4882 * 'valid_host()' - Is the Host: field valid?
4883 */
4884
4885static int /* O - 1 if valid, 0 if not */
4886valid_host(cupsd_client_t *con) /* I - Client connection */
4887{
4888 cupsd_alias_t *a; /* Current alias */
4889 cupsd_netif_t *netif; /* Current network interface */
4890 const char *host, /* Host field */
4891 *end; /* End character */
4892
4893
4894 host = con->http.fields[HTTP_FIELD_HOST];
4895
4896 if (httpAddrLocalhost(con->http.hostaddr))
4897 {
4898 /*
4899 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4900 * addresses when accessing CUPS via the loopback interface...
4901 */
4902
4903 return (!strcasecmp(host, "localhost") ||
4904 !strncasecmp(host, "localhost:", 10) ||
4905 !strcasecmp(host, "localhost.") ||
4906 !strncasecmp(host, "localhost.:", 11) ||
4907#ifdef __linux
4908 !strcasecmp(host, "localhost.localdomain") ||
4909 !strncasecmp(host, "localhost.localdomain:", 22) ||
4910#endif /* __linux */
4911 !strcmp(host, "127.0.0.1") ||
4912 !strncmp(host, "127.0.0.1:", 10) ||
4913 !strcmp(host, "[::1]") ||
4914 !strncmp(host, "[::1]:", 6));
4915 }
4916
4917#ifdef HAVE_DNSSD
4918 /*
4919 * Check if the hostname is something.local (Bonjour); if so, allow it.
4920 */
4921
4922 if ((end = strrchr(host, '.')) != NULL &&
4923 (!strcasecmp(end, ".local") || !strncasecmp(end, ".local:", 7) ||
4924 !strcasecmp(end, ".local.") || !strncasecmp(end, ".local.:", 8)))
4925 return (1);
4926#endif /* HAVE_DNSSD */
4927
4928 /*
4929 * Check if the hostname is an IP address...
4930 */
4931
4932 if (isdigit(*host & 255) || *host == '[')
4933 {
4934 /*
4935 * Possible IPv4/IPv6 address...
4936 */
4937
4938 char temp[1024], /* Temporary string */
4939 *ptr; /* Pointer into temporary string */
4940 http_addrlist_t *addrlist; /* List of addresses */
4941
4942
4943 strlcpy(temp, host, sizeof(temp));
4944 if ((ptr = strrchr(temp, ':')) != NULL && !strchr(ptr, ']'))
4945 *ptr = '\0'; /* Strip :port from host value */
4946
4947 if ((addrlist = httpAddrGetList(temp, AF_UNSPEC, NULL)) != NULL)
4948 {
4949 /*
4950 * Good IPv4/IPv6 address...
4951 */
4952
4953 httpAddrFreeList(addrlist);
4954 return (1);
4955 }
4956 }
4957
4958 /*
4959 * Check for (alias) name matches...
4960 */
4961
4962 for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
4963 a;
4964 a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
4965 {
4966 /*
4967 * "ServerAlias *" allows all host values through...
4968 */
4969
4970 if (!strcmp(a->name, "*"))
4971 return (1);
4972
4973 if (!strncasecmp(host, a->name, a->namelen))
4974 {
4975 /*
4976 * Prefix matches; check the character at the end - it must be ":", ".",
4977 * ".:", or nul...
4978 */
4979
4980 end = host + a->namelen;
4981
4982 if (!*end || *end == ':' || (*end == '.' && (!end[1] || end[1] == ':')))
4983 return (1);
4984 }
4985 }
4986
4987#ifdef HAVE_DNSSD
4988 for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
4989 a;
4990 a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
4991 {
4992 /*
4993 * "ServerAlias *" allows all host values through...
4994 */
4995
4996 if (!strcmp(a->name, "*"))
4997 return (1);
4998
4999 if (!strncasecmp(host, a->name, a->namelen))
5000 {
5001 /*
5002 * Prefix matches; check the character at the end - it must be ":", ".",
5003 * ".:", or nul...
5004 */
5005
5006 end = host + a->namelen;
5007
5008 if (!*end || *end == ':' || (*end == '.' && (!end[1] || end[1] == ':')))
5009 return (1);
5010 }
5011 }
5012#endif /* HAVE_DNSSD */
5013
5014 /*
5015 * Check for interface hostname matches...
5016 */
5017
5018 for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
5019 netif;
5020 netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
5021 {
5022 if (!strncasecmp(host, netif->hostname, netif->hostlen))
5023 {
5024 /*
5025 * Prefix matches; check the character at the end - it must be ":", ".",
5026 * ".:", or nul...
5027 */
5028
5029 end = host + netif->hostlen;
5030
5031 if (!*end || *end == ':' || (*end == '.' && (!end[1] || end[1] == ':')))
5032 return (1);
5033 }
5034 }
5035
5036 return (0);
5037}
5038
5039
ef416fc2 5040/*
a74454a7 5041 * 'write_file()' - Send a file via HTTP.
e1d6a774 5042 */
5043
5044static int /* O - 0 on failure, 1 on success */
a74454a7 5045write_file(cupsd_client_t *con, /* I - Client connection */
5046 http_status_t code, /* I - HTTP status */
5047 char *filename, /* I - Filename */
5048 char *type, /* I - File type */
5049 struct stat *filestats) /* O - File information */
e1d6a774 5050{
5051 con->file = open(filename, O_RDONLY);
5052
b9faaae1
MS
5053 cupsdLogMessage(CUPSD_LOG_DEBUG2,
5054 "write_file(con=%p(%d), code=%d, filename=\"%s\" (%d), "
5055 "type=\"%s\", filestats=%p)", con, con->http.fd,
5056 code, filename, con->file, type ? type : "(null)", filestats);
e1d6a774 5057
5058 if (con->file < 0)
5059 return (0);
5060
5061 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
5062
5063 con->pipe_pid = 0;
5064
5bd77a73 5065 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
e1d6a774 5066 return (0);
5067
5068 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
5069 httpGetDateString(filestats->st_mtime)) < 0)
5070 return (0);
5071 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
5072 CUPS_LLCAST filestats->st_size) < 0)
5073 return (0);
5074 if (httpPrintf(HTTP(con), "\r\n") < 0)
5075 return (0);
5076
07725fee 5077 if (cupsdFlushHeader(con) < 0)
5078 return (0);
d09495fa 5079
e1d6a774 5080 con->http.data_encoding = HTTP_ENCODE_LENGTH;
5081 con->http.data_remaining = filestats->st_size;
5082
5083 if (con->http.data_remaining <= INT_MAX)
5084 con->http._data_remaining = con->http.data_remaining;
5085 else
5086 con->http._data_remaining = INT_MAX;
5087
f7deaa1a 5088 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
5089 (cupsd_selfunc_t)cupsdWriteClient, con);
e1d6a774 5090
5091 return (1);
5092}
5093
5094
5095/*
f899b121 5096 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5097 */
5098
5099static void
5100write_pipe(cupsd_client_t *con) /* I - Client connection */
5101{
b9faaae1
MS
5102 cupsdLogMessage(CUPSD_LOG_DEBUG2,
5103 "write_pipe(con=%p(%d)) CGI output on fd %d",
5104 con, con->http.fd, con->file);
f899b121 5105
5106 con->file_ready = 1;
5107
5108 cupsdRemoveSelect(con->file);
5109 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
5110}
5111
5112
5113/*
b19ccc9e 5114 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".
ef416fc2 5115 */