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