]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/client.c
Import CUPS 1.4svn-r7153.
[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 if (con->file < 0)
1643 {
1644 cupsdLogMessage(CUPSD_LOG_ERROR,
1645 "Unable to create request file %s: %s",
1646 con->filename, strerror(errno));
1647
1648 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, AUTH_NONE))
1649 {
1650 cupsdCloseClient(con);
1651 return;
1652 }
1653 }
1654
1655 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1656 "cupsdReadClient: %d REQUEST %s=%d", con->http.fd,
1657 con->filename, con->file);
1658
1659 fchmod(con->file, 0640);
1660 fchown(con->file, RunUser, Group);
1661 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1662 break;
1663
1664 case HTTP_DELETE :
1665 case HTTP_TRACE :
1666 cupsdSendError(con, HTTP_NOT_IMPLEMENTED, AUTH_NONE);
1667 cupsdCloseClient(con);
1668 return;
1669
1670 case HTTP_HEAD :
1671 if (!strncmp(con->uri, "/printers/", 10) &&
1672 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1673 {
1674 /*
1675 * Send PPD file - get the real printer name since printer
1676 * names are not case sensitive but filenames can be...
1677 */
1678
1679 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1680
1681 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1682 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1683 else
1684 {
1685 if (!cupsdSendError(con, HTTP_NOT_FOUND, AUTH_NONE))
1686 {
1687 cupsdCloseClient(con);
1688 return;
1689 }
1690
1691 break;
1692 }
1693 }
1694
1695 if ((!strncmp(con->uri, "/admin", 6) &&
1696 strncmp(con->uri, "/admin/conf/", 12) &&
1697 strncmp(con->uri, "/admin/log/", 11)) ||
1698 !strncmp(con->uri, "/printers", 9) ||
1699 !strncmp(con->uri, "/classes", 8) ||
1700 !strncmp(con->uri, "/help", 5) ||
1701 !strncmp(con->uri, "/jobs", 5))
1702 {
1703 /*
1704 * CGI output...
1705 */
1706
1707 if (!cupsdSendHeader(con, HTTP_OK, "text/html", AUTH_NONE))
1708 {
1709 cupsdCloseClient(con);
1710 return;
1711 }
1712
1713 if (httpPrintf(HTTP(con), "\r\n") < 0)
1714 {
1715 cupsdCloseClient(con);
1716 return;
1717 }
1718
1719 if (cupsdFlushHeader(con) < 0)
1720 {
1721 cupsdCloseClient(con);
1722 return;
1723 }
1724
1725 cupsdLogRequest(con, HTTP_OK);
1726 }
1727 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1728 (strchr(con->uri + 12, '/') ||
1729 strlen(con->uri) == 12)) ||
1730 (!strncmp(con->uri, "/admin/log/", 11) &&
1731 (strchr(con->uri + 11, '/') ||
1732 strlen(con->uri) == 11)))
1733 {
1734 /*
1735 * HEAD can only be done to configuration files under
1736 * /admin/conf...
1737 */
1738
1739 if (!cupsdSendError(con, HTTP_FORBIDDEN, AUTH_NONE))
1740 {
1741 cupsdCloseClient(con);
1742 return;
1743 }
1744
1745 break;
1746 }
1747 else if ((filename = get_file(con, &filestats, buf,
1748 sizeof(buf))) == NULL)
1749 {
1750 if (!cupsdSendHeader(con, HTTP_NOT_FOUND, "text/html", AUTH_NONE))
1751 {
1752 cupsdCloseClient(con);
1753 return;
1754 }
1755
1756 cupsdLogRequest(con, HTTP_NOT_FOUND);
1757 }
1758 else if (!check_if_modified(con, &filestats))
1759 {
1760 if (!cupsdSendError(con, HTTP_NOT_MODIFIED, AUTH_NONE))
1761 {
1762 cupsdCloseClient(con);
1763 return;
1764 }
1765
1766 cupsdLogRequest(con, HTTP_NOT_MODIFIED);
1767 }
1768 else
1769 {
1770 /*
1771 * Serve a file...
1772 */
1773
1774 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1775 if (type == NULL)
1776 strcpy(line, "text/plain");
1777 else
1778 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1779
1780 if (!cupsdSendHeader(con, HTTP_OK, line, AUTH_NONE))
1781 {
1782 cupsdCloseClient(con);
1783 return;
1784 }
1785
1786 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
1787 httpGetDateString(filestats.st_mtime)) < 0)
1788 {
1789 cupsdCloseClient(con);
1790 return;
1791 }
1792
1793 if (httpPrintf(HTTP(con), "Content-Length: %lu\r\n",
1794 (unsigned long)filestats.st_size) < 0)
1795 {
1796 cupsdCloseClient(con);
1797 return;
1798 }
1799
1800 cupsdLogRequest(con, HTTP_OK);
1801 }
1802
1803 if (httpPrintf(HTTP(con), "\r\n") < 0)
1804 {
1805 cupsdCloseClient(con);
1806 return;
1807 }
1808
1809 if (cupsdFlushHeader(con) < 0)
1810 {
1811 cupsdCloseClient(con);
1812 return;
1813 }
1814
1815 con->http.state = HTTP_WAITING;
1816 break;
1817
1818 default :
1819 break; /* Anti-compiler-warning-code */
1820 }
1821 }
1822 }
1823
1824 /*
1825 * Handle any incoming data...
1826 */
1827
1828 switch (con->http.state)
1829 {
1830 case HTTP_PUT_RECV :
1831 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1832 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1833 "con->data_remaining=" CUPS_LLFMT ", con->file=%d",
1834 con->http.fd,
1835 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
1836 "CHUNKED" : "LENGTH",
1837 CUPS_LLCAST con->http.data_remaining, con->file);
1838
1839 do
1840 {
1841 if ((bytes = httpRead2(HTTP(con), line, sizeof(line))) < 0)
1842 {
1843 cupsdCloseClient(con);
1844 return;
1845 }
1846 else if (bytes > 0)
1847 {
1848 con->bytes += bytes;
1849
1850 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1851 "cupsdReadClient: %d writing %d bytes to %d",
1852 con->http.fd, bytes, con->file);
1853
1854 if (write(con->file, line, bytes) < bytes)
1855 {
1856 cupsdLogMessage(CUPSD_LOG_ERROR,
1857 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1858 bytes, con->filename, strerror(errno));
1859
1860 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1861 "cupsdReadClient: Closing data file %d...",
1862 con->file);
1863
1864 close(con->file);
1865 con->file = -1;
1866 unlink(con->filename);
1867 cupsdClearString(&con->filename);
1868
1869 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, AUTH_NONE))
1870 {
1871 cupsdCloseClient(con);
1872 return;
1873 }
1874 }
1875 }
1876 }
1877 while (con->http.state == HTTP_PUT_RECV && con->http.used > 0);
1878
1879 if (con->http.state == HTTP_WAITING)
1880 {
1881 /*
1882 * End of file, see how big it is...
1883 */
1884
1885 fstat(con->file, &filestats);
1886
1887 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1888 "cupsdReadClient: %d Closing data file %d, size="
1889 CUPS_LLFMT ".",
1890 con->http.fd, con->file,
1891 CUPS_LLCAST filestats.st_size);
1892
1893 close(con->file);
1894 con->file = -1;
1895
1896 if (filestats.st_size > MaxRequestSize &&
1897 MaxRequestSize > 0)
1898 {
1899 /*
1900 * Request is too big; remove it and send an error...
1901 */
1902
1903 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1904 "cupsdReadClient: %d Removing temp file %s",
1905 con->http.fd, con->filename);
1906 unlink(con->filename);
1907 cupsdClearString(&con->filename);
1908
1909 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, AUTH_NONE))
1910 {
1911 cupsdCloseClient(con);
1912 return;
1913 }
1914 }
1915
1916 /*
1917 * Install the configuration file...
1918 */
1919
1920 status = install_conf_file(con);
1921
1922 /*
1923 * Return the status to the client...
1924 */
1925
1926 if (!cupsdSendError(con, status, AUTH_NONE))
1927 {
1928 cupsdCloseClient(con);
1929 return;
1930 }
1931 }
1932 break;
1933
1934 case HTTP_POST_RECV :
1935 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1936 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1937 "%s, con->data_remaining=" CUPS_LLFMT ", con->file=%d",
1938 con->http.fd,
1939 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
1940 "CHUNKED" : "LENGTH",
1941 CUPS_LLCAST con->http.data_remaining, con->file);
1942
1943 do
1944 {
1945 if (con->request)
1946 {
1947 /*
1948 * Grab any request data from the connection...
1949 */
1950
1951 if ((ipp_state = ippRead(&(con->http), con->request)) == IPP_ERROR)
1952 {
1953 cupsdLogMessage(CUPSD_LOG_ERROR,
1954 "cupsdReadClient: %d IPP Read Error!",
1955 con->http.fd);
1956
1957 cupsdSendError(con, HTTP_BAD_REQUEST, AUTH_NONE);
1958 cupsdCloseClient(con);
1959 return;
1960 }
1961 else if (ipp_state != IPP_DATA)
1962 {
1963 if (con->http.state == HTTP_POST_SEND)
1964 {
1965 cupsdSendError(con, HTTP_BAD_REQUEST, AUTH_NONE);
1966 cupsdCloseClient(con);
1967 return;
1968 }
1969
1970 break;
1971 }
1972 else
1973 con->bytes += ippLength(con->request);
1974 }
1975
1976 if (con->file < 0 && con->http.state != HTTP_POST_SEND)
1977 {
1978 /*
1979 * Create a file as needed for the request data...
1980 */
1981
1982 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot, request_id ++);
1983 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1984
1985 if (con->file < 0)
1986 {
1987 cupsdLogMessage(CUPSD_LOG_ERROR,
1988 "Unable to create request file %s: %s",
1989 con->filename, strerror(errno));
1990
1991 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, AUTH_NONE))
1992 {
1993 cupsdCloseClient(con);
1994 return;
1995 }
1996 }
1997
1998 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadClient: %d REQUEST %s=%d", con->http.fd,
1999 con->filename, con->file);
2000
2001 fchmod(con->file, 0640);
2002 fchown(con->file, RunUser, Group);
2003 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2004 }
2005
2006 if (con->http.state != HTTP_POST_SEND)
2007 {
2008 if ((bytes = httpRead2(HTTP(con), line, sizeof(line))) < 0)
2009 {
2010 cupsdCloseClient(con);
2011 return;
2012 }
2013 else if (bytes > 0)
2014 {
2015 con->bytes += bytes;
2016
2017 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2018 "cupsdReadClient: %d writing %d bytes to %d",
2019 con->http.fd, bytes, con->file);
2020
2021 if (write(con->file, line, bytes) < bytes)
2022 {
2023 cupsdLogMessage(CUPSD_LOG_ERROR,
2024 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2025 bytes, con->filename, strerror(errno));
2026
2027 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2028 "cupsdReadClient: Closing file %d...",
2029 con->file);
2030
2031 close(con->file);
2032 con->file = -1;
2033 unlink(con->filename);
2034 cupsdClearString(&con->filename);
2035
2036 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, AUTH_NONE))
2037 {
2038 cupsdCloseClient(con);
2039 return;
2040 }
2041 }
2042 }
2043 else if (con->http.state == HTTP_POST_RECV)
2044 return;
2045 else if (con->http.state != HTTP_POST_SEND)
2046 {
2047 cupsdCloseClient(con);
2048 return;
2049 }
2050 }
2051 }
2052 while (con->http.state == HTTP_POST_RECV && con->http.used > 0);
2053
2054 if (con->http.state == HTTP_POST_SEND)
2055 {
2056 if (con->file >= 0)
2057 {
2058 fstat(con->file, &filestats);
2059
2060 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2061 "cupsdReadClient: %d Closing data file %d, "
2062 "size=" CUPS_LLFMT ".",
2063 con->http.fd, con->file,
2064 CUPS_LLCAST filestats.st_size);
2065
2066 close(con->file);
2067 con->file = -1;
2068
2069 if (filestats.st_size > MaxRequestSize &&
2070 MaxRequestSize > 0)
2071 {
2072 /*
2073 * Request is too big; remove it and send an error...
2074 */
2075
2076 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2077 "cupsdReadClient: %d Removing temp file %s",
2078 con->http.fd, con->filename);
2079 unlink(con->filename);
2080 cupsdClearString(&con->filename);
2081
2082 if (con->request)
2083 {
2084 /*
2085 * Delete any IPP request data...
2086 */
2087
2088 ippDelete(con->request);
2089 con->request = NULL;
2090 }
2091
2092 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, AUTH_NONE))
2093 {
2094 cupsdCloseClient(con);
2095 return;
2096 }
2097 }
2098
2099 if (con->command)
2100 {
2101 if (!cupsdSendCommand(con, con->command, con->options, 0))
2102 {
2103 if (!cupsdSendError(con, HTTP_NOT_FOUND, AUTH_NONE))
2104 {
2105 cupsdCloseClient(con);
2106 return;
2107 }
2108 }
2109 else
2110 cupsdLogRequest(con, HTTP_OK);
2111 }
2112 }
2113
2114 if (con->request)
2115 {
2116 cupsdProcessIPPRequest(con);
2117
2118 if (con->filename)
2119 {
2120 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2121 "cupsdReadClient: %d Removing temp file %s",
2122 con->http.fd, con->filename);
2123 unlink(con->filename);
2124 cupsdClearString(&con->filename);
2125 }
2126
2127 return;
2128 }
2129 }
2130 break;
2131
2132 default :
2133 break; /* Anti-compiler-warning-code */
2134 }
2135
2136 if (!con->http.keep_alive && con->http.state == HTTP_WAITING)
2137 cupsdCloseClient(con);
2138 }
2139
2140
2141 /*
2142 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2143 */
2144
2145 int /* O - 1 on success, 0 on failure */
2146 cupsdSendCommand(
2147 cupsd_client_t *con, /* I - Client connection */
2148 char *command, /* I - Command to run */
2149 char *options, /* I - Command-line options */
2150 int root) /* I - Run as root? */
2151 {
2152 int fd; /* Standard input file descriptor */
2153
2154
2155 if (con->filename)
2156 {
2157 fd = open(con->filename, O_RDONLY);
2158
2159 if (fd < 0)
2160 {
2161 cupsdLogMessage(CUPSD_LOG_ERROR,
2162 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2163 con->http.fd, con->filename ? con->filename : "/dev/null",
2164 strerror(errno));
2165 return (0);
2166 }
2167
2168 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
2169 }
2170 else
2171 fd = -1;
2172
2173 con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
2174
2175 if (fd >= 0)
2176 close(fd);
2177
2178 cupsdLogMessage(CUPSD_LOG_INFO, "Started \"%s\" (pid=%d)", command,
2179 con->pipe_pid);
2180
2181 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendCommand: %d file=%d",
2182 con->http.fd, con->file);
2183
2184 if (con->pipe_pid == 0)
2185 return (0);
2186
2187 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2188
2189 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2190
2191 con->sent_header = 0;
2192 con->file_ready = 0;
2193 con->got_fields = 0;
2194 con->field_col = 0;
2195
2196 return (1);
2197 }
2198
2199
2200 /*
2201 * 'cupsdSendError()' - Send an error message via HTTP.
2202 */
2203
2204 int /* O - 1 if successful, 0 otherwise */
2205 cupsdSendError(cupsd_client_t *con, /* I - Connection */
2206 http_status_t code, /* I - Error code */
2207 int auth_type)/* I - Authentication type */
2208 {
2209 #ifdef HAVE_SSL
2210 /*
2211 * Force client to upgrade for authentication if that is how the
2212 * server is configured...
2213 */
2214
2215 if (code == HTTP_UNAUTHORIZED &&
2216 DefaultEncryption == HTTP_ENCRYPT_REQUIRED &&
2217 strcasecmp(con->http.hostname, "localhost") &&
2218 !con->http.tls)
2219 {
2220 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2221 "cupsdSendError: Encryption before authentication!");
2222 code = HTTP_UPGRADE_REQUIRED;
2223 }
2224 #endif /* HAVE_SSL */
2225
2226 /*
2227 * Put the request in the access_log file...
2228 */
2229
2230 cupsdLogRequest(con, code);
2231
2232 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendError: %d code=%d (%s)",
2233 con->http.fd, code, httpStatus(code));
2234
2235 /*
2236 * To work around bugs in some proxies, don't use Keep-Alive for some
2237 * error messages...
2238 *
2239 * Kerberos authentication doesn't work without Keep-Alive, so
2240 * never disable it in that case.
2241 */
2242
2243 if (code >= HTTP_BAD_REQUEST && con->http.auth_type != AUTH_NEGOTIATE)
2244 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
2245
2246 /*
2247 * Send an error message back to the client. If the error code is a
2248 * 400 or 500 series, make sure the message contains some text, too!
2249 */
2250
2251 if (!cupsdSendHeader(con, code, NULL, auth_type))
2252 return (0);
2253
2254 #ifdef HAVE_SSL
2255 if (code == HTTP_UPGRADE_REQUIRED)
2256 if (httpPrintf(HTTP(con), "Connection: Upgrade\r\n") < 0)
2257 return (0);
2258
2259 if (httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2260 return (0);
2261 #endif /* HAVE_SSL */
2262
2263 if (con->http.version >= HTTP_1_1 &&
2264 con->http.keep_alive == HTTP_KEEPALIVE_OFF)
2265 {
2266 if (httpPrintf(HTTP(con), "Connection: close\r\n") < 0)
2267 return (0);
2268 }
2269
2270 if (code >= HTTP_BAD_REQUEST)
2271 {
2272 /*
2273 * Send a human-readable error message.
2274 */
2275
2276 char message[4096], /* Message for user */
2277 urltext[1024], /* URL redirection text */
2278 redirect[1024]; /* Redirection link */
2279 const char *text; /* Status-specific text */
2280
2281
2282 redirect[0] = '\0';
2283
2284 if (code == HTTP_UNAUTHORIZED)
2285 text = _cupsLangString(con->language,
2286 _("Enter your username and password or the "
2287 "root username and password to access this "
2288 "page. If you are using Kerberos authentication, "
2289 "make sure you have a valid Kerberos ticket."));
2290 else if (code == HTTP_UPGRADE_REQUIRED)
2291 {
2292 text = urltext;
2293
2294 snprintf(urltext, sizeof(urltext),
2295 _cupsLangString(con->language,
2296 _("You must access this page using the URL "
2297 "<A HREF=\"https://%s:%d%s\">"
2298 "https://%s:%d%s</A>.")),
2299 con->servername, con->serverport, con->uri,
2300 con->servername, con->serverport, con->uri);
2301
2302 snprintf(redirect, sizeof(redirect),
2303 "<META HTTP-EQUIV=\"Refresh\" "
2304 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2305 con->servername, con->serverport, con->uri);
2306 }
2307 else
2308 text = "";
2309
2310 snprintf(message, sizeof(message),
2311 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2312 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2313 "<HTML>\n"
2314 "<HEAD>\n"
2315 "\t<META HTTP-EQUIV=\"Content-Type\" "
2316 "CONTENT=\"text/html; charset=utf-8\">\n"
2317 "\t<TITLE>%d %s</TITLE>\n"
2318 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2319 "HREF=\"/cups.css\">\n"
2320 "%s"
2321 "</HEAD>\n"
2322 "<BODY>\n"
2323 "<H1>%d %s</H1>\n"
2324 "<P>%s</P>\n"
2325 "</BODY>\n"
2326 "</HTML>\n",
2327 code, httpStatus(code), redirect, code, httpStatus(code), text);
2328
2329 if (httpPrintf(HTTP(con), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2330 return (0);
2331 if (httpPrintf(HTTP(con), "Content-Length: %d\r\n",
2332 (int)strlen(message)) < 0)
2333 return (0);
2334 if (httpPrintf(HTTP(con), "\r\n") < 0)
2335 return (0);
2336 if (httpPrintf(HTTP(con), "%s", message) < 0)
2337 return (0);
2338 }
2339 else if (httpPrintf(HTTP(con), "\r\n") < 0)
2340 return (0);
2341
2342 if (cupsdFlushHeader(con) < 0)
2343 return (0);
2344
2345 con->http.state = HTTP_WAITING;
2346
2347 return (1);
2348 }
2349
2350
2351 /*
2352 * 'cupsdSendHeader()' - Send an HTTP request.
2353 */
2354
2355 int /* O - 1 on success, 0 on failure */
2356 cupsdSendHeader(
2357 cupsd_client_t *con, /* I - Client to send to */
2358 http_status_t code, /* I - HTTP status code */
2359 char *type, /* I - MIME type of document */
2360 int auth_type) /* I - Type of authentication */
2361 {
2362 char auth_str[1024]; /* Authorization string */
2363
2364
2365 /*
2366 * Send the HTTP status header...
2367 */
2368
2369 if (code == HTTP_CONTINUE)
2370 {
2371 /*
2372 * 100-continue doesn't send any headers...
2373 */
2374
2375 return (httpPrintf(HTTP(con), "HTTP/%d.%d 100 Continue\r\n\r\n",
2376 con->http.version / 100, con->http.version % 100) > 0);
2377 }
2378
2379 httpFlushWrite(HTTP(con));
2380
2381 con->http.data_encoding = HTTP_ENCODE_FIELDS;
2382
2383 if (httpPrintf(HTTP(con), "HTTP/%d.%d %d %s\r\n", con->http.version / 100,
2384 con->http.version % 100, code, httpStatus(code)) < 0)
2385 return (0);
2386 if (httpPrintf(HTTP(con), "Date: %s\r\n", httpGetDateString(time(NULL))) < 0)
2387 return (0);
2388 if (ServerHeader)
2389 if (httpPrintf(HTTP(con), "Server: %s\r\n", ServerHeader) < 0)
2390 return (0);
2391 if (con->http.keep_alive && con->http.version >= HTTP_1_0)
2392 {
2393 if (httpPrintf(HTTP(con), "Connection: Keep-Alive\r\n") < 0)
2394 return (0);
2395 if (httpPrintf(HTTP(con), "Keep-Alive: timeout=%d\r\n",
2396 KeepAliveTimeout) < 0)
2397 return (0);
2398 }
2399 if (code == HTTP_METHOD_NOT_ALLOWED)
2400 if (httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2401 return (0);
2402
2403 if (code == HTTP_UNAUTHORIZED)
2404 {
2405 if (auth_type == AUTH_NONE)
2406 {
2407 if (!con->best || con->best->type <= AUTH_NONE)
2408 auth_type = DefaultAuthType;
2409 else
2410 auth_type = con->best->type;
2411 }
2412
2413 auth_str[0] = '\0';
2414
2415 if (auth_type == AUTH_BASIC || auth_type == AUTH_BASICDIGEST)
2416 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2417 else if (auth_type == AUTH_DIGEST)
2418 snprintf(auth_str, sizeof(auth_str), "Digest realm=\"CUPS\", nonce=\"%s\"",
2419 con->http.hostname);
2420 #ifdef HAVE_GSSAPI
2421 else if (auth_type == AUTH_NEGOTIATE && con->gss_output_token.length == 0)
2422 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2423 #endif /* HAVE_GSSAPI */
2424
2425 #ifdef HAVE_AUTHORIZATION_H
2426 if (con->best && auth_type != AUTH_NEGOTIATE)
2427 {
2428 int i; /* Looping var */
2429 char *auth_key; /* Auth key buffer */
2430 size_t auth_size; /* Size of remaining buffer */
2431
2432
2433 auth_key = auth_str + strlen(auth_str);
2434 auth_size = sizeof(auth_str) - (auth_key - auth_str);
2435
2436 for (i = 0; i < con->best->num_names; i ++)
2437 {
2438 if (!strncasecmp(con->best->names[i], "@AUTHKEY(", 9))
2439 {
2440 snprintf(auth_key, auth_size, ", authkey=\"%s\"",
2441 con->best->names[i] + 9);
2442 /* end parenthesis is stripped in conf.c */
2443 break;
2444 }
2445 else if (!strcasecmp(con->best->names[i], "@SYSTEM") &&
2446 SystemGroupAuthKey)
2447 {
2448 snprintf(auth_key, auth_size, ", authkey=\"%s\"", SystemGroupAuthKey);
2449 break;
2450 }
2451 }
2452 }
2453 #endif /* HAVE_AUTHORIZATION_H */
2454
2455 if (auth_str[0])
2456 {
2457 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendHeader: WWW-Authenticate: %s",
2458 auth_str);
2459
2460 if (httpPrintf(HTTP(con), "WWW-Authenticate: %s\r\n", auth_str) < 0)
2461 return (0);
2462 }
2463 }
2464
2465 #ifdef HAVE_GSSAPI
2466 /*
2467 * WWW-Authenticate: Negotiate can be included even for
2468 * non-401 replies...
2469 */
2470
2471 if (con->gss_output_token.length > 0)
2472 {
2473 char buf[2048]; /* Output token buffer */
2474 OM_uint32 minor_status; /* Minor status code */
2475
2476
2477 httpEncode64_2(buf, sizeof(buf),
2478 con->gss_output_token.value,
2479 con->gss_output_token.length);
2480 gss_release_buffer(&minor_status, &con->gss_output_token);
2481
2482 cupsdLogMessage(CUPSD_LOG_DEBUG,
2483 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", buf);
2484
2485 if (httpPrintf(HTTP(con), "WWW-Authenticate: Negotiate %s\r\n", buf) < 0)
2486 return (0);
2487 }
2488 #endif /* HAVE_GSSAPI */
2489
2490 if (con->language && strcmp(con->language->language, "C"))
2491 {
2492 if (httpPrintf(HTTP(con), "Content-Language: %s\r\n",
2493 con->language->language) < 0)
2494 return (0);
2495 }
2496
2497 if (type)
2498 {
2499 if (!strcmp(type, "text/html"))
2500 {
2501 if (httpPrintf(HTTP(con),
2502 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2503 return (0);
2504 }
2505 else if (httpPrintf(HTTP(con), "Content-Type: %s\r\n", type) < 0)
2506 return (0);
2507 }
2508
2509 return (1);
2510 }
2511
2512
2513 /*
2514 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2515 */
2516
2517 void
2518 cupsdUpdateCGI(void)
2519 {
2520 char *ptr, /* Pointer to end of line in buffer */
2521 message[1024]; /* Pointer to message text */
2522 int loglevel; /* Log level for message */
2523
2524
2525 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2526 message, sizeof(message))) != NULL)
2527 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2528 break;
2529
2530 if (ptr == NULL && !CGIStatusBuffer->bufused)
2531 {
2532 /*
2533 * Fatal error on pipe - should never happen!
2534 */
2535
2536 cupsdLogMessage(CUPSD_LOG_CRIT,
2537 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2538 strerror(errno));
2539 }
2540 }
2541
2542
2543 /*
2544 * 'cupsdWriteClient()' - Write data to a client as needed.
2545 */
2546
2547 void
2548 cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2549 {
2550 int bytes; /* Number of bytes written */
2551 char buf[16385]; /* Data buffer */
2552 char *bufptr; /* Pointer into buffer */
2553 ipp_state_t ipp_state; /* IPP state value */
2554
2555
2556 #ifdef DEBUG
2557 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2558 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2559 "pipe_pid=%d state=%d",
2560 con, con->http.fd, con->response, con->response->state,
2561 con->file, con->pipe_pid, con->http.state);
2562 #endif /* DEBUG */
2563
2564 if (con->http.state != HTTP_GET_SEND &&
2565 con->http.state != HTTP_POST_SEND)
2566 return;
2567
2568 if (con->pipe_pid)
2569 {
2570 /*
2571 * Make sure we select on the CGI output...
2572 */
2573
2574 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2575
2576 if (!con->file_ready)
2577 {
2578 /*
2579 * Try again later when there is CGI output available...
2580 */
2581
2582 cupsdRemoveSelect(con->http.fd);
2583 return;
2584 }
2585
2586 con->file_ready = 0;
2587 }
2588
2589 if (con->response && con->response->state != IPP_DATA)
2590 {
2591 ipp_state = ippWrite(HTTP(con), con->response);
2592 bytes = ipp_state != IPP_ERROR &&
2593 (con->file >= 0 || ipp_state != IPP_DATA);
2594 }
2595 else if ((bytes = read(con->file, buf, sizeof(buf) - 1)) > 0)
2596 {
2597 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2598 "cupsdWriteClient: Read %d bytes from file %d...",
2599 bytes, con->file);
2600
2601 if (con->pipe_pid && !con->got_fields)
2602 {
2603 /*
2604 * Inspect the data for Content-Type and other fields.
2605 */
2606
2607 buf[bytes] = '\0';
2608
2609 for (bufptr = buf; !con->got_fields && *bufptr; bufptr ++)
2610 if (*bufptr == '\n')
2611 {
2612 /*
2613 * Send line to client...
2614 */
2615
2616 if (bufptr > buf && bufptr[-1] == '\r')
2617 bufptr[-1] = '\0';
2618 *bufptr++ = '\0';
2619
2620 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Script header: %s", buf);
2621
2622 if (!con->sent_header)
2623 {
2624 /*
2625 * Handle redirection and CGI status codes...
2626 */
2627
2628 if (!strncasecmp(buf, "Location:", 9))
2629 {
2630 cupsdSendHeader(con, HTTP_SEE_OTHER, NULL, AUTH_NONE);
2631 con->sent_header = 2;
2632
2633 if (httpPrintf(HTTP(con), "Content-Length: 0\r\n") < 0)
2634 return;
2635 }
2636 else if (!strncasecmp(buf, "Status:", 7))
2637 {
2638 cupsdSendError(con, (http_status_t)atoi(buf + 7), AUTH_NONE);
2639 con->sent_header = 2;
2640 }
2641 else
2642 {
2643 cupsdSendHeader(con, HTTP_OK, NULL, AUTH_NONE);
2644 con->sent_header = 1;
2645
2646 if (con->http.version == HTTP_1_1)
2647 {
2648 if (httpPrintf(HTTP(con), "Transfer-Encoding: chunked\r\n") < 0)
2649 return;
2650 }
2651 }
2652 }
2653
2654 if (strncasecmp(buf, "Status:", 7))
2655 httpPrintf(HTTP(con), "%s\r\n", buf);
2656
2657 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d %s",
2658 con->http.fd, buf);
2659
2660 /*
2661 * Update buffer...
2662 */
2663
2664 bytes -= (bufptr - buf);
2665 memmove(buf, bufptr, bytes + 1);
2666 bufptr = buf - 1;
2667
2668 /*
2669 * See if the line was empty...
2670 */
2671
2672 if (con->field_col == 0)
2673 {
2674 con->got_fields = 1;
2675
2676 if (cupsdFlushHeader(con) < 0)
2677 {
2678 cupsdCloseClient(con);
2679 return;
2680 }
2681
2682 if (con->http.version == HTTP_1_1)
2683 con->http.data_encoding = HTTP_ENCODE_CHUNKED;
2684 }
2685 else
2686 con->field_col = 0;
2687 }
2688 else if (*bufptr != '\r')
2689 con->field_col ++;
2690
2691 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2692 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2693 con->http.fd, bytes, con->got_fields);
2694
2695 if (bytes > 0 && !con->got_fields)
2696 {
2697 /*
2698 * Remaining text needs to go out...
2699 */
2700
2701 httpPrintf(HTTP(con), "%s", buf);
2702
2703 con->http.activity = time(NULL);
2704 return;
2705 }
2706 else if (bytes == 0)
2707 con->http.activity = time(NULL);
2708 }
2709
2710 if (bytes > 0)
2711 {
2712 if (httpWrite2(HTTP(con), buf, bytes) < 0)
2713 {
2714 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2715 "cupsdWriteClient: %d Write of %d bytes failed!",
2716 con->http.fd, bytes);
2717
2718 cupsdCloseClient(con);
2719 return;
2720 }
2721
2722 con->bytes += bytes;
2723
2724 if (con->http.state == HTTP_WAITING)
2725 bytes = 0;
2726 }
2727 }
2728
2729 if (bytes <= 0)
2730 {
2731 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d bytes < 0",
2732 con->http.fd);
2733
2734 cupsdLogRequest(con, HTTP_OK);
2735
2736 httpFlushWrite(HTTP(con));
2737
2738 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED && con->sent_header == 1)
2739 {
2740 if (httpWrite2(HTTP(con), "", 0) < 0)
2741 {
2742 cupsdCloseClient(con);
2743 return;
2744 }
2745 }
2746
2747 con->http.state = HTTP_WAITING;
2748
2749 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
2750
2751 if (con->file >= 0)
2752 {
2753 cupsdRemoveSelect(con->file);
2754
2755 if (con->pipe_pid)
2756 cupsdEndProcess(con->pipe_pid, 0);
2757
2758 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2759 "cupsdWriteClient: %d Closing data file %d.",
2760 con->http.fd, con->file);
2761
2762 close(con->file);
2763 con->file = -1;
2764 con->pipe_pid = 0;
2765 }
2766
2767 if (con->filename)
2768 {
2769 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2770 "cupsdWriteClient: %d Removing temp file %s",
2771 con->http.fd, con->filename);
2772 unlink(con->filename);
2773 cupsdClearString(&con->filename);
2774 }
2775
2776 if (con->request)
2777 {
2778 ippDelete(con->request);
2779 con->request = NULL;
2780 }
2781
2782 if (con->response)
2783 {
2784 ippDelete(con->response);
2785 con->response = NULL;
2786 }
2787
2788 cupsdClearString(&con->command);
2789 cupsdClearString(&con->options);
2790 cupsdClearString(&con->query_string);
2791
2792 if (!con->http.keep_alive)
2793 {
2794 cupsdCloseClient(con);
2795 return;
2796 }
2797 }
2798
2799 con->http.activity = time(NULL);
2800 }
2801
2802
2803 /*
2804 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2805 */
2806
2807 static int /* O - 1 if modified since */
2808 check_if_modified(
2809 cupsd_client_t *con, /* I - Client connection */
2810 struct stat *filestats) /* I - File information */
2811 {
2812 char *ptr; /* Pointer into field */
2813 time_t date; /* Time/date value */
2814 off_t size; /* Size/length value */
2815
2816
2817 size = 0;
2818 date = 0;
2819 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
2820
2821 if (*ptr == '\0')
2822 return (1);
2823
2824 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2825 "check_if_modified: %d If-Modified-Since=\"%s\"",
2826 con->http.fd, ptr);
2827
2828 while (*ptr != '\0')
2829 {
2830 while (isspace(*ptr) || *ptr == ';')
2831 ptr ++;
2832
2833 if (strncasecmp(ptr, "length=", 7) == 0)
2834 {
2835 ptr += 7;
2836 size = strtoll(ptr, NULL, 10);
2837
2838 while (isdigit(*ptr))
2839 ptr ++;
2840 }
2841 else if (isalpha(*ptr))
2842 {
2843 date = httpGetDateTime(ptr);
2844 while (*ptr != '\0' && *ptr != ';')
2845 ptr ++;
2846 }
2847 else
2848 ptr ++;
2849 }
2850
2851 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2852 "check_if_modified: %d sizes=" CUPS_LLFMT ","
2853 CUPS_LLFMT " dates=%d,%d",
2854 con->http.fd, CUPS_LLCAST size,
2855 CUPS_LLCAST filestats->st_size, (int)date,
2856 (int)filestats->st_mtime);
2857
2858 return ((size != filestats->st_size && size != 0) ||
2859 (date < filestats->st_mtime && date != 0) ||
2860 (size == 0 && date == 0));
2861 }
2862
2863
2864 #ifdef HAVE_SSL
2865 /*
2866 * 'encrypt_client()' - Enable encryption for the client...
2867 */
2868
2869 static int /* O - 1 on success, 0 on error */
2870 encrypt_client(cupsd_client_t *con) /* I - Client to encrypt */
2871 {
2872 # ifdef HAVE_LIBSSL
2873 SSL_CTX *context; /* Context for encryption */
2874 SSL *conn; /* Connection for encryption */
2875 BIO *bio; /* BIO data */
2876 unsigned long error; /* Error code */
2877
2878
2879 /*
2880 * Verify that we have a certificate...
2881 */
2882
2883 if (access(ServerKey, 0) || access(ServerCertificate, 0))
2884 {
2885 /*
2886 * Nope, make a self-signed certificate...
2887 */
2888
2889 if (!make_certificate(con))
2890 return (0);
2891 }
2892
2893 /*
2894 * Create the SSL context and accept the connection...
2895 */
2896
2897 context = SSL_CTX_new(SSLv23_server_method());
2898
2899 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
2900 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
2901 SSL_CTX_use_certificate_file(context, ServerCertificate, SSL_FILETYPE_PEM);
2902
2903 bio = BIO_new(_httpBIOMethods());
2904 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)HTTP(con));
2905
2906 conn = SSL_new(context);
2907 SSL_set_bio(conn, bio, bio);
2908
2909 if (SSL_accept(conn) != 1)
2910 {
2911 cupsdLogMessage(CUPSD_LOG_ERROR,
2912 "encrypt_client: Unable to encrypt connection from %s!",
2913 con->http.hostname);
2914
2915 while ((error = ERR_get_error()) != 0)
2916 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
2917 ERR_error_string(error, NULL));
2918
2919 SSL_CTX_free(context);
2920 SSL_free(conn);
2921 return (0);
2922 }
2923
2924 cupsdLogMessage(CUPSD_LOG_DEBUG,
2925 "encrypt_client: %d Connection from %s now encrypted.",
2926 con->http.fd, con->http.hostname);
2927
2928 con->http.tls = conn;
2929 return (1);
2930
2931 # elif defined(HAVE_GNUTLS)
2932 http_tls_t *conn; /* TLS session object */
2933 int error; /* Error code */
2934 gnutls_certificate_server_credentials *credentials;
2935 /* TLS credentials */
2936
2937
2938 /*
2939 * Verify that we have a certificate...
2940 */
2941
2942 if (access(ServerKey, 0) || access(ServerCertificate, 0))
2943 {
2944 /*
2945 * Nope, make a self-signed certificate...
2946 */
2947
2948 if (!make_certificate(con))
2949 return (0);
2950 }
2951
2952 /*
2953 * Create the SSL object and perform the SSL handshake...
2954 */
2955
2956 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
2957
2958 if (conn == NULL)
2959 return (0);
2960
2961 credentials = (gnutls_certificate_server_credentials *)
2962 malloc(sizeof(gnutls_certificate_server_credentials));
2963 if (credentials == NULL)
2964 {
2965 cupsdLogMessage(CUPSD_LOG_ERROR,
2966 "encrypt_client: Unable to encrypt connection from %s!",
2967 con->http.hostname);
2968 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s", strerror(errno));
2969
2970 free(conn);
2971 return (0);
2972 }
2973
2974 gnutls_certificate_allocate_credentials(credentials);
2975 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
2976 ServerKey, GNUTLS_X509_FMT_PEM);
2977
2978 gnutls_init(&(conn->session), GNUTLS_SERVER);
2979 gnutls_set_default_priority(conn->session);
2980 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
2981 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)HTTP(con));
2982 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
2983 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
2984
2985 error = gnutls_handshake(conn->session);
2986
2987 if (error != GNUTLS_E_SUCCESS)
2988 {
2989 cupsdLogMessage(CUPSD_LOG_ERROR,
2990 "encrypt_client: Unable to encrypt connection from %s!",
2991 con->http.hostname);
2992 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
2993 gnutls_strerror(error));
2994
2995 gnutls_deinit(conn->session);
2996 gnutls_certificate_free_credentials(*credentials);
2997 free(conn);
2998 free(credentials);
2999 return (0);
3000 }
3001
3002 cupsdLogMessage(CUPSD_LOG_DEBUG,
3003 "encrypt_client: %d Connection from %s now encrypted.",
3004 con->http.fd, con->http.hostname);
3005
3006 conn->credentials = credentials;
3007 con->http.tls = conn;
3008 return (1);
3009
3010 # elif defined(HAVE_CDSASSL)
3011 OSStatus error; /* Error code */
3012 http_tls_t *conn; /* CDSA connection information */
3013
3014
3015 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
3016 return (0);
3017
3018 error = 0;
3019 conn->session = NULL;
3020 conn->certsArray = get_cdsa_certificate(con);
3021
3022 if (!conn->certsArray)
3023 {
3024 /*
3025 * No keychain (yet), make a self-signed certificate...
3026 */
3027
3028 if (make_certificate(con))
3029 conn->certsArray = get_cdsa_certificate(con);
3030 }
3031
3032 if (!conn->certsArray)
3033 {
3034 cupsdLogMessage(CUPSD_LOG_ERROR,
3035 "encrypt_client: Could not find signing key in keychain "
3036 "\"%s\"", ServerCertificate);
3037 error = errSSLBadCert; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3038 }
3039
3040 if (!error)
3041 error = SSLNewContext(true, &conn->session);
3042
3043 if (!error)
3044 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
3045
3046 if (!error)
3047 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
3048
3049 if (!error)
3050 error = SSLSetConnection(conn->session, HTTP(con));
3051
3052 if (!error)
3053 error = SSLSetAllowsExpiredCerts(conn->session, true);
3054
3055 if (!error)
3056 error = SSLSetAllowsAnyRoot(conn->session, true);
3057
3058 if (!error)
3059 error = SSLSetCertificate(conn->session, conn->certsArray);
3060
3061 if (!error)
3062 {
3063 /*
3064 * Perform SSL/TLS handshake
3065 */
3066
3067 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
3068 usleep(1000);
3069 }
3070
3071 if (error)
3072 {
3073 cupsdLogMessage(CUPSD_LOG_ERROR,
3074 "encrypt_client: Unable to encrypt connection from %s!",
3075 con->http.hostname);
3076
3077 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s (%d)",
3078 cssmErrorString(error), (int)error);
3079
3080 con->http.error = error;
3081 con->http.status = HTTP_ERROR;
3082
3083 if (conn->session)
3084 SSLDisposeContext(conn->session);
3085
3086 if (conn->certsArray)
3087 CFRelease(conn->certsArray);
3088
3089 free(conn);
3090
3091 return (0);
3092 }
3093
3094 cupsdLogMessage(CUPSD_LOG_DEBUG,
3095 "encrypt_client: %d Connection from %s now encrypted.",
3096 con->http.fd, con->http.hostname);
3097
3098 con->http.tls = conn;
3099 return (1);
3100
3101 # endif /* HAVE_LIBSSL */
3102 }
3103 #endif /* HAVE_SSL */
3104
3105
3106 #ifdef HAVE_CDSASSL
3107 /*
3108 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3109 */
3110
3111 static CFArrayRef /* O - Array of certificates */
3112 get_cdsa_certificate(cupsd_client_t *con) /* I - Client connection */
3113 {
3114 OSStatus err; /* Error info */
3115 SecKeychainRef keychain; /* Keychain reference */
3116 SecIdentitySearchRef search; /* Search reference */
3117 SecIdentityRef identity; /* Identity */
3118 CFArrayRef certificates = NULL;
3119 /* Certificate array */
3120
3121
3122 if ((err = SecKeychainOpen(ServerCertificate, &keychain)))
3123 {
3124 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\", %s",
3125 ServerCertificate, cssmErrorString(err));
3126 return (NULL);
3127 }
3128
3129 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3130 /*
3131 * Use a policy to search for valid certificates who's common name matches the
3132 * servername...
3133 */
3134
3135 SecPolicySearchRef policy_search; /* Policy search ref */
3136 SecPolicyRef policy; /* Policy ref */
3137 CSSM_DATA options; /* Policy options */
3138 CSSM_APPLE_TP_SSL_OPTIONS
3139 ssl_options; /* SSL Option for hostname */
3140
3141
3142 if ((err = SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL,
3143 NULL, &policy_search)))
3144 {
3145 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create a policy search reference");
3146 CFRelease(keychain);
3147 return (NULL);
3148 }
3149
3150 if ((err = SecPolicySearchCopyNext(policy_search, &policy)))
3151 {
3152 cupsdLogMessage(CUPSD_LOG_ERROR,
3153 "Cannot find a policy to use for searching");
3154 CFRelease(keychain);
3155 CFRelease(policy_search);
3156 return (NULL);
3157 }
3158
3159 memset(&ssl_options, 0, sizeof(ssl_options));
3160 ssl_options.Version = CSSM_APPLE_TP_SSL_OPTS_VERSION;
3161 ssl_options.ServerName = con->servername;
3162 ssl_options.ServerNameLen = strlen(con->servername);
3163
3164 options.Data = (uint8 *)&ssl_options;
3165 options.Length = sizeof(ssl_options);
3166
3167 if ((err = SecPolicySetValue(policy, &options)))
3168 {
3169 cupsdLogMessage(CUPSD_LOG_ERROR,
3170 "Cannot set policy value to use for searching");
3171 CFRelease(keychain);
3172 CFRelease(policy_search);
3173 return (NULL);
3174 }
3175
3176 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3177 keychain, FALSE, &search);
3178 # else
3179 /*
3180 * Assume there is exactly one SecIdentity in the keychain...
3181 */
3182
3183 err = SecIdentitySearchCreate(keychain, CSSM_KEYUSE_SIGN, &search);
3184 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3185
3186 if (err)
3187 cupsdLogMessage(CUPSD_LOG_DEBUG,
3188 "Cannot create keychain search reference: %s",
3189 cssmErrorString(err));
3190 else
3191 {
3192 if ((err = SecIdentitySearchCopyNext(search, &identity)))
3193 {
3194 cupsdLogMessage(CUPSD_LOG_DEBUG,
3195 "Cannot find signing key in keychain \"%s\", error %d",
3196 ServerCertificate, (int)err);
3197 }
3198 else
3199 {
3200 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3201 cupsdLogMessage(CUPSD_LOG_ERROR,
3202 "SecIdentitySearchCopyNext CFTypeID failure!");
3203 else
3204 {
3205 if ((certificates = CFArrayCreate(NULL, (const void **)&identity,
3206 1, &kCFTypeArrayCallBacks)) == NULL)
3207 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create certificate array");
3208 }
3209
3210 CFRelease(identity);
3211 }
3212
3213 CFRelease(search);
3214 }
3215
3216 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3217 CFRelease(policy);
3218 CFRelease(policy_search);
3219 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3220
3221 return (certificates);
3222 }
3223 #endif /* HAVE_CDSASSL */
3224
3225
3226 /*
3227 * 'get_file()' - Get a filename and state info.
3228 */
3229
3230 static char * /* O - Real filename */
3231 get_file(cupsd_client_t *con, /* I - Client connection */
3232 struct stat *filestats, /* O - File information */
3233 char *filename, /* IO - Filename buffer */
3234 int len) /* I - Buffer length */
3235 {
3236 int status; /* Status of filesystem calls */
3237 char *ptr; /* Pointer info filename */
3238 int plen; /* Remaining length after pointer */
3239 char language[7]; /* Language subdirectory, if any */
3240
3241
3242 /*
3243 * Figure out the real filename...
3244 */
3245
3246 language[0] = '\0';
3247
3248 if (!strncmp(con->uri, "/ppd/", 5))
3249 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
3250 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3251 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
3252 else if (!strncmp(con->uri, "/admin/conf/", 12))
3253 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3254 else if (!strncmp(con->uri, "/admin/log/", 11))
3255 {
3256 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
3257 strlcpy(filename, AccessLog, len);
3258 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
3259 strlcpy(filename, ErrorLog, len);
3260 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
3261 strlcpy(filename, PageLog, len);
3262 else
3263 return (NULL);
3264 }
3265 else if (con->language)
3266 {
3267 snprintf(language, sizeof(language), "/%s", con->language->language);
3268 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3269 }
3270 else
3271 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3272
3273 if ((ptr = strchr(filename, '?')) != NULL)
3274 *ptr = '\0';
3275
3276 /*
3277 * Grab the status for this language; if there isn't a language-specific file
3278 * then fallback to the default one...
3279 */
3280
3281 if ((status = stat(filename, filestats)) != 0 && language[0] &&
3282 strncmp(con->uri, "/ppd/", 5) &&
3283 strncmp(con->uri, "/admin/conf/", 12) &&
3284 strncmp(con->uri, "/admin/log/", 11))
3285 {
3286 /*
3287 * Drop the country code...
3288 */
3289
3290 language[3] = '\0';
3291 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3292
3293 if ((ptr = strchr(filename, '?')) != NULL)
3294 *ptr = '\0';
3295
3296 if ((status = stat(filename, filestats)) != 0)
3297 {
3298 /*
3299 * Drop the language prefix and try the root directory...
3300 */
3301
3302 language[0] = '\0';
3303 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3304
3305 if ((ptr = strchr(filename, '?')) != NULL)
3306 *ptr = '\0';
3307
3308 status = stat(filename, filestats);
3309 }
3310 }
3311
3312 /*
3313 * If we're found a directory, get the index.html file instead...
3314 */
3315
3316 if (!status && S_ISDIR(filestats->st_mode))
3317 {
3318 /*
3319 * Make sure the URI ends with a slash...
3320 */
3321
3322 if (con->uri[strlen(con->uri) - 1] != '/')
3323 strlcat(con->uri, "/", sizeof(con->uri));
3324
3325 /*
3326 * Find the directory index file, trying every language...
3327 */
3328
3329 do
3330 {
3331 if (status && language[0])
3332 {
3333 /*
3334 * Try a different language subset...
3335 */
3336
3337 if (language[3])
3338 language[0] = '\0'; /* Strip country code */
3339 else
3340 language[0] = '\0'; /* Strip language */
3341 }
3342
3343 /*
3344 * Look for the index file...
3345 */
3346
3347 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3348
3349 if ((ptr = strchr(filename, '?')) != NULL)
3350 *ptr = '\0';
3351
3352 ptr = filename + strlen(filename);
3353 plen = len - (ptr - filename);
3354
3355 strlcpy(ptr, "index.html", plen);
3356 status = stat(filename, filestats);
3357
3358 #ifdef HAVE_JAVA
3359 if (status)
3360 {
3361 strlcpy(ptr, "index.class", plen);
3362 status = stat(filename, filestats);
3363 }
3364 #endif /* HAVE_JAVA */
3365
3366 #ifdef HAVE_PERL
3367 if (status)
3368 {
3369 strlcpy(ptr, "index.pl", plen);
3370 status = stat(filename, filestats);
3371 }
3372 #endif /* HAVE_PERL */
3373
3374 #ifdef HAVE_PHP
3375 if (status)
3376 {
3377 strlcpy(ptr, "index.php", plen);
3378 status = stat(filename, filestats);
3379 }
3380 #endif /* HAVE_PHP */
3381
3382 #ifdef HAVE_PYTHON
3383 if (status)
3384 {
3385 strlcpy(ptr, "index.pyc", plen);
3386 status = stat(filename, filestats);
3387 }
3388
3389 if (status)
3390 {
3391 strlcpy(ptr, "index.py", plen);
3392 status = stat(filename, filestats);
3393 }
3394 #endif /* HAVE_PYTHON */
3395
3396 }
3397 while (status && language[0]);
3398 }
3399
3400 cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_file: %d filename=%s size=%d",
3401 con->http.fd, filename,
3402 status ? -1 : (int)filestats->st_size);
3403
3404 if (!status)
3405 con->http.data_remaining = (int)filestats->st_size;
3406
3407 if (status)
3408 return (NULL);
3409 else
3410 return (filename);
3411 }
3412
3413
3414 /*
3415 * 'install_conf_file()' - Install a configuration file.
3416 */
3417
3418 static http_status_t /* O - Status */
3419 install_conf_file(cupsd_client_t *con) /* I - Connection */
3420 {
3421 cups_file_t *in, /* Input file */
3422 *out; /* Output file */
3423 char buffer[1024]; /* Copy buffer */
3424 int bytes; /* Number of bytes */
3425 char conffile[1024], /* Configuration filename */
3426 newfile[1024], /* New config filename */
3427 oldfile[1024]; /* Old config filename */
3428 struct stat confinfo; /* Config file info */
3429
3430
3431 /*
3432 * First construct the filenames...
3433 */
3434
3435 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3436 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3437 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3438
3439 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3440
3441 /*
3442 * Get the owner, group, and permissions of the configuration file.
3443 * If it doesn't exist, assign it to the User and Group in the
3444 * cupsd.conf file with mode 0640 permissions.
3445 */
3446
3447 if (stat(conffile, &confinfo))
3448 {
3449 confinfo.st_uid = User;
3450 confinfo.st_gid = Group;
3451 confinfo.st_mode = ConfigFilePerm;
3452 }
3453
3454 /*
3455 * Open the request file and new config file...
3456 */
3457
3458 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3459 {
3460 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3461 con->filename, strerror(errno));
3462 return (HTTP_SERVER_ERROR);
3463 }
3464
3465 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3466 {
3467 cupsFileClose(in);
3468 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3469 newfile, strerror(errno));
3470 return (HTTP_SERVER_ERROR);
3471 }
3472
3473 fchmod(cupsFileNumber(out), confinfo.st_mode);
3474 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3475
3476 /*
3477 * Copy from the request to the new config file...
3478 */
3479
3480 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3481 if (cupsFileWrite(out, buffer, bytes) < bytes)
3482 {
3483 cupsdLogMessage(CUPSD_LOG_ERROR,
3484 "Unable to copy to config file \"%s\" - %s",
3485 newfile, strerror(errno));
3486
3487 cupsFileClose(in);
3488 cupsFileClose(out);
3489 unlink(newfile);
3490
3491 return (HTTP_SERVER_ERROR);
3492 }
3493
3494 /*
3495 * Close the files...
3496 */
3497
3498 cupsFileClose(in);
3499 if (cupsFileClose(out))
3500 {
3501 cupsdLogMessage(CUPSD_LOG_ERROR,
3502 "Error file closing config file \"%s\" - %s",
3503 newfile, strerror(errno));
3504
3505 unlink(newfile);
3506
3507 return (HTTP_SERVER_ERROR);
3508 }
3509
3510 /*
3511 * Remove the request file...
3512 */
3513
3514 unlink(con->filename);
3515 cupsdClearString(&con->filename);
3516
3517 /*
3518 * Unlink the old backup, rename the current config file to the backup
3519 * filename, and rename the new config file to the config file name...
3520 */
3521
3522 if (unlink(oldfile))
3523 if (errno != ENOENT)
3524 {
3525 cupsdLogMessage(CUPSD_LOG_ERROR,
3526 "Unable to remove backup config file \"%s\" - %s",
3527 oldfile, strerror(errno));
3528
3529 unlink(newfile);
3530
3531 return (HTTP_SERVER_ERROR);
3532 }
3533
3534 if (rename(conffile, oldfile))
3535 if (errno != ENOENT)
3536 {
3537 cupsdLogMessage(CUPSD_LOG_ERROR,
3538 "Unable to rename old config file \"%s\" - %s",
3539 conffile, strerror(errno));
3540
3541 unlink(newfile);
3542
3543 return (HTTP_SERVER_ERROR);
3544 }
3545
3546 if (rename(newfile, conffile))
3547 {
3548 cupsdLogMessage(CUPSD_LOG_ERROR,
3549 "Unable to rename new config file \"%s\" - %s",
3550 newfile, strerror(errno));
3551
3552 rename(oldfile, conffile);
3553 unlink(newfile);
3554
3555 return (HTTP_SERVER_ERROR);
3556 }
3557
3558 /*
3559 * If the cupsd.conf file was updated, set the NeedReload flag...
3560 */
3561
3562 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3563 NeedReload = RELOAD_CUPSD;
3564 else
3565 NeedReload = RELOAD_ALL;
3566
3567 ReloadTime = time(NULL);
3568
3569 /*
3570 * Return that the file was created successfully...
3571 */
3572
3573 return (HTTP_CREATED);
3574 }
3575
3576
3577 /*
3578 * 'is_cgi()' - Is the resource a CGI script/program?
3579 */
3580
3581 static int /* O - 1 = CGI, 0 = file */
3582 is_cgi(cupsd_client_t *con, /* I - Client connection */
3583 const char *filename, /* I - Real filename */
3584 struct stat *filestats, /* I - File information */
3585 mime_type_t *type) /* I - MIME type */
3586 {
3587 const char *options; /* Options on URL */
3588
3589
3590 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3591 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3592 con, filename, filestats, type ? type->super : "unknown",
3593 type ? type->type : "unknown");
3594
3595 /*
3596 * Get the options, if any...
3597 */
3598
3599 if ((options = strchr(con->uri, '?')) != NULL)
3600 {
3601 options ++;
3602
3603 if (strchr(options, '='))
3604 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3605 }
3606
3607 /*
3608 * Check for known types...
3609 */
3610
3611 if (!type || strcasecmp(type->super, "application"))
3612 {
3613 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3614 return (0);
3615 }
3616
3617 if (!strcasecmp(type->type, "x-httpd-cgi") &&
3618 (filestats->st_mode & 0111))
3619 {
3620 /*
3621 * "application/x-httpd-cgi" is a CGI script.
3622 */
3623
3624 cupsdSetString(&con->command, filename);
3625
3626 filename = strrchr(filename, '/') + 1; /* Filename always absolute */
3627
3628 cupsdSetString(&con->options, options);
3629
3630 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3631 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3632 con->command, con->options);
3633
3634 return (1);
3635 }
3636 #ifdef HAVE_JAVA
3637 else if (!strcasecmp(type->type, "x-httpd-java"))
3638 {
3639 /*
3640 * "application/x-httpd-java" is a Java servlet.
3641 */
3642
3643 cupsdSetString(&con->command, CUPS_JAVA);
3644
3645 if (options)
3646 cupsdSetStringf(&con->options, " %s %s", filename, options);
3647 else
3648 cupsdSetStringf(&con->options, " %s", filename);
3649
3650 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3651 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3652 con->command, con->options);
3653
3654 return (1);
3655 }
3656 #endif /* HAVE_JAVA */
3657 #ifdef HAVE_PERL
3658 else if (!strcasecmp(type->type, "x-httpd-perl"))
3659 {
3660 /*
3661 * "application/x-httpd-perl" is a Perl page.
3662 */
3663
3664 cupsdSetString(&con->command, CUPS_PERL);
3665
3666 if (options)
3667 cupsdSetStringf(&con->options, " %s %s", filename, options);
3668 else
3669 cupsdSetStringf(&con->options, " %s", filename);
3670
3671 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3672 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3673 con->command, con->options);
3674
3675 return (1);
3676 }
3677 #endif /* HAVE_PERL */
3678 #ifdef HAVE_PHP
3679 else if (!strcasecmp(type->type, "x-httpd-php"))
3680 {
3681 /*
3682 * "application/x-httpd-php" is a PHP page.
3683 */
3684
3685 cupsdSetString(&con->command, CUPS_PHP);
3686
3687 if (options)
3688 cupsdSetStringf(&con->options, " %s %s", filename, options);
3689 else
3690 cupsdSetStringf(&con->options, " %s", filename);
3691
3692 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3693 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3694 con->command, con->options);
3695
3696 return (1);
3697 }
3698 #endif /* HAVE_PHP */
3699 #ifdef HAVE_PYTHON
3700 else if (!strcasecmp(type->type, "x-httpd-python"))
3701 {
3702 /*
3703 * "application/x-httpd-python" is a Python page.
3704 */
3705
3706 cupsdSetString(&con->command, CUPS_PYTHON);
3707
3708 if (options)
3709 cupsdSetStringf(&con->options, " %s %s", filename, options);
3710 else
3711 cupsdSetStringf(&con->options, " %s", filename);
3712
3713 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3714 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3715 con->command, con->options);
3716
3717 return (1);
3718 }
3719 #endif /* HAVE_PYTHON */
3720
3721 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3722
3723 return (0);
3724 }
3725
3726
3727 /*
3728 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3729 */
3730
3731 static int /* O - 0 if relative, 1 if absolute */
3732 is_path_absolute(const char *path) /* I - Input path */
3733 {
3734 /*
3735 * Check for a leading slash...
3736 */
3737
3738 if (path[0] != '/')
3739 return (0);
3740
3741 /*
3742 * Check for "/.." in the path...
3743 */
3744
3745 while ((path = strstr(path, "/..")) != NULL)
3746 {
3747 if (!path[3] || path[3] == '/')
3748 return (0);
3749
3750 path ++;
3751 }
3752
3753 /*
3754 * If we haven't found any relative paths, return 1 indicating an
3755 * absolute path...
3756 */
3757
3758 return (1);
3759 }
3760
3761
3762 #ifdef HAVE_SSL
3763 /*
3764 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3765 */
3766
3767 static int /* O - 1 on success, 0 on failure */
3768 make_certificate(cupsd_client_t *con) /* I - Client connection */
3769 {
3770 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3771 int pid, /* Process ID of command */
3772 status; /* Status of command */
3773 char command[1024], /* Command */
3774 *argv[12], /* Command-line arguments */
3775 *envp[MAX_ENV + 1], /* Environment variables */
3776 home[1024], /* HOME environment variable */
3777 infofile[1024], /* Type-in information for cert */
3778 seedfile[1024]; /* Random number seed file */
3779 int envc, /* Number of environment variables */
3780 bytes; /* Bytes written */
3781 cups_file_t *fp; /* Seed/info file */
3782 int infofd; /* Info file descriptor */
3783
3784
3785 /*
3786 * Run the "openssl" command to seed the random number generator and
3787 * generate a self-signed certificate that is good for 10 years:
3788 *
3789 * openssl rand -rand seedfile 1
3790 *
3791 * openssl req -new -x509 -keyout ServerKey \
3792 * -out ServerCertificate -days 3650 -nodes
3793 *
3794 * The seeding step is crucial in ensuring that the openssl command
3795 * does not block on systems without sufficient entropy...
3796 */
3797
3798 if (!cupsFileFind("openssl", getenv("PATH"), 1, command, sizeof(command)))
3799 {
3800 cupsdLogMessage(CUPSD_LOG_ERROR,
3801 "No SSL certificate and openssl command not found!");
3802 return (0);
3803 }
3804
3805 if (access("/dev/urandom", 0))
3806 {
3807 /*
3808 * If the system doesn't provide /dev/urandom, then any random source
3809 * will probably be blocking-style, so generate some random data to
3810 * use as a seed for the certificate. Note that we have already
3811 * seeded the random number generator in cupsdInitCerts()...
3812 */
3813
3814 cupsdLogMessage(CUPSD_LOG_INFO,
3815 "Seeding the random number generator...");
3816
3817 snprintf(home, sizeof(home), "HOME=%s", TempDir);
3818
3819 /*
3820 * Write the seed file...
3821 */
3822
3823 if ((fp = cupsTempFile2(seedfile, sizeof(seedfile))) == NULL)
3824 {
3825 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create seed file %s - %s",
3826 seedfile, strerror(errno));
3827 return (0);
3828 }
3829
3830 for (bytes = 0; bytes < 262144; bytes ++)
3831 cupsFilePutChar(fp, random());
3832
3833 cupsFileClose(fp);
3834
3835 /*
3836 * Run the openssl command to seed its random number generator...
3837 */
3838
3839 argv[0] = "openssl";
3840 argv[1] = "rand";
3841 argv[2] = "-rand";
3842 argv[3] = seedfile;
3843 argv[4] = "1";
3844 argv[5] = NULL;
3845
3846 envc = cupsdLoadEnv(envp, MAX_ENV);
3847 envp[envc++] = home;
3848 envp[envc] = NULL;
3849
3850 if (!cupsdStartProcess(command, argv, envp, -1, -1, -1, -1, -1, 1, NULL,
3851 &pid))
3852 {
3853 unlink(seedfile);
3854 return (0);
3855 }
3856
3857 while (waitpid(pid, &status, 0) < 0)
3858 if (errno != EINTR)
3859 {
3860 status = 1;
3861 break;
3862 }
3863
3864 cupsdFinishProcess(pid, command, sizeof(command));
3865
3866 /*
3867 * Remove the seed file, as it is no longer needed...
3868 */
3869
3870 unlink(seedfile);
3871
3872 if (status)
3873 {
3874 if (WIFEXITED(status))
3875 cupsdLogMessage(CUPSD_LOG_ERROR,
3876 "Unable to seed random number generator - "
3877 "the openssl command stopped with status %d!",
3878 WEXITSTATUS(status));
3879 else
3880 cupsdLogMessage(CUPSD_LOG_ERROR,
3881 "Unable to seed random number generator - "
3882 "the openssl command crashed on signal %d!",
3883 WTERMSIG(status));
3884
3885 return (0);
3886 }
3887 }
3888
3889 /*
3890 * Create a file with the certificate information fields...
3891 *
3892 * Note: This assumes that the default questions are asked by the openssl
3893 * command...
3894 */
3895
3896 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
3897 {
3898 cupsdLogMessage(CUPSD_LOG_ERROR,
3899 "Unable to create certificate information file %s - %s",
3900 infofile, strerror(errno));
3901 return (0);
3902 }
3903
3904 cupsFilePrintf(fp, ".\n.\n.\n%s\n.\n%s\n%s\n",
3905 ServerName, ServerName, ServerAdmin);
3906 cupsFileClose(fp);
3907
3908 cupsdLogMessage(CUPSD_LOG_INFO,
3909 "Generating SSL server key and certificate...");
3910
3911 argv[0] = "openssl";
3912 argv[1] = "req";
3913 argv[2] = "-new";
3914 argv[3] = "-x509";
3915 argv[4] = "-keyout";
3916 argv[5] = ServerKey;
3917 argv[6] = "-out";
3918 argv[7] = ServerCertificate;
3919 argv[8] = "-days";
3920 argv[9] = "3650";
3921 argv[10] = "-nodes";
3922 argv[11] = NULL;
3923
3924 cupsdLoadEnv(envp, MAX_ENV);
3925
3926 infofd = open(infofile, O_RDONLY);
3927
3928 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
3929 &pid))
3930 {
3931 close(infofd);
3932 unlink(infofile);
3933 return (0);
3934 }
3935
3936 close(infofd);
3937 unlink(infofile);
3938
3939 while (waitpid(pid, &status, 0) < 0)
3940 if (errno != EINTR)
3941 {
3942 status = 1;
3943 break;
3944 }
3945
3946 cupsdFinishProcess(pid, command, sizeof(command));
3947
3948 if (status)
3949 {
3950 if (WIFEXITED(status))
3951 cupsdLogMessage(CUPSD_LOG_ERROR,
3952 "Unable to create SSL server key and certificate - "
3953 "the openssl command stopped with status %d!",
3954 WEXITSTATUS(status));
3955 else
3956 cupsdLogMessage(CUPSD_LOG_ERROR,
3957 "Unable to create SSL server key and certificate - "
3958 "the openssl command crashed on signal %d!",
3959 WTERMSIG(status));
3960 }
3961 else
3962 {
3963 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
3964 ServerKey);
3965 cupsdLogMessage(CUPSD_LOG_INFO,
3966 "Created SSL server certificate file \"%s\"...",
3967 ServerCertificate);
3968 }
3969
3970 return (!status);
3971
3972 #elif defined(HAVE_GNUTLS)
3973 gnutls_x509_crt crt; /* Self-signed certificate */
3974 gnutls_x509_privkey key; /* Encryption key */
3975 cups_lang_t *language; /* Default language info */
3976 cups_file_t *fp; /* Key/cert file */
3977 unsigned char buffer[8192]; /* Buffer for x509 data */
3978 size_t bytes; /* Number of bytes of data */
3979 unsigned char serial[4]; /* Serial number buffer */
3980 time_t curtime; /* Current time */
3981 int result; /* Result of GNU TLS calls */
3982
3983
3984 /*
3985 * Create the encryption key...
3986 */
3987
3988 cupsdLogMessage(CUPSD_LOG_INFO, "Generating SSL server key...");
3989
3990 gnutls_x509_privkey_init(&key);
3991 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
3992
3993 /*
3994 * Save it...
3995 */
3996
3997 bytes = sizeof(buffer);
3998
3999 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM,
4000 buffer, &bytes)) < 0)
4001 {
4002 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to export SSL server key - %s",
4003 gnutls_strerror(result));
4004 gnutls_x509_privkey_deinit(key);
4005 return (0);
4006 }
4007 else if ((fp = cupsFileOpen(ServerKey, "w")) != NULL)
4008 {
4009 cupsFileWrite(fp, (char *)buffer, bytes);
4010 cupsFileClose(fp);
4011
4012 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4013 ServerKey);
4014 }
4015 else
4016 {
4017 cupsdLogMessage(CUPSD_LOG_ERROR,
4018 "Unable to create SSL server key file \"%s\" - %s",
4019 ServerKey, strerror(errno));
4020 gnutls_x509_privkey_deinit(key);
4021 return (0);
4022 }
4023
4024 /*
4025 * Create the self-signed certificate...
4026 */
4027
4028 cupsdLogMessage(CUPSD_LOG_INFO, "Generating self-signed SSL certificate...");
4029
4030 language = cupsLangDefault();
4031 curtime = time(NULL);
4032 serial[0] = curtime >> 24;
4033 serial[1] = curtime >> 16;
4034 serial[2] = curtime >> 8;
4035 serial[3] = curtime;
4036
4037 gnutls_x509_crt_init(&crt);
4038 if (strlen(language->language) == 5)
4039 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4040 language->language + 3, 2);
4041 else
4042 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4043 "US", 2);
4044 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
4045 ServerName, strlen(ServerName));
4046 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
4047 ServerName, strlen(ServerName));
4048 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
4049 0, "Unknown", 7);
4050 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
4051 "Unknown", 7);
4052 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
4053 "Unknown", 7);
4054 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
4055 ServerAdmin, strlen(ServerAdmin));
4056 gnutls_x509_crt_set_key(crt, key);
4057 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
4058 gnutls_x509_crt_set_activation_time(crt, curtime);
4059 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
4060 gnutls_x509_crt_set_ca_status(crt, 0);
4061 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME,
4062 ServerName);
4063 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
4064 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
4065 gnutls_x509_crt_set_version(crt, 3);
4066
4067 bytes = sizeof(buffer);
4068 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
4069 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
4070
4071 gnutls_x509_crt_sign(crt, crt, key);
4072
4073 /*
4074 * Save it...
4075 */
4076
4077 bytes = sizeof(buffer);
4078 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM,
4079 buffer, &bytes)) < 0)
4080 cupsdLogMessage(CUPSD_LOG_ERROR,
4081 "Unable to export SSL server certificate - %s",
4082 gnutls_strerror(result));
4083 else if ((fp = cupsFileOpen(ServerCertificate, "w")) != NULL)
4084 {
4085 cupsFileWrite(fp, (char *)buffer, bytes);
4086 cupsFileClose(fp);
4087
4088 cupsdLogMessage(CUPSD_LOG_INFO,
4089 "Created SSL server certificate file \"%s\"...",
4090 ServerCertificate);
4091 }
4092 else
4093 cupsdLogMessage(CUPSD_LOG_ERROR,
4094 "Unable to create SSL server certificate file \"%s\" - %s",
4095 ServerCertificate, strerror(errno));
4096
4097 /*
4098 * Cleanup...
4099 */
4100
4101 gnutls_x509_crt_deinit(crt);
4102 gnutls_x509_privkey_deinit(key);
4103
4104 return (1);
4105
4106 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4107 int pid, /* Process ID of command */
4108 status; /* Status of command */
4109 char command[1024], /* Command */
4110 *argv[4], /* Command-line arguments */
4111 *envp[MAX_ENV + 1], /* Environment variables */
4112 keychain[1024], /* Keychain argument */
4113 infofile[1024]; /* Type-in information for cert */
4114 cups_file_t *fp; /* Seed/info file */
4115 int infofd; /* Info file descriptor */
4116
4117
4118 /*
4119 * Run the "certtool" command to generate a self-signed certificate...
4120 */
4121
4122 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
4123 {
4124 cupsdLogMessage(CUPSD_LOG_ERROR,
4125 "No SSL certificate and certtool command not found!");
4126 return (0);
4127 }
4128
4129 /*
4130 * Create a file with the certificate information fields...
4131 *
4132 * Note: This assumes that the default questions are asked by the certtool
4133 * command...
4134 */
4135
4136 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4137 {
4138 cupsdLogMessage(CUPSD_LOG_ERROR,
4139 "Unable to create certificate information file %s - %s",
4140 infofile, strerror(errno));
4141 return (0);
4142 }
4143
4144 cupsFilePrintf(fp, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4145 con->servername, con->servername, ServerAdmin);
4146 cupsFileClose(fp);
4147
4148 cupsdLogMessage(CUPSD_LOG_INFO,
4149 "Generating SSL server key and certificate...");
4150
4151 snprintf(keychain, sizeof(keychain), "k=%s", ServerCertificate);
4152
4153 argv[0] = "certtool";
4154 argv[1] = "c";
4155 argv[2] = keychain;
4156 argv[3] = NULL;
4157
4158 cupsdLoadEnv(envp, MAX_ENV);
4159
4160 infofd = open(infofile, O_RDONLY);
4161
4162 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4163 &pid))
4164 {
4165 close(infofd);
4166 unlink(infofile);
4167 return (0);
4168 }
4169
4170 close(infofd);
4171 unlink(infofile);
4172
4173 while (waitpid(pid, &status, 0) < 0)
4174 if (errno != EINTR)
4175 {
4176 status = 1;
4177 break;
4178 }
4179
4180 cupsdFinishProcess(pid, command, sizeof(command));
4181
4182 if (status)
4183 {
4184 if (WIFEXITED(status))
4185 cupsdLogMessage(CUPSD_LOG_ERROR,
4186 "Unable to create SSL server key and certificate - "
4187 "the certtool command stopped with status %d!",
4188 WEXITSTATUS(status));
4189 else
4190 cupsdLogMessage(CUPSD_LOG_ERROR,
4191 "Unable to create SSL server key and certificate - "
4192 "the certtool command crashed on signal %d!",
4193 WTERMSIG(status));
4194 }
4195 else
4196 {
4197 cupsdLogMessage(CUPSD_LOG_INFO,
4198 "Created SSL server certificate file \"%s\"...",
4199 ServerCertificate);
4200 }
4201
4202 return (!status);
4203
4204 #else
4205 return (0);
4206 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4207 }
4208 #endif /* HAVE_SSL */
4209
4210
4211 /*
4212 * 'pipe_command()' - Pipe the output of a command to the remote client.
4213 */
4214
4215 static int /* O - Process ID */
4216 pipe_command(cupsd_client_t *con, /* I - Client connection */
4217 int infile, /* I - Standard input for command */
4218 int *outfile, /* O - Standard output for command */
4219 char *command, /* I - Command to run */
4220 char *options, /* I - Options for command */
4221 int root) /* I - Run as root? */
4222 {
4223 int i; /* Looping var */
4224 int pid; /* Process ID */
4225 char *commptr, /* Command string pointer */
4226 commch; /* Command string character */
4227 char *uriptr; /* URI string pointer */
4228 int fds[2]; /* Pipe FDs */
4229 int argc; /* Number of arguments */
4230 int envc; /* Number of environment variables */
4231 char argbuf[10240], /* Argument buffer */
4232 *argv[100], /* Argument strings */
4233 *envp[MAX_ENV + 20]; /* Environment variables */
4234 char auth_type[256], /* AUTH_TYPE environment variable */
4235 content_length[1024], /* CONTENT_LENGTH environment variable */
4236 content_type[1024], /* CONTENT_TYPE environment variable */
4237 http_cookie[32768], /* HTTP_COOKIE environment variable */
4238 http_referer[1024], /* HTTP_REFERER environment variable */
4239 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
4240 lang[1024], /* LANG environment variable */
4241 path_info[1024], /* PATH_INFO environment variable */
4242 remote_addr[1024], /* REMOTE_ADDR environment variable */
4243 remote_host[1024], /* REMOTE_HOST environment variable */
4244 remote_user[1024], /* REMOTE_USER environment variable */
4245 script_filename[1024], /* SCRIPT_FILENAME environment variable */
4246 script_name[1024], /* SCRIPT_NAME environment variable */
4247 server_name[1024], /* SERVER_NAME environment variable */
4248 server_port[1024]; /* SERVER_PORT environment variable */
4249 ipp_attribute_t *attr; /* attributes-natural-language attribute */
4250
4251
4252 /*
4253 * Parse a copy of the options string, which is of the form:
4254 *
4255 * argument+argument+argument
4256 * ?argument+argument+argument
4257 * param=value&param=value
4258 * ?param=value&param=value
4259 * /name?argument+argument+argument
4260 * /name?param=value&param=value
4261 *
4262 * If the string contains an "=" character after the initial name,
4263 * then we treat it as a HTTP GET form request and make a copy of
4264 * the remaining string for the environment variable.
4265 *
4266 * The string is always parsed out as command-line arguments, to
4267 * be consistent with Apache...
4268 */
4269
4270 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4271 "pipe_command: command=\"%s\", options=\"%s\"",
4272 command, options ? options : "(null)");
4273
4274 argv[0] = command;
4275
4276 if (options)
4277 strlcpy(argbuf, options, sizeof(argbuf));
4278 else
4279 argbuf[0] = '\0';
4280
4281 if (argbuf[0] == '/')
4282 {
4283 /*
4284 * Found some trailing path information, set PATH_INFO...
4285 */
4286
4287 if ((commptr = strchr(argbuf, '?')) == NULL)
4288 commptr = argbuf + strlen(argbuf);
4289
4290 commch = *commptr;
4291 *commptr = '\0';
4292 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
4293 *commptr = commch;
4294 }
4295 else
4296 {
4297 commptr = argbuf;
4298 path_info[0] = '\0';
4299
4300 if (*commptr == ' ')
4301 commptr ++;
4302 }
4303
4304 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
4305 {
4306 commptr ++;
4307 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
4308 }
4309
4310 argc = 1;
4311
4312 if (*commptr)
4313 {
4314 argv[argc ++] = commptr;
4315
4316 for (; *commptr && argc < 99; commptr ++)
4317 {
4318 /*
4319 * Break arguments whenever we see a + or space...
4320 */
4321
4322 if (*commptr == ' ' || *commptr == '+')
4323 {
4324 while (*commptr == ' ' || *commptr == '+')
4325 *commptr++ = '\0';
4326
4327 /*
4328 * If we don't have a blank string, save it as another argument...
4329 */
4330
4331 if (*commptr)
4332 {
4333 argv[argc] = commptr;
4334 argc ++;
4335 }
4336 else
4337 break;
4338 }
4339 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
4340 isxdigit(commptr[2] & 255))
4341 {
4342 /*
4343 * Convert the %xx notation to the individual character.
4344 */
4345
4346 if (commptr[1] >= '0' && commptr[1] <= '9')
4347 *commptr = (commptr[1] - '0') << 4;
4348 else
4349 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
4350
4351 if (commptr[2] >= '0' && commptr[2] <= '9')
4352 *commptr |= commptr[2] - '0';
4353 else
4354 *commptr |= tolower(commptr[2]) - 'a' + 10;
4355
4356 _cups_strcpy(commptr + 1, commptr + 3);
4357
4358 /*
4359 * Check for a %00 and break if that is the case...
4360 */
4361
4362 if (!*commptr)
4363 break;
4364 }
4365 }
4366 }
4367
4368 argv[argc] = NULL;
4369
4370 /*
4371 * Setup the environment variables as needed...
4372 */
4373
4374 if (con->username[0])
4375 {
4376 snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
4377 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
4378
4379 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
4380 *uriptr = '\0';
4381 }
4382 else
4383 auth_type[0] = '\0';
4384
4385 if (con->request &&
4386 (attr = ippFindAttribute(con->request, "attributes-natural-language",
4387 IPP_TAG_LANGUAGE)) != NULL)
4388 {
4389 switch (strlen(attr->values[0].string.text))
4390 {
4391 default :
4392 /*
4393 * This is an unknown or badly formatted language code; use
4394 * the POSIX locale...
4395 */
4396
4397 strcpy(lang, "LANG=C");
4398 break;
4399
4400 case 2 :
4401 /*
4402 * Just the language code (ll)...
4403 */
4404
4405 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
4406 attr->values[0].string.text);
4407 break;
4408
4409 case 5 :
4410 /*
4411 * Language and country code (ll-cc)...
4412 */
4413
4414 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
4415 attr->values[0].string.text[0],
4416 attr->values[0].string.text[1],
4417 toupper(attr->values[0].string.text[3] & 255),
4418 toupper(attr->values[0].string.text[4] & 255));
4419 break;
4420 }
4421 }
4422 else if (con->language)
4423 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
4424 else
4425 strcpy(lang, "LANG=C");
4426
4427 strcpy(remote_addr, "REMOTE_ADDR=");
4428 httpAddrString(con->http.hostaddr, remote_addr + 12,
4429 sizeof(remote_addr) - 12);
4430
4431 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
4432 con->http.hostname);
4433
4434 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
4435 if ((uriptr = strchr(script_name, '?')) != NULL)
4436 *uriptr = '\0';
4437
4438 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
4439 DocumentRoot, script_name + 12);
4440
4441 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
4442
4443 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
4444 con->servername);
4445
4446 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
4447
4448 if (auth_type[0])
4449 envp[envc ++] = auth_type;
4450
4451 envp[envc ++] = lang;
4452 envp[envc ++] = "REDIRECT_STATUS=1";
4453 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
4454 envp[envc ++] = server_name;
4455 envp[envc ++] = server_port;
4456 envp[envc ++] = remote_addr;
4457 envp[envc ++] = remote_host;
4458 envp[envc ++] = script_name;
4459 envp[envc ++] = script_filename;
4460
4461 if (path_info[0])
4462 envp[envc ++] = path_info;
4463
4464 if (con->username[0])
4465 {
4466 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
4467
4468 envp[envc ++] = remote_user;
4469 }
4470
4471 if (con->http.version == HTTP_1_1)
4472 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
4473 else if (con->http.version == HTTP_1_0)
4474 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
4475 else
4476 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
4477
4478 if (con->http.cookie)
4479 {
4480 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
4481 con->http.cookie);
4482 envp[envc ++] = http_cookie;
4483 }
4484
4485 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
4486 {
4487 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
4488 con->http.fields[HTTP_FIELD_USER_AGENT]);
4489 envp[envc ++] = http_user_agent;
4490 }
4491
4492 if (con->http.fields[HTTP_FIELD_REFERER][0])
4493 {
4494 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
4495 con->http.fields[HTTP_FIELD_REFERER]);
4496 envp[envc ++] = http_referer;
4497 }
4498
4499 if (con->operation == HTTP_GET)
4500 {
4501 envp[envc ++] = "REQUEST_METHOD=GET";
4502
4503 if (con->query_string)
4504 {
4505 /*
4506 * Add GET form variables after ?...
4507 */
4508
4509 envp[envc ++] = con->query_string;
4510 }
4511 }
4512 else
4513 {
4514 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
4515 CUPS_LLCAST con->bytes);
4516 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
4517 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
4518
4519 envp[envc ++] = "REQUEST_METHOD=POST";
4520 envp[envc ++] = content_length;
4521 envp[envc ++] = content_type;
4522 }
4523
4524 /*
4525 * Tell the CGI if we are using encryption...
4526 */
4527
4528 if (con->http.tls)
4529 envp[envc ++] = "HTTPS=ON";
4530
4531 /*
4532 * Terminate the environment array...
4533 */
4534
4535 envp[envc] = NULL;
4536
4537 if (LogLevel == CUPSD_LOG_DEBUG2)
4538 {
4539 for (i = 0; i < argc; i ++)
4540 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4541 "pipe_command: argv[%d] = \"%s\"", i, argv[i]);
4542 for (i = 0; i < envc; i ++)
4543 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4544 "pipe_command: envp[%d] = \"%s\"", i, envp[i]);
4545 }
4546
4547 /*
4548 * Create a pipe for the output...
4549 */
4550
4551 if (cupsdOpenPipe(fds))
4552 {
4553 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create pipes for CGI %s - %s",
4554 argv[0], strerror(errno));
4555 return (0);
4556 }
4557
4558 /*
4559 * Then execute the command...
4560 */
4561
4562 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
4563 -1, -1, root, DefaultProfile, &pid) < 0)
4564 {
4565 /*
4566 * Error - can't fork!
4567 */
4568
4569 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork for CGI %s - %s", argv[0],
4570 strerror(errno));
4571
4572 cupsdClosePipe(fds);
4573 pid = 0;
4574 }
4575 else
4576 {
4577 /*
4578 * Fork successful - return the PID...
4579 */
4580
4581 if (con->username[0])
4582 cupsdAddCert(pid, con->username);
4583
4584 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] %s started - PID = %d",
4585 command, pid);
4586
4587 *outfile = fds[0];
4588 close(fds[1]);
4589 }
4590
4591 return (pid);
4592 }
4593
4594
4595 /*
4596 * 'write_file()' - Send a file via HTTP.
4597 */
4598
4599 static int /* O - 0 on failure, 1 on success */
4600 write_file(cupsd_client_t *con, /* I - Client connection */
4601 http_status_t code, /* I - HTTP status */
4602 char *filename, /* I - Filename */
4603 char *type, /* I - File type */
4604 struct stat *filestats) /* O - File information */
4605 {
4606 con->file = open(filename, O_RDONLY);
4607
4608 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_file: %d file=%d", con->http.fd,
4609 con->file);
4610
4611 if (con->file < 0)
4612 return (0);
4613
4614 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4615
4616 con->pipe_pid = 0;
4617
4618 if (!cupsdSendHeader(con, code, type, AUTH_NONE))
4619 return (0);
4620
4621 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
4622 httpGetDateString(filestats->st_mtime)) < 0)
4623 return (0);
4624 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
4625 CUPS_LLCAST filestats->st_size) < 0)
4626 return (0);
4627 if (httpPrintf(HTTP(con), "\r\n") < 0)
4628 return (0);
4629
4630 if (cupsdFlushHeader(con) < 0)
4631 return (0);
4632
4633 con->http.data_encoding = HTTP_ENCODE_LENGTH;
4634 con->http.data_remaining = filestats->st_size;
4635
4636 if (con->http.data_remaining <= INT_MAX)
4637 con->http._data_remaining = con->http.data_remaining;
4638 else
4639 con->http._data_remaining = INT_MAX;
4640
4641 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
4642 (cupsd_selfunc_t)cupsdWriteClient, con);
4643
4644 return (1);
4645 }
4646
4647
4648 /*
4649 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4650 */
4651
4652 static void
4653 write_pipe(cupsd_client_t *con) /* I - Client connection */
4654 {
4655 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d...",
4656 con->file);
4657
4658 con->file_ready = 1;
4659
4660 cupsdRemoveSelect(con->file);
4661 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4662 }
4663
4664
4665 /*
4666 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".
4667 */