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