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