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