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