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