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