]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/client.c
Merge changes from CUPS 1.4svn-r8033.
[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_DONT_INSERT_EMPTY_FRAGMENTS);
3097 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
3098 SSL_CTX_use_certificate_chain_file(context, ServerCertificate);
3099
3100 bio = BIO_new(_httpBIOMethods());
3101 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)HTTP(con));
3102
3103 conn = SSL_new(context);
3104 SSL_set_bio(conn, bio, bio);
3105
3106 if (SSL_accept(conn) != 1)
3107 {
3108 cupsdLogMessage(CUPSD_LOG_ERROR,
3109 "encrypt_client: Unable to encrypt connection from %s!",
3110 con->http.hostname);
3111
3112 while ((error = ERR_get_error()) != 0)
3113 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
3114 ERR_error_string(error, NULL));
3115
3116 SSL_CTX_free(context);
3117 SSL_free(conn);
3118 return (0);
3119 }
3120
3121 cupsdLogMessage(CUPSD_LOG_DEBUG,
3122 "encrypt_client: %d Connection from %s now encrypted.",
3123 con->http.fd, con->http.hostname);
3124
3125 con->http.tls = conn;
3126 return (1);
3127
3128 # elif defined(HAVE_GNUTLS)
3129 http_tls_t *conn; /* TLS session object */
3130 int error; /* Error code */
3131 gnutls_certificate_server_credentials *credentials;
3132 /* TLS credentials */
3133
3134
3135 /*
3136 * Verify that we have a certificate...
3137 */
3138
3139 if (access(ServerKey, 0) || access(ServerCertificate, 0))
3140 {
3141 /*
3142 * Nope, make a self-signed certificate...
3143 */
3144
3145 if (!make_certificate(con))
3146 return (0);
3147 }
3148
3149 /*
3150 * Create the SSL object and perform the SSL handshake...
3151 */
3152
3153 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
3154
3155 if (conn == NULL)
3156 return (0);
3157
3158 credentials = (gnutls_certificate_server_credentials *)
3159 malloc(sizeof(gnutls_certificate_server_credentials));
3160 if (credentials == NULL)
3161 {
3162 cupsdLogMessage(CUPSD_LOG_ERROR,
3163 "encrypt_client: Unable to encrypt connection from %s!",
3164 con->http.hostname);
3165 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s", strerror(errno));
3166
3167 free(conn);
3168 return (0);
3169 }
3170
3171 gnutls_certificate_allocate_credentials(credentials);
3172 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
3173 ServerKey, GNUTLS_X509_FMT_PEM);
3174
3175 gnutls_init(&(conn->session), GNUTLS_SERVER);
3176 gnutls_set_default_priority(conn->session);
3177 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
3178 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)HTTP(con));
3179 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
3180 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
3181
3182 error = gnutls_handshake(conn->session);
3183
3184 if (error != GNUTLS_E_SUCCESS)
3185 {
3186 cupsdLogMessage(CUPSD_LOG_ERROR,
3187 "encrypt_client: Unable to encrypt connection from %s!",
3188 con->http.hostname);
3189 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
3190 gnutls_strerror(error));
3191
3192 gnutls_deinit(conn->session);
3193 gnutls_certificate_free_credentials(*credentials);
3194 free(conn);
3195 free(credentials);
3196 return (0);
3197 }
3198
3199 cupsdLogMessage(CUPSD_LOG_DEBUG,
3200 "encrypt_client: %d Connection from %s now encrypted.",
3201 con->http.fd, con->http.hostname);
3202
3203 conn->credentials = credentials;
3204 con->http.tls = conn;
3205 return (1);
3206
3207 # elif defined(HAVE_CDSASSL)
3208 OSStatus error; /* Error code */
3209 http_tls_t *conn; /* CDSA connection information */
3210
3211
3212 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
3213 return (0);
3214
3215 error = 0;
3216 conn->session = NULL;
3217 conn->certsArray = get_cdsa_certificate(con);
3218
3219 if (!conn->certsArray)
3220 {
3221 /*
3222 * No keychain (yet), make a self-signed certificate...
3223 */
3224
3225 if (make_certificate(con))
3226 conn->certsArray = get_cdsa_certificate(con);
3227 }
3228
3229 if (!conn->certsArray)
3230 {
3231 cupsdLogMessage(CUPSD_LOG_ERROR,
3232 "encrypt_client: Could not find signing key in keychain "
3233 "\"%s\"", ServerCertificate);
3234 error = errSSLBadCert; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3235 }
3236
3237 if (!error)
3238 error = SSLNewContext(true, &conn->session);
3239
3240 if (!error)
3241 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
3242
3243 if (!error)
3244 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
3245
3246 if (!error)
3247 error = SSLSetConnection(conn->session, HTTP(con));
3248
3249 if (!error)
3250 error = SSLSetAllowsExpiredCerts(conn->session, true);
3251
3252 if (!error)
3253 error = SSLSetAllowsAnyRoot(conn->session, true);
3254
3255 if (!error)
3256 error = SSLSetCertificate(conn->session, conn->certsArray);
3257
3258 if (!error)
3259 {
3260 /*
3261 * Perform SSL/TLS handshake
3262 */
3263
3264 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
3265 usleep(1000);
3266 }
3267
3268 if (error)
3269 {
3270 cupsdLogMessage(CUPSD_LOG_ERROR,
3271 "encrypt_client: Unable to encrypt connection from %s!",
3272 con->http.hostname);
3273
3274 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s (%d)",
3275 cssmErrorString(error), (int)error);
3276
3277 con->http.error = error;
3278 con->http.status = HTTP_ERROR;
3279
3280 if (conn->session)
3281 SSLDisposeContext(conn->session);
3282
3283 if (conn->certsArray)
3284 CFRelease(conn->certsArray);
3285
3286 free(conn);
3287
3288 return (0);
3289 }
3290
3291 cupsdLogMessage(CUPSD_LOG_DEBUG,
3292 "encrypt_client: %d Connection from %s now encrypted.",
3293 con->http.fd, con->http.hostname);
3294
3295 con->http.tls = conn;
3296 return (1);
3297
3298 # endif /* HAVE_LIBSSL */
3299 }
3300 #endif /* HAVE_SSL */
3301
3302
3303 #ifdef HAVE_CDSASSL
3304 /*
3305 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3306 */
3307
3308 static CFArrayRef /* O - Array of certificates */
3309 get_cdsa_certificate(cupsd_client_t *con) /* I - Client connection */
3310 {
3311 OSStatus err; /* Error info */
3312 SecKeychainRef keychain; /* Keychain reference */
3313 SecIdentitySearchRef search; /* Search reference */
3314 SecIdentityRef identity; /* Identity */
3315 CFArrayRef certificates = NULL;
3316 /* Certificate array */
3317
3318
3319 if ((err = SecKeychainOpen(ServerCertificate, &keychain)))
3320 {
3321 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\", %s",
3322 ServerCertificate, cssmErrorString(err));
3323 return (NULL);
3324 }
3325
3326 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3327 /*
3328 * Use a policy to search for valid certificates who's common name matches the
3329 * servername...
3330 */
3331
3332 SecPolicySearchRef policy_search; /* Policy search ref */
3333 SecPolicyRef policy; /* Policy ref */
3334 CSSM_DATA options; /* Policy options */
3335 CSSM_APPLE_TP_SSL_OPTIONS
3336 ssl_options; /* SSL Option for hostname */
3337
3338
3339 if (SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL,
3340 NULL, &policy_search))
3341 {
3342 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create a policy search reference");
3343 CFRelease(keychain);
3344 return (NULL);
3345 }
3346
3347 if (SecPolicySearchCopyNext(policy_search, &policy))
3348 {
3349 cupsdLogMessage(CUPSD_LOG_ERROR,
3350 "Cannot find a policy to use for searching");
3351 CFRelease(keychain);
3352 CFRelease(policy_search);
3353 return (NULL);
3354 }
3355
3356 memset(&ssl_options, 0, sizeof(ssl_options));
3357 ssl_options.Version = CSSM_APPLE_TP_SSL_OPTS_VERSION;
3358 ssl_options.ServerName = con->servername;
3359 ssl_options.ServerNameLen = strlen(con->servername);
3360
3361 options.Data = (uint8 *)&ssl_options;
3362 options.Length = sizeof(ssl_options);
3363
3364 if (SecPolicySetValue(policy, &options))
3365 {
3366 cupsdLogMessage(CUPSD_LOG_ERROR,
3367 "Cannot set policy value to use for searching");
3368 CFRelease(keychain);
3369 CFRelease(policy_search);
3370 return (NULL);
3371 }
3372
3373 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3374 keychain, FALSE, &search);
3375 # else
3376 /*
3377 * Assume there is exactly one SecIdentity in the keychain...
3378 */
3379
3380 err = SecIdentitySearchCreate(keychain, CSSM_KEYUSE_SIGN, &search);
3381 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3382
3383 if (err)
3384 cupsdLogMessage(CUPSD_LOG_DEBUG,
3385 "Cannot create keychain search reference: %s",
3386 cssmErrorString(err));
3387 else
3388 {
3389 if ((err = SecIdentitySearchCopyNext(search, &identity)))
3390 {
3391 cupsdLogMessage(CUPSD_LOG_DEBUG,
3392 "Cannot find signing key in keychain \"%s\", error %d",
3393 ServerCertificate, (int)err);
3394 }
3395 else
3396 {
3397 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3398 cupsdLogMessage(CUPSD_LOG_ERROR,
3399 "SecIdentitySearchCopyNext CFTypeID failure!");
3400 else
3401 {
3402 if ((certificates = CFArrayCreate(NULL, (const void **)&identity,
3403 1, &kCFTypeArrayCallBacks)) == NULL)
3404 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create certificate array");
3405 }
3406
3407 CFRelease(identity);
3408 }
3409
3410 CFRelease(search);
3411 }
3412
3413 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3414 CFRelease(policy);
3415 CFRelease(policy_search);
3416 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3417
3418 return (certificates);
3419 }
3420 #endif /* HAVE_CDSASSL */
3421
3422
3423 /*
3424 * 'get_file()' - Get a filename and state info.
3425 */
3426
3427 static char * /* O - Real filename */
3428 get_file(cupsd_client_t *con, /* I - Client connection */
3429 struct stat *filestats, /* O - File information */
3430 char *filename, /* IO - Filename buffer */
3431 int len) /* I - Buffer length */
3432 {
3433 int status; /* Status of filesystem calls */
3434 char *ptr; /* Pointer info filename */
3435 int plen; /* Remaining length after pointer */
3436 char language[7]; /* Language subdirectory, if any */
3437
3438
3439 /*
3440 * Figure out the real filename...
3441 */
3442
3443 language[0] = '\0';
3444
3445 if (!strncmp(con->uri, "/ppd/", 5))
3446 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
3447 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3448 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
3449 else if (!strncmp(con->uri, "/admin/conf/", 12))
3450 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3451 else if (!strncmp(con->uri, "/admin/log/", 11))
3452 {
3453 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
3454 strlcpy(filename, AccessLog, len);
3455 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
3456 strlcpy(filename, ErrorLog, len);
3457 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
3458 strlcpy(filename, PageLog, len);
3459 else
3460 return (NULL);
3461 }
3462 else if (con->language)
3463 {
3464 snprintf(language, sizeof(language), "/%s", con->language->language);
3465 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3466 }
3467 else
3468 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3469
3470 if ((ptr = strchr(filename, '?')) != NULL)
3471 *ptr = '\0';
3472
3473 /*
3474 * Grab the status for this language; if there isn't a language-specific file
3475 * then fallback to the default one...
3476 */
3477
3478 if ((status = stat(filename, filestats)) != 0 && language[0] &&
3479 strncmp(con->uri, "/ppd/", 5) &&
3480 strncmp(con->uri, "/admin/conf/", 12) &&
3481 strncmp(con->uri, "/admin/log/", 11))
3482 {
3483 /*
3484 * Drop the country code...
3485 */
3486
3487 language[3] = '\0';
3488 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3489
3490 if ((ptr = strchr(filename, '?')) != NULL)
3491 *ptr = '\0';
3492
3493 if ((status = stat(filename, filestats)) != 0)
3494 {
3495 /*
3496 * Drop the language prefix and try the root directory...
3497 */
3498
3499 language[0] = '\0';
3500 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3501
3502 if ((ptr = strchr(filename, '?')) != NULL)
3503 *ptr = '\0';
3504
3505 status = stat(filename, filestats);
3506 }
3507 }
3508
3509 /*
3510 * If we're found a directory, get the index.html file instead...
3511 */
3512
3513 if (!status && S_ISDIR(filestats->st_mode))
3514 {
3515 /*
3516 * Make sure the URI ends with a slash...
3517 */
3518
3519 if (con->uri[strlen(con->uri) - 1] != '/')
3520 strlcat(con->uri, "/", sizeof(con->uri));
3521
3522 /*
3523 * Find the directory index file, trying every language...
3524 */
3525
3526 do
3527 {
3528 if (status && language[0])
3529 {
3530 /*
3531 * Try a different language subset...
3532 */
3533
3534 if (language[3])
3535 language[0] = '\0'; /* Strip country code */
3536 else
3537 language[0] = '\0'; /* Strip language */
3538 }
3539
3540 /*
3541 * Look for the index file...
3542 */
3543
3544 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3545
3546 if ((ptr = strchr(filename, '?')) != NULL)
3547 *ptr = '\0';
3548
3549 ptr = filename + strlen(filename);
3550 plen = len - (ptr - filename);
3551
3552 strlcpy(ptr, "index.html", plen);
3553 status = stat(filename, filestats);
3554
3555 #ifdef HAVE_JAVA
3556 if (status)
3557 {
3558 strlcpy(ptr, "index.class", plen);
3559 status = stat(filename, filestats);
3560 }
3561 #endif /* HAVE_JAVA */
3562
3563 #ifdef HAVE_PERL
3564 if (status)
3565 {
3566 strlcpy(ptr, "index.pl", plen);
3567 status = stat(filename, filestats);
3568 }
3569 #endif /* HAVE_PERL */
3570
3571 #ifdef HAVE_PHP
3572 if (status)
3573 {
3574 strlcpy(ptr, "index.php", plen);
3575 status = stat(filename, filestats);
3576 }
3577 #endif /* HAVE_PHP */
3578
3579 #ifdef HAVE_PYTHON
3580 if (status)
3581 {
3582 strlcpy(ptr, "index.pyc", plen);
3583 status = stat(filename, filestats);
3584 }
3585
3586 if (status)
3587 {
3588 strlcpy(ptr, "index.py", plen);
3589 status = stat(filename, filestats);
3590 }
3591 #endif /* HAVE_PYTHON */
3592
3593 }
3594 while (status && language[0]);
3595 }
3596
3597 cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_file: %d filename=%s size=%d",
3598 con->http.fd, filename,
3599 status ? -1 : (int)filestats->st_size);
3600
3601 if (!status)
3602 con->http.data_remaining = (int)filestats->st_size;
3603
3604 if (status)
3605 return (NULL);
3606 else
3607 return (filename);
3608 }
3609
3610
3611 /*
3612 * 'install_conf_file()' - Install a configuration file.
3613 */
3614
3615 static http_status_t /* O - Status */
3616 install_conf_file(cupsd_client_t *con) /* I - Connection */
3617 {
3618 cups_file_t *in, /* Input file */
3619 *out; /* Output file */
3620 char buffer[1024]; /* Copy buffer */
3621 int bytes; /* Number of bytes */
3622 char conffile[1024], /* Configuration filename */
3623 newfile[1024], /* New config filename */
3624 oldfile[1024]; /* Old config filename */
3625 struct stat confinfo; /* Config file info */
3626
3627
3628 /*
3629 * First construct the filenames...
3630 */
3631
3632 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3633 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3634 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3635
3636 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3637
3638 /*
3639 * Get the owner, group, and permissions of the configuration file.
3640 * If it doesn't exist, assign it to the User and Group in the
3641 * cupsd.conf file with mode 0640 permissions.
3642 */
3643
3644 if (stat(conffile, &confinfo))
3645 {
3646 confinfo.st_uid = User;
3647 confinfo.st_gid = Group;
3648 confinfo.st_mode = ConfigFilePerm;
3649 }
3650
3651 /*
3652 * Open the request file and new config file...
3653 */
3654
3655 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3656 {
3657 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3658 con->filename, strerror(errno));
3659 return (HTTP_SERVER_ERROR);
3660 }
3661
3662 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3663 {
3664 cupsFileClose(in);
3665 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3666 newfile, strerror(errno));
3667 return (HTTP_SERVER_ERROR);
3668 }
3669
3670 fchmod(cupsFileNumber(out), confinfo.st_mode);
3671 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3672
3673 /*
3674 * Copy from the request to the new config file...
3675 */
3676
3677 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3678 if (cupsFileWrite(out, buffer, bytes) < bytes)
3679 {
3680 cupsdLogMessage(CUPSD_LOG_ERROR,
3681 "Unable to copy to config file \"%s\" - %s",
3682 newfile, strerror(errno));
3683
3684 cupsFileClose(in);
3685 cupsFileClose(out);
3686 unlink(newfile);
3687
3688 return (HTTP_SERVER_ERROR);
3689 }
3690
3691 /*
3692 * Close the files...
3693 */
3694
3695 cupsFileClose(in);
3696 if (cupsFileClose(out))
3697 {
3698 cupsdLogMessage(CUPSD_LOG_ERROR,
3699 "Error file closing config file \"%s\" - %s",
3700 newfile, strerror(errno));
3701
3702 unlink(newfile);
3703
3704 return (HTTP_SERVER_ERROR);
3705 }
3706
3707 /*
3708 * Remove the request file...
3709 */
3710
3711 unlink(con->filename);
3712 cupsdClearString(&con->filename);
3713
3714 /*
3715 * Unlink the old backup, rename the current config file to the backup
3716 * filename, and rename the new config file to the config file name...
3717 */
3718
3719 if (unlink(oldfile))
3720 if (errno != ENOENT)
3721 {
3722 cupsdLogMessage(CUPSD_LOG_ERROR,
3723 "Unable to remove backup config file \"%s\" - %s",
3724 oldfile, strerror(errno));
3725
3726 unlink(newfile);
3727
3728 return (HTTP_SERVER_ERROR);
3729 }
3730
3731 if (rename(conffile, oldfile))
3732 if (errno != ENOENT)
3733 {
3734 cupsdLogMessage(CUPSD_LOG_ERROR,
3735 "Unable to rename old config file \"%s\" - %s",
3736 conffile, strerror(errno));
3737
3738 unlink(newfile);
3739
3740 return (HTTP_SERVER_ERROR);
3741 }
3742
3743 if (rename(newfile, conffile))
3744 {
3745 cupsdLogMessage(CUPSD_LOG_ERROR,
3746 "Unable to rename new config file \"%s\" - %s",
3747 newfile, strerror(errno));
3748
3749 rename(oldfile, conffile);
3750 unlink(newfile);
3751
3752 return (HTTP_SERVER_ERROR);
3753 }
3754
3755 /*
3756 * If the cupsd.conf file was updated, set the NeedReload flag...
3757 */
3758
3759 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3760 NeedReload = RELOAD_CUPSD;
3761 else
3762 NeedReload = RELOAD_ALL;
3763
3764 ReloadTime = time(NULL);
3765
3766 /*
3767 * Return that the file was created successfully...
3768 */
3769
3770 return (HTTP_CREATED);
3771 }
3772
3773
3774 /*
3775 * 'is_cgi()' - Is the resource a CGI script/program?
3776 */
3777
3778 static int /* O - 1 = CGI, 0 = file */
3779 is_cgi(cupsd_client_t *con, /* I - Client connection */
3780 const char *filename, /* I - Real filename */
3781 struct stat *filestats, /* I - File information */
3782 mime_type_t *type) /* I - MIME type */
3783 {
3784 const char *options; /* Options on URL */
3785
3786
3787 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3788 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3789 con, filename, filestats, type ? type->super : "unknown",
3790 type ? type->type : "unknown");
3791
3792 /*
3793 * Get the options, if any...
3794 */
3795
3796 if ((options = strchr(con->uri, '?')) != NULL)
3797 {
3798 options ++;
3799 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3800 }
3801
3802 /*
3803 * Check for known types...
3804 */
3805
3806 if (!type || strcasecmp(type->super, "application"))
3807 {
3808 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3809 return (0);
3810 }
3811
3812 if (!strcasecmp(type->type, "x-httpd-cgi") &&
3813 (filestats->st_mode & 0111))
3814 {
3815 /*
3816 * "application/x-httpd-cgi" is a CGI script.
3817 */
3818
3819 cupsdSetString(&con->command, filename);
3820
3821 if (options)
3822 cupsdSetStringf(&con->options, " %s", options);
3823
3824 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3825 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3826 con->command, con->options);
3827
3828 return (1);
3829 }
3830 #ifdef HAVE_JAVA
3831 else if (!strcasecmp(type->type, "x-httpd-java"))
3832 {
3833 /*
3834 * "application/x-httpd-java" is a Java servlet.
3835 */
3836
3837 cupsdSetString(&con->command, CUPS_JAVA);
3838
3839 if (options)
3840 cupsdSetStringf(&con->options, " %s %s", filename, options);
3841 else
3842 cupsdSetStringf(&con->options, " %s", filename);
3843
3844 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3845 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3846 con->command, con->options);
3847
3848 return (1);
3849 }
3850 #endif /* HAVE_JAVA */
3851 #ifdef HAVE_PERL
3852 else if (!strcasecmp(type->type, "x-httpd-perl"))
3853 {
3854 /*
3855 * "application/x-httpd-perl" is a Perl page.
3856 */
3857
3858 cupsdSetString(&con->command, CUPS_PERL);
3859
3860 if (options)
3861 cupsdSetStringf(&con->options, " %s %s", filename, options);
3862 else
3863 cupsdSetStringf(&con->options, " %s", filename);
3864
3865 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3866 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3867 con->command, con->options);
3868
3869 return (1);
3870 }
3871 #endif /* HAVE_PERL */
3872 #ifdef HAVE_PHP
3873 else if (!strcasecmp(type->type, "x-httpd-php"))
3874 {
3875 /*
3876 * "application/x-httpd-php" is a PHP page.
3877 */
3878
3879 cupsdSetString(&con->command, CUPS_PHP);
3880
3881 if (options)
3882 cupsdSetStringf(&con->options, " %s %s", filename, options);
3883 else
3884 cupsdSetStringf(&con->options, " %s", filename);
3885
3886 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3887 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3888 con->command, con->options);
3889
3890 return (1);
3891 }
3892 #endif /* HAVE_PHP */
3893 #ifdef HAVE_PYTHON
3894 else if (!strcasecmp(type->type, "x-httpd-python"))
3895 {
3896 /*
3897 * "application/x-httpd-python" is a Python page.
3898 */
3899
3900 cupsdSetString(&con->command, CUPS_PYTHON);
3901
3902 if (options)
3903 cupsdSetStringf(&con->options, " %s %s", filename, options);
3904 else
3905 cupsdSetStringf(&con->options, " %s", filename);
3906
3907 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3908 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3909 con->command, con->options);
3910
3911 return (1);
3912 }
3913 #endif /* HAVE_PYTHON */
3914
3915 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3916
3917 return (0);
3918 }
3919
3920
3921 /*
3922 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3923 */
3924
3925 static int /* O - 0 if relative, 1 if absolute */
3926 is_path_absolute(const char *path) /* I - Input path */
3927 {
3928 /*
3929 * Check for a leading slash...
3930 */
3931
3932 if (path[0] != '/')
3933 return (0);
3934
3935 /*
3936 * Check for "/.." in the path...
3937 */
3938
3939 while ((path = strstr(path, "/..")) != NULL)
3940 {
3941 if (!path[3] || path[3] == '/')
3942 return (0);
3943
3944 path ++;
3945 }
3946
3947 /*
3948 * If we haven't found any relative paths, return 1 indicating an
3949 * absolute path...
3950 */
3951
3952 return (1);
3953 }
3954
3955
3956 #ifdef HAVE_SSL
3957 /*
3958 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3959 */
3960
3961 static int /* O - 1 on success, 0 on failure */
3962 make_certificate(cupsd_client_t *con) /* I - Client connection */
3963 {
3964 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3965 int pid, /* Process ID of command */
3966 status; /* Status of command */
3967 char command[1024], /* Command */
3968 *argv[12], /* Command-line arguments */
3969 *envp[MAX_ENV + 1], /* Environment variables */
3970 home[1024], /* HOME environment variable */
3971 infofile[1024], /* Type-in information for cert */
3972 seedfile[1024]; /* Random number seed file */
3973 int envc, /* Number of environment variables */
3974 bytes; /* Bytes written */
3975 cups_file_t *fp; /* Seed/info file */
3976 int infofd; /* Info file descriptor */
3977
3978
3979 /*
3980 * Run the "openssl" command to seed the random number generator and
3981 * generate a self-signed certificate that is good for 10 years:
3982 *
3983 * openssl rand -rand seedfile 1
3984 *
3985 * openssl req -new -x509 -keyout ServerKey \
3986 * -out ServerCertificate -days 3650 -nodes
3987 *
3988 * The seeding step is crucial in ensuring that the openssl command
3989 * does not block on systems without sufficient entropy...
3990 */
3991
3992 if (!cupsFileFind("openssl", getenv("PATH"), 1, command, sizeof(command)))
3993 {
3994 cupsdLogMessage(CUPSD_LOG_ERROR,
3995 "No SSL certificate and openssl command not found!");
3996 return (0);
3997 }
3998
3999 if (access("/dev/urandom", 0))
4000 {
4001 /*
4002 * If the system doesn't provide /dev/urandom, then any random source
4003 * will probably be blocking-style, so generate some random data to
4004 * use as a seed for the certificate. Note that we have already
4005 * seeded the random number generator in cupsdInitCerts()...
4006 */
4007
4008 cupsdLogMessage(CUPSD_LOG_INFO,
4009 "Seeding the random number generator...");
4010
4011 snprintf(home, sizeof(home), "HOME=%s", TempDir);
4012
4013 /*
4014 * Write the seed file...
4015 */
4016
4017 if ((fp = cupsTempFile2(seedfile, sizeof(seedfile))) == NULL)
4018 {
4019 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create seed file %s - %s",
4020 seedfile, strerror(errno));
4021 return (0);
4022 }
4023
4024 for (bytes = 0; bytes < 262144; bytes ++)
4025 cupsFilePutChar(fp, random());
4026
4027 cupsFileClose(fp);
4028
4029 /*
4030 * Run the openssl command to seed its random number generator...
4031 */
4032
4033 argv[0] = "openssl";
4034 argv[1] = "rand";
4035 argv[2] = "-rand";
4036 argv[3] = seedfile;
4037 argv[4] = "1";
4038 argv[5] = NULL;
4039
4040 envc = cupsdLoadEnv(envp, MAX_ENV);
4041 envp[envc++] = home;
4042 envp[envc] = NULL;
4043
4044 if (!cupsdStartProcess(command, argv, envp, -1, -1, -1, -1, -1, 1, NULL,
4045 &pid))
4046 {
4047 unlink(seedfile);
4048 return (0);
4049 }
4050
4051 while (waitpid(pid, &status, 0) < 0)
4052 if (errno != EINTR)
4053 {
4054 status = 1;
4055 break;
4056 }
4057
4058 cupsdFinishProcess(pid, command, sizeof(command));
4059
4060 /*
4061 * Remove the seed file, as it is no longer needed...
4062 */
4063
4064 unlink(seedfile);
4065
4066 if (status)
4067 {
4068 if (WIFEXITED(status))
4069 cupsdLogMessage(CUPSD_LOG_ERROR,
4070 "Unable to seed random number generator - "
4071 "the openssl command stopped with status %d!",
4072 WEXITSTATUS(status));
4073 else
4074 cupsdLogMessage(CUPSD_LOG_ERROR,
4075 "Unable to seed random number generator - "
4076 "the openssl command crashed on signal %d!",
4077 WTERMSIG(status));
4078
4079 return (0);
4080 }
4081 }
4082
4083 /*
4084 * Create a file with the certificate information fields...
4085 *
4086 * Note: This assumes that the default questions are asked by the openssl
4087 * command...
4088 */
4089
4090 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4091 {
4092 cupsdLogMessage(CUPSD_LOG_ERROR,
4093 "Unable to create certificate information file %s - %s",
4094 infofile, strerror(errno));
4095 return (0);
4096 }
4097
4098 cupsFilePrintf(fp, ".\n.\n.\n%s\n.\n%s\n%s\n",
4099 ServerName, ServerName, ServerAdmin);
4100 cupsFileClose(fp);
4101
4102 cupsdLogMessage(CUPSD_LOG_INFO,
4103 "Generating SSL server key and certificate...");
4104
4105 argv[0] = "openssl";
4106 argv[1] = "req";
4107 argv[2] = "-new";
4108 argv[3] = "-x509";
4109 argv[4] = "-keyout";
4110 argv[5] = ServerKey;
4111 argv[6] = "-out";
4112 argv[7] = ServerCertificate;
4113 argv[8] = "-days";
4114 argv[9] = "3650";
4115 argv[10] = "-nodes";
4116 argv[11] = NULL;
4117
4118 cupsdLoadEnv(envp, MAX_ENV);
4119
4120 infofd = open(infofile, O_RDONLY);
4121
4122 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4123 &pid))
4124 {
4125 close(infofd);
4126 unlink(infofile);
4127 return (0);
4128 }
4129
4130 close(infofd);
4131 unlink(infofile);
4132
4133 while (waitpid(pid, &status, 0) < 0)
4134 if (errno != EINTR)
4135 {
4136 status = 1;
4137 break;
4138 }
4139
4140 cupsdFinishProcess(pid, command, sizeof(command));
4141
4142 if (status)
4143 {
4144 if (WIFEXITED(status))
4145 cupsdLogMessage(CUPSD_LOG_ERROR,
4146 "Unable to create SSL server key and certificate - "
4147 "the openssl command stopped with status %d!",
4148 WEXITSTATUS(status));
4149 else
4150 cupsdLogMessage(CUPSD_LOG_ERROR,
4151 "Unable to create SSL server key and certificate - "
4152 "the openssl command crashed on signal %d!",
4153 WTERMSIG(status));
4154 }
4155 else
4156 {
4157 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4158 ServerKey);
4159 cupsdLogMessage(CUPSD_LOG_INFO,
4160 "Created SSL server certificate file \"%s\"...",
4161 ServerCertificate);
4162 }
4163
4164 return (!status);
4165
4166 #elif defined(HAVE_GNUTLS)
4167 gnutls_x509_crt crt; /* Self-signed certificate */
4168 gnutls_x509_privkey key; /* Encryption key */
4169 cups_lang_t *language; /* Default language info */
4170 cups_file_t *fp; /* Key/cert file */
4171 unsigned char buffer[8192]; /* Buffer for x509 data */
4172 size_t bytes; /* Number of bytes of data */
4173 unsigned char serial[4]; /* Serial number buffer */
4174 time_t curtime; /* Current time */
4175 int result; /* Result of GNU TLS calls */
4176
4177
4178 /*
4179 * Create the encryption key...
4180 */
4181
4182 cupsdLogMessage(CUPSD_LOG_INFO, "Generating SSL server key...");
4183
4184 gnutls_x509_privkey_init(&key);
4185 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
4186
4187 /*
4188 * Save it...
4189 */
4190
4191 bytes = sizeof(buffer);
4192
4193 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM,
4194 buffer, &bytes)) < 0)
4195 {
4196 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to export SSL server key - %s",
4197 gnutls_strerror(result));
4198 gnutls_x509_privkey_deinit(key);
4199 return (0);
4200 }
4201 else if ((fp = cupsFileOpen(ServerKey, "w")) != NULL)
4202 {
4203 cupsFileWrite(fp, (char *)buffer, bytes);
4204 cupsFileClose(fp);
4205
4206 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4207 ServerKey);
4208 }
4209 else
4210 {
4211 cupsdLogMessage(CUPSD_LOG_ERROR,
4212 "Unable to create SSL server key file \"%s\" - %s",
4213 ServerKey, strerror(errno));
4214 gnutls_x509_privkey_deinit(key);
4215 return (0);
4216 }
4217
4218 /*
4219 * Create the self-signed certificate...
4220 */
4221
4222 cupsdLogMessage(CUPSD_LOG_INFO, "Generating self-signed SSL certificate...");
4223
4224 language = cupsLangDefault();
4225 curtime = time(NULL);
4226 serial[0] = curtime >> 24;
4227 serial[1] = curtime >> 16;
4228 serial[2] = curtime >> 8;
4229 serial[3] = curtime;
4230
4231 gnutls_x509_crt_init(&crt);
4232 if (strlen(language->language) == 5)
4233 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4234 language->language + 3, 2);
4235 else
4236 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4237 "US", 2);
4238 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
4239 ServerName, strlen(ServerName));
4240 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
4241 ServerName, strlen(ServerName));
4242 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
4243 0, "Unknown", 7);
4244 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
4245 "Unknown", 7);
4246 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
4247 "Unknown", 7);
4248 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
4249 ServerAdmin, strlen(ServerAdmin));
4250 gnutls_x509_crt_set_key(crt, key);
4251 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
4252 gnutls_x509_crt_set_activation_time(crt, curtime);
4253 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
4254 gnutls_x509_crt_set_ca_status(crt, 0);
4255 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME,
4256 ServerName);
4257 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
4258 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
4259 gnutls_x509_crt_set_version(crt, 3);
4260
4261 bytes = sizeof(buffer);
4262 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
4263 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
4264
4265 gnutls_x509_crt_sign(crt, crt, key);
4266
4267 /*
4268 * Save it...
4269 */
4270
4271 bytes = sizeof(buffer);
4272 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM,
4273 buffer, &bytes)) < 0)
4274 cupsdLogMessage(CUPSD_LOG_ERROR,
4275 "Unable to export SSL server certificate - %s",
4276 gnutls_strerror(result));
4277 else if ((fp = cupsFileOpen(ServerCertificate, "w")) != NULL)
4278 {
4279 cupsFileWrite(fp, (char *)buffer, bytes);
4280 cupsFileClose(fp);
4281
4282 cupsdLogMessage(CUPSD_LOG_INFO,
4283 "Created SSL server certificate file \"%s\"...",
4284 ServerCertificate);
4285 }
4286 else
4287 cupsdLogMessage(CUPSD_LOG_ERROR,
4288 "Unable to create SSL server certificate file \"%s\" - %s",
4289 ServerCertificate, strerror(errno));
4290
4291 /*
4292 * Cleanup...
4293 */
4294
4295 gnutls_x509_crt_deinit(crt);
4296 gnutls_x509_privkey_deinit(key);
4297
4298 return (1);
4299
4300 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4301 int pid, /* Process ID of command */
4302 status; /* Status of command */
4303 char command[1024], /* Command */
4304 *argv[4], /* Command-line arguments */
4305 *envp[MAX_ENV + 1], /* Environment variables */
4306 keychain[1024], /* Keychain argument */
4307 infofile[1024]; /* Type-in information for cert */
4308 cups_file_t *fp; /* Seed/info file */
4309 int infofd; /* Info file descriptor */
4310
4311
4312 /*
4313 * Run the "certtool" command to generate a self-signed certificate...
4314 */
4315
4316 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
4317 {
4318 cupsdLogMessage(CUPSD_LOG_ERROR,
4319 "No SSL certificate and certtool command not found!");
4320 return (0);
4321 }
4322
4323 /*
4324 * Create a file with the certificate information fields...
4325 *
4326 * Note: This assumes that the default questions are asked by the certtool
4327 * command...
4328 */
4329
4330 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4331 {
4332 cupsdLogMessage(CUPSD_LOG_ERROR,
4333 "Unable to create certificate information file %s - %s",
4334 infofile, strerror(errno));
4335 return (0);
4336 }
4337
4338 cupsFilePrintf(fp, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4339 con->servername, con->servername, ServerAdmin);
4340 cupsFileClose(fp);
4341
4342 cupsdLogMessage(CUPSD_LOG_INFO,
4343 "Generating SSL server key and certificate...");
4344
4345 snprintf(keychain, sizeof(keychain), "k=%s", ServerCertificate);
4346
4347 argv[0] = "certtool";
4348 argv[1] = "c";
4349 argv[2] = keychain;
4350 argv[3] = NULL;
4351
4352 cupsdLoadEnv(envp, MAX_ENV);
4353
4354 infofd = open(infofile, O_RDONLY);
4355
4356 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4357 &pid))
4358 {
4359 close(infofd);
4360 unlink(infofile);
4361 return (0);
4362 }
4363
4364 close(infofd);
4365 unlink(infofile);
4366
4367 while (waitpid(pid, &status, 0) < 0)
4368 if (errno != EINTR)
4369 {
4370 status = 1;
4371 break;
4372 }
4373
4374 cupsdFinishProcess(pid, command, sizeof(command));
4375
4376 if (status)
4377 {
4378 if (WIFEXITED(status))
4379 cupsdLogMessage(CUPSD_LOG_ERROR,
4380 "Unable to create SSL server key and certificate - "
4381 "the certtool command stopped with status %d!",
4382 WEXITSTATUS(status));
4383 else
4384 cupsdLogMessage(CUPSD_LOG_ERROR,
4385 "Unable to create SSL server key and certificate - "
4386 "the certtool command crashed on signal %d!",
4387 WTERMSIG(status));
4388 }
4389 else
4390 {
4391 cupsdLogMessage(CUPSD_LOG_INFO,
4392 "Created SSL server certificate file \"%s\"...",
4393 ServerCertificate);
4394 }
4395
4396 return (!status);
4397
4398 #else
4399 return (0);
4400 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4401 }
4402 #endif /* HAVE_SSL */
4403
4404
4405 /*
4406 * 'pipe_command()' - Pipe the output of a command to the remote client.
4407 */
4408
4409 static int /* O - Process ID */
4410 pipe_command(cupsd_client_t *con, /* I - Client connection */
4411 int infile, /* I - Standard input for command */
4412 int *outfile, /* O - Standard output for command */
4413 char *command, /* I - Command to run */
4414 char *options, /* I - Options for command */
4415 int root) /* I - Run as root? */
4416 {
4417 int i; /* Looping var */
4418 int pid; /* Process ID */
4419 char *commptr, /* Command string pointer */
4420 commch; /* Command string character */
4421 char *uriptr; /* URI string pointer */
4422 int fds[2]; /* Pipe FDs */
4423 int argc; /* Number of arguments */
4424 int envc; /* Number of environment variables */
4425 char argbuf[10240], /* Argument buffer */
4426 *argv[100], /* Argument strings */
4427 *envp[MAX_ENV + 20]; /* Environment variables */
4428 char auth_type[256], /* CUPSD_AUTH_TYPE environment variable */
4429 content_length[1024], /* CONTENT_LENGTH environment variable */
4430 content_type[1024], /* CONTENT_TYPE environment variable */
4431 http_cookie[32768], /* HTTP_COOKIE environment variable */
4432 http_referer[1024], /* HTTP_REFERER environment variable */
4433 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
4434 lang[1024], /* LANG environment variable */
4435 path_info[1024], /* PATH_INFO environment variable */
4436 remote_addr[1024], /* REMOTE_ADDR environment variable */
4437 remote_host[1024], /* REMOTE_HOST environment variable */
4438 remote_user[1024], /* REMOTE_USER environment variable */
4439 script_filename[1024], /* SCRIPT_FILENAME environment variable */
4440 script_name[1024], /* SCRIPT_NAME environment variable */
4441 server_name[1024], /* SERVER_NAME environment variable */
4442 server_port[1024]; /* SERVER_PORT environment variable */
4443 ipp_attribute_t *attr; /* attributes-natural-language attribute */
4444 #ifdef HAVE_GSSAPI
4445 krb5_ccache ccache = NULL; /* Kerberos credentials */
4446 char krb5ccname[1024]; /* KRB5CCNAME environment variable */
4447 #endif /* HAVE_GSSAPI */
4448
4449
4450 /*
4451 * Parse a copy of the options string, which is of the form:
4452 *
4453 * argument+argument+argument
4454 * ?argument+argument+argument
4455 * param=value&param=value
4456 * ?param=value&param=value
4457 * /name?argument+argument+argument
4458 * /name?param=value&param=value
4459 *
4460 * If the string contains an "=" character after the initial name,
4461 * then we treat it as a HTTP GET form request and make a copy of
4462 * the remaining string for the environment variable.
4463 *
4464 * The string is always parsed out as command-line arguments, to
4465 * be consistent with Apache...
4466 */
4467
4468 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4469 "pipe_command: command=\"%s\", options=\"%s\"",
4470 command, options ? options : "(null)");
4471
4472 argv[0] = command;
4473
4474 if (options)
4475 strlcpy(argbuf, options, sizeof(argbuf));
4476 else
4477 argbuf[0] = '\0';
4478
4479 if (argbuf[0] == '/')
4480 {
4481 /*
4482 * Found some trailing path information, set PATH_INFO...
4483 */
4484
4485 if ((commptr = strchr(argbuf, '?')) == NULL)
4486 commptr = argbuf + strlen(argbuf);
4487
4488 commch = *commptr;
4489 *commptr = '\0';
4490 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
4491 *commptr = commch;
4492 }
4493 else
4494 {
4495 commptr = argbuf;
4496 path_info[0] = '\0';
4497
4498 if (*commptr == ' ')
4499 commptr ++;
4500 }
4501
4502 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
4503 {
4504 commptr ++;
4505 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
4506 }
4507
4508 argc = 1;
4509
4510 if (*commptr)
4511 {
4512 argv[argc ++] = commptr;
4513
4514 for (; *commptr && argc < 99; commptr ++)
4515 {
4516 /*
4517 * Break arguments whenever we see a + or space...
4518 */
4519
4520 if (*commptr == ' ' || *commptr == '+')
4521 {
4522 while (*commptr == ' ' || *commptr == '+')
4523 *commptr++ = '\0';
4524
4525 /*
4526 * If we don't have a blank string, save it as another argument...
4527 */
4528
4529 if (*commptr)
4530 {
4531 argv[argc] = commptr;
4532 argc ++;
4533 }
4534 else
4535 break;
4536 }
4537 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
4538 isxdigit(commptr[2] & 255))
4539 {
4540 /*
4541 * Convert the %xx notation to the individual character.
4542 */
4543
4544 if (commptr[1] >= '0' && commptr[1] <= '9')
4545 *commptr = (commptr[1] - '0') << 4;
4546 else
4547 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
4548
4549 if (commptr[2] >= '0' && commptr[2] <= '9')
4550 *commptr |= commptr[2] - '0';
4551 else
4552 *commptr |= tolower(commptr[2]) - 'a' + 10;
4553
4554 _cups_strcpy(commptr + 1, commptr + 3);
4555
4556 /*
4557 * Check for a %00 and break if that is the case...
4558 */
4559
4560 if (!*commptr)
4561 break;
4562 }
4563 }
4564 }
4565
4566 argv[argc] = NULL;
4567
4568 /*
4569 * Setup the environment variables as needed...
4570 */
4571
4572 if (con->username[0])
4573 {
4574 snprintf(auth_type, sizeof(auth_type), "CUPSD_AUTH_TYPE=%s",
4575 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
4576
4577 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
4578 *uriptr = '\0';
4579 }
4580 else
4581 auth_type[0] = '\0';
4582
4583 if (con->request &&
4584 (attr = ippFindAttribute(con->request, "attributes-natural-language",
4585 IPP_TAG_LANGUAGE)) != NULL)
4586 {
4587 switch (strlen(attr->values[0].string.text))
4588 {
4589 default :
4590 /*
4591 * This is an unknown or badly formatted language code; use
4592 * the POSIX locale...
4593 */
4594
4595 strcpy(lang, "LANG=C");
4596 break;
4597
4598 case 2 :
4599 /*
4600 * Just the language code (ll)...
4601 */
4602
4603 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
4604 attr->values[0].string.text);
4605 break;
4606
4607 case 5 :
4608 /*
4609 * Language and country code (ll-cc)...
4610 */
4611
4612 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
4613 attr->values[0].string.text[0],
4614 attr->values[0].string.text[1],
4615 toupper(attr->values[0].string.text[3] & 255),
4616 toupper(attr->values[0].string.text[4] & 255));
4617 break;
4618 }
4619 }
4620 else if (con->language)
4621 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
4622 else
4623 strcpy(lang, "LANG=C");
4624
4625 strcpy(remote_addr, "REMOTE_ADDR=");
4626 httpAddrString(con->http.hostaddr, remote_addr + 12,
4627 sizeof(remote_addr) - 12);
4628
4629 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
4630 con->http.hostname);
4631
4632 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
4633 if ((uriptr = strchr(script_name, '?')) != NULL)
4634 *uriptr = '\0';
4635
4636 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
4637 DocumentRoot, script_name + 12);
4638
4639 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
4640
4641 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
4642 con->servername);
4643
4644 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
4645
4646 if (auth_type[0])
4647 envp[envc ++] = auth_type;
4648
4649 envp[envc ++] = lang;
4650 envp[envc ++] = "REDIRECT_STATUS=1";
4651 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
4652 envp[envc ++] = server_name;
4653 envp[envc ++] = server_port;
4654 envp[envc ++] = remote_addr;
4655 envp[envc ++] = remote_host;
4656 envp[envc ++] = script_name;
4657 envp[envc ++] = script_filename;
4658
4659 if (path_info[0])
4660 envp[envc ++] = path_info;
4661
4662 if (con->username[0])
4663 {
4664 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
4665
4666 envp[envc ++] = remote_user;
4667
4668 /*
4669 * Save Kerberos credentials, if any...
4670 */
4671
4672 #ifdef HAVE_GSSAPI
4673 if (con->gss_have_creds)
4674 {
4675 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4676 cupsdLogMessage(CUPSD_LOG_INFO,
4677 "Sorry, your version of Kerberos does not support "
4678 "delegated credentials!");
4679
4680 # else
4681 krb5_error_code error; /* Kerberos error code */
4682 OM_uint32 major_status, /* Major status code */
4683 minor_status; /* Minor status code */
4684 krb5_principal principal; /* Kerberos principal */
4685
4686
4687 # ifdef __APPLE__
4688 /*
4689 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4690 * to use it...
4691 */
4692
4693 if (krb5_init_context != NULL)
4694 {
4695 # endif /* __APPLE__ */
4696
4697 if (!KerberosInitialized)
4698 {
4699 /*
4700 * Setup a Kerberos context for the scheduler to use...
4701 */
4702
4703 KerberosInitialized = 1;
4704
4705 if (krb5_init_context(&KerberosContext))
4706 {
4707 KerberosContext = NULL;
4708
4709 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to initialize Kerberos context");
4710 }
4711 }
4712
4713 /*
4714 * We MUST create a file-based cache because memory-based caches are
4715 * only valid for the current process/address space.
4716 *
4717 * Due to various bugs/features in different versions of Kerberos, we
4718 * need either the krb5_cc_new_unique() function or Heimdal's version
4719 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4720 * can be passed to the backend. These functions create a temporary
4721 * file (typically in /tmp) containing the cached credentials, which
4722 * are removed when we have successfully printed a job.
4723 */
4724
4725 if (KerberosContext)
4726 {
4727 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4728 if ((error = krb5_cc_new_unique(KerberosContext, "FILE", NULL,
4729 &ccache)) != 0)
4730 # else /* HAVE_HEIMDAL */
4731 if ((error = krb5_cc_gen_new(KerberosContext, &krb5_fcc_ops,
4732 &ccache)) != 0)
4733 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4734 {
4735 cupsdLogMessage(CUPSD_LOG_ERROR,
4736 "Unable to create new credentials cache (%d/%s)",
4737 error, strerror(errno));
4738 ccache = NULL;
4739 }
4740 else if ((error = krb5_parse_name(KerberosContext, con->username,
4741 &principal)) != 0)
4742 {
4743 cupsdLogMessage(CUPSD_LOG_ERROR,
4744 "Unable to parse kerberos username (%d/%s)", error,
4745 strerror(errno));
4746 krb5_cc_destroy(KerberosContext, ccache);
4747 ccache = NULL;
4748 }
4749 else if ((error = krb5_cc_initialize(KerberosContext, ccache,
4750 principal)))
4751 {
4752 cupsdLogMessage(CUPSD_LOG_ERROR,
4753 "Unable to initialize credentials cache (%d/%s)", error,
4754 strerror(errno));
4755 krb5_cc_destroy(KerberosContext, ccache);
4756 krb5_free_principal(KerberosContext, principal);
4757 ccache = NULL;
4758 }
4759 else
4760 {
4761 krb5_free_principal(KerberosContext, principal);
4762
4763 /*
4764 * Copy the user's credentials to the new cache file...
4765 */
4766
4767 major_status = gss_krb5_copy_ccache(&minor_status,
4768 con->gss_delegated_cred, ccache);
4769
4770 if (GSS_ERROR(major_status))
4771 {
4772 cupsdLogGSSMessage(CUPSD_LOG_ERROR, major_status, minor_status,
4773 "Unable to import client credentials cache");
4774 krb5_cc_destroy(KerberosContext, ccache);
4775 ccache = NULL;
4776 }
4777 else
4778 {
4779 /*
4780 * Add the KRB5CCNAME environment variable to the job so that the
4781 * backend can use the credentials when printing.
4782 */
4783
4784 snprintf(krb5ccname, sizeof(krb5ccname), "KRB5CCNAME=FILE:%s",
4785 krb5_cc_get_name(KerberosContext, ccache));
4786 envp[envc++] = krb5ccname;
4787
4788 if (!RunUser)
4789 chown(krb5_cc_get_name(KerberosContext, ccache), User, Group);
4790 }
4791 }
4792 }
4793 # ifdef __APPLE__
4794 }
4795 # endif /* __APPLE__ */
4796 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4797 }
4798 #endif /* HAVE_GSSAPI */
4799 }
4800
4801 if (con->http.version == HTTP_1_1)
4802 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
4803 else if (con->http.version == HTTP_1_0)
4804 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
4805 else
4806 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
4807
4808 if (con->http.cookie)
4809 {
4810 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
4811 con->http.cookie);
4812 envp[envc ++] = http_cookie;
4813 }
4814
4815 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
4816 {
4817 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
4818 con->http.fields[HTTP_FIELD_USER_AGENT]);
4819 envp[envc ++] = http_user_agent;
4820 }
4821
4822 if (con->http.fields[HTTP_FIELD_REFERER][0])
4823 {
4824 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
4825 con->http.fields[HTTP_FIELD_REFERER]);
4826 envp[envc ++] = http_referer;
4827 }
4828
4829 if (con->operation == HTTP_GET)
4830 {
4831 envp[envc ++] = "REQUEST_METHOD=GET";
4832
4833 if (con->query_string)
4834 {
4835 /*
4836 * Add GET form variables after ?...
4837 */
4838
4839 envp[envc ++] = con->query_string;
4840 }
4841 else
4842 envp[envc ++] = "QUERY_STRING=";
4843 }
4844 else
4845 {
4846 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
4847 CUPS_LLCAST con->bytes);
4848 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
4849 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
4850
4851 envp[envc ++] = "REQUEST_METHOD=POST";
4852 envp[envc ++] = content_length;
4853 envp[envc ++] = content_type;
4854 }
4855
4856 /*
4857 * Tell the CGI if we are using encryption...
4858 */
4859
4860 if (con->http.tls)
4861 envp[envc ++] = "HTTPS=ON";
4862
4863 /*
4864 * Terminate the environment array...
4865 */
4866
4867 envp[envc] = NULL;
4868
4869 if (LogLevel == CUPSD_LOG_DEBUG2)
4870 {
4871 for (i = 0; i < argc; i ++)
4872 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4873 "pipe_command: argv[%d] = \"%s\"", i, argv[i]);
4874 for (i = 0; i < envc; i ++)
4875 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4876 "pipe_command: envp[%d] = \"%s\"", i, envp[i]);
4877 }
4878
4879 /*
4880 * Create a pipe for the output...
4881 */
4882
4883 if (cupsdOpenPipe(fds))
4884 {
4885 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create pipes for CGI %s - %s",
4886 argv[0], strerror(errno));
4887 return (0);
4888 }
4889
4890 /*
4891 * Then execute the command...
4892 */
4893
4894 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
4895 -1, -1, root, DefaultProfile, &pid) < 0)
4896 {
4897 /*
4898 * Error - can't fork!
4899 */
4900
4901 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork for CGI %s - %s", argv[0],
4902 strerror(errno));
4903
4904 cupsdClosePipe(fds);
4905 pid = 0;
4906 }
4907 else
4908 {
4909 /*
4910 * Fork successful - return the PID...
4911 */
4912
4913 if (con->username[0])
4914 #ifdef HAVE_GSSAPI
4915 cupsdAddCert(pid, con->username, ccache);
4916 #else
4917 cupsdAddCert(pid, con->username, NULL);
4918 #endif /* HAVE_GSSAPI */
4919
4920 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] %s started - PID = %d",
4921 command, pid);
4922
4923 *outfile = fds[0];
4924 close(fds[1]);
4925 }
4926
4927 return (pid);
4928 }
4929
4930
4931 /*
4932 * 'write_file()' - Send a file via HTTP.
4933 */
4934
4935 static int /* O - 0 on failure, 1 on success */
4936 write_file(cupsd_client_t *con, /* I - Client connection */
4937 http_status_t code, /* I - HTTP status */
4938 char *filename, /* I - Filename */
4939 char *type, /* I - File type */
4940 struct stat *filestats) /* O - File information */
4941 {
4942 con->file = open(filename, O_RDONLY);
4943
4944 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_file: %d file=%d", con->http.fd,
4945 con->file);
4946
4947 if (con->file < 0)
4948 return (0);
4949
4950 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4951
4952 con->pipe_pid = 0;
4953
4954 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
4955 return (0);
4956
4957 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
4958 httpGetDateString(filestats->st_mtime)) < 0)
4959 return (0);
4960 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
4961 CUPS_LLCAST filestats->st_size) < 0)
4962 return (0);
4963 if (httpPrintf(HTTP(con), "\r\n") < 0)
4964 return (0);
4965
4966 if (cupsdFlushHeader(con) < 0)
4967 return (0);
4968
4969 con->http.data_encoding = HTTP_ENCODE_LENGTH;
4970 con->http.data_remaining = filestats->st_size;
4971
4972 if (con->http.data_remaining <= INT_MAX)
4973 con->http._data_remaining = con->http.data_remaining;
4974 else
4975 con->http._data_remaining = INT_MAX;
4976
4977 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
4978 (cupsd_selfunc_t)cupsdWriteClient, con);
4979
4980 return (1);
4981 }
4982
4983
4984 /*
4985 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4986 */
4987
4988 static void
4989 write_pipe(cupsd_client_t *con) /* I - Client connection */
4990 {
4991 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d...",
4992 con->file);
4993
4994 con->file_ready = 1;
4995
4996 cupsdRemoveSelect(con->file);
4997 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4998 }
4999
5000
5001 /*
5002 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".
5003 */