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