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