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