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