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