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