]> 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 6504 2007-05-02 00:14:56Z 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(%d), file=%d "
2535 "pipe_pid=%d state=%d",
2536 con, con->http.fd, con->response, con->response->state,
2537 con->file, con->pipe_pid, 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 && con->response->state != IPP_DATA)
2566 {
2567 ipp_state = ippWrite(HTTP(con), con->response);
2568 bytes = ipp_state != IPP_ERROR &&
2569 (con->file >= 0 || ipp_state != IPP_DATA);
2570 }
2571 else if ((bytes = read(con->file, buf, sizeof(buf) - 1)) > 0)
2572 {
2573 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2574 "cupsdWriteClient: Read %d bytes from file %d...",
2575 bytes, con->file);
2576
2577 if (con->pipe_pid && !con->got_fields)
2578 {
2579 /*
2580 * Inspect the data for Content-Type and other fields.
2581 */
2582
2583 buf[bytes] = '\0';
2584
2585 for (bufptr = buf; !con->got_fields && *bufptr; bufptr ++)
2586 if (*bufptr == '\n')
2587 {
2588 /*
2589 * Send line to client...
2590 */
2591
2592 if (bufptr > buf && bufptr[-1] == '\r')
2593 bufptr[-1] = '\0';
2594 *bufptr++ = '\0';
2595
2596 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Script header: %s", buf);
2597
2598 if (!con->sent_header)
2599 {
2600 /*
2601 * Handle redirection and CGI status codes...
2602 */
2603
2604 if (!strncasecmp(buf, "Location:", 9))
2605 {
2606 cupsdSendHeader(con, HTTP_SEE_OTHER, NULL, AUTH_NONE);
2607 con->sent_header = 2;
2608
2609 if (httpPrintf(HTTP(con), "Content-Length: 0\r\n") < 0)
2610 return;
2611 }
2612 else if (!strncasecmp(buf, "Status:", 7))
2613 {
2614 cupsdSendError(con, (http_status_t)atoi(buf + 7), AUTH_NONE);
2615 con->sent_header = 2;
2616 }
2617 else
2618 {
2619 cupsdSendHeader(con, HTTP_OK, NULL, AUTH_NONE);
2620 con->sent_header = 1;
2621
2622 if (con->http.version == HTTP_1_1)
2623 {
2624 if (httpPrintf(HTTP(con), "Transfer-Encoding: chunked\r\n") < 0)
2625 return;
2626 }
2627 }
2628 }
2629
2630 if (strncasecmp(buf, "Status:", 7))
2631 httpPrintf(HTTP(con), "%s\r\n", buf);
2632
2633 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d %s",
2634 con->http.fd, buf);
2635
2636 /*
2637 * Update buffer...
2638 */
2639
2640 bytes -= (bufptr - buf);
2641 memmove(buf, bufptr, bytes + 1);
2642 bufptr = buf - 1;
2643
2644 /*
2645 * See if the line was empty...
2646 */
2647
2648 if (con->field_col == 0)
2649 {
2650 con->got_fields = 1;
2651
2652 if (cupsdFlushHeader(con) < 0)
2653 {
2654 cupsdCloseClient(con);
2655 return;
2656 }
2657
2658 if (con->http.version == HTTP_1_1)
2659 con->http.data_encoding = HTTP_ENCODE_CHUNKED;
2660 }
2661 else
2662 con->field_col = 0;
2663 }
2664 else if (*bufptr != '\r')
2665 con->field_col ++;
2666
2667 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2668 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2669 con->http.fd, bytes, con->got_fields);
2670
2671 if (bytes > 0 && !con->got_fields)
2672 {
2673 /*
2674 * Remaining text needs to go out...
2675 */
2676
2677 httpPrintf(HTTP(con), "%s", buf);
2678
2679 con->http.activity = time(NULL);
2680 return;
2681 }
2682 else if (bytes == 0)
2683 con->http.activity = time(NULL);
2684 }
2685
2686 if (bytes > 0)
2687 {
2688 if (httpWrite2(HTTP(con), buf, bytes) < 0)
2689 {
2690 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2691 "cupsdWriteClient: %d Write of %d bytes failed!",
2692 con->http.fd, bytes);
2693
2694 cupsdCloseClient(con);
2695 return;
2696 }
2697
2698 con->bytes += bytes;
2699
2700 if (con->http.state == HTTP_WAITING)
2701 bytes = 0;
2702 }
2703 }
2704
2705 if (bytes <= 0)
2706 {
2707 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d bytes < 0",
2708 con->http.fd);
2709
2710 cupsdLogRequest(con, HTTP_OK);
2711
2712 httpFlushWrite(HTTP(con));
2713
2714 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED && con->sent_header == 1)
2715 {
2716 if (httpWrite2(HTTP(con), "", 0) < 0)
2717 {
2718 cupsdCloseClient(con);
2719 return;
2720 }
2721 }
2722
2723 con->http.state = HTTP_WAITING;
2724
2725 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
2726
2727 if (con->file >= 0)
2728 {
2729 cupsdRemoveSelect(con->file);
2730
2731 if (con->pipe_pid)
2732 cupsdEndProcess(con->pipe_pid, 0);
2733
2734 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2735 "cupsdWriteClient: %d Closing data file %d.",
2736 con->http.fd, con->file);
2737
2738 close(con->file);
2739 con->file = -1;
2740 con->pipe_pid = 0;
2741 }
2742
2743 if (con->filename)
2744 {
2745 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2746 "cupsdWriteClient: %d Removing temp file %s",
2747 con->http.fd, con->filename);
2748 unlink(con->filename);
2749 cupsdClearString(&con->filename);
2750 }
2751
2752 if (con->request)
2753 {
2754 ippDelete(con->request);
2755 con->request = NULL;
2756 }
2757
2758 if (con->response)
2759 {
2760 ippDelete(con->response);
2761 con->response = NULL;
2762 }
2763
2764 cupsdClearString(&con->command);
2765 cupsdClearString(&con->options);
2766 cupsdClearString(&con->query_string);
2767
2768 if (!con->http.keep_alive)
2769 {
2770 cupsdCloseClient(con);
2771 return;
2772 }
2773 }
2774
2775 con->http.activity = time(NULL);
2776 }
2777
2778
2779 /*
2780 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2781 */
2782
2783 static int /* O - 1 if modified since */
2784 check_if_modified(
2785 cupsd_client_t *con, /* I - Client connection */
2786 struct stat *filestats) /* I - File information */
2787 {
2788 char *ptr; /* Pointer into field */
2789 time_t date; /* Time/date value */
2790 off_t size; /* Size/length value */
2791
2792
2793 size = 0;
2794 date = 0;
2795 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
2796
2797 if (*ptr == '\0')
2798 return (1);
2799
2800 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2801 "check_if_modified: %d If-Modified-Since=\"%s\"",
2802 con->http.fd, ptr);
2803
2804 while (*ptr != '\0')
2805 {
2806 while (isspace(*ptr) || *ptr == ';')
2807 ptr ++;
2808
2809 if (strncasecmp(ptr, "length=", 7) == 0)
2810 {
2811 ptr += 7;
2812 size = strtoll(ptr, NULL, 10);
2813
2814 while (isdigit(*ptr))
2815 ptr ++;
2816 }
2817 else if (isalpha(*ptr))
2818 {
2819 date = httpGetDateTime(ptr);
2820 while (*ptr != '\0' && *ptr != ';')
2821 ptr ++;
2822 }
2823 else
2824 ptr ++;
2825 }
2826
2827 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2828 "check_if_modified: %d sizes=" CUPS_LLFMT ","
2829 CUPS_LLFMT " dates=%d,%d",
2830 con->http.fd, CUPS_LLCAST size,
2831 CUPS_LLCAST filestats->st_size, (int)date,
2832 (int)filestats->st_mtime);
2833
2834 return ((size != filestats->st_size && size != 0) ||
2835 (date < filestats->st_mtime && date != 0) ||
2836 (size == 0 && date == 0));
2837 }
2838
2839
2840 #ifdef HAVE_SSL
2841 /*
2842 * 'encrypt_client()' - Enable encryption for the client...
2843 */
2844
2845 static int /* O - 1 on success, 0 on error */
2846 encrypt_client(cupsd_client_t *con) /* I - Client to encrypt */
2847 {
2848 # ifdef HAVE_LIBSSL
2849 SSL_CTX *context; /* Context for encryption */
2850 SSL *conn; /* Connection for encryption */
2851 BIO *bio; /* BIO data */
2852 unsigned long error; /* Error code */
2853
2854
2855 /*
2856 * Verify that we have a certificate...
2857 */
2858
2859 if (access(ServerKey, 0) || access(ServerCertificate, 0))
2860 {
2861 /*
2862 * Nope, make a self-signed certificate...
2863 */
2864
2865 if (!make_certificate(con))
2866 return (0);
2867 }
2868
2869 /*
2870 * Create the SSL context and accept the connection...
2871 */
2872
2873 context = SSL_CTX_new(SSLv23_server_method());
2874
2875 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
2876 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
2877 SSL_CTX_use_certificate_file(context, ServerCertificate, SSL_FILETYPE_PEM);
2878
2879 bio = BIO_new(_httpBIOMethods());
2880 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)HTTP(con));
2881
2882 conn = SSL_new(context);
2883 SSL_set_bio(conn, bio, bio);
2884
2885 if (SSL_accept(conn) != 1)
2886 {
2887 cupsdLogMessage(CUPSD_LOG_ERROR,
2888 "encrypt_client: Unable to encrypt connection from %s!",
2889 con->http.hostname);
2890
2891 while ((error = ERR_get_error()) != 0)
2892 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
2893 ERR_error_string(error, NULL));
2894
2895 SSL_CTX_free(context);
2896 SSL_free(conn);
2897 return (0);
2898 }
2899
2900 cupsdLogMessage(CUPSD_LOG_DEBUG,
2901 "encrypt_client: %d Connection from %s now encrypted.",
2902 con->http.fd, con->http.hostname);
2903
2904 con->http.tls = conn;
2905 return (1);
2906
2907 # elif defined(HAVE_GNUTLS)
2908 http_tls_t *conn; /* TLS session object */
2909 int error; /* Error code */
2910 gnutls_certificate_server_credentials *credentials;
2911 /* TLS credentials */
2912
2913
2914 /*
2915 * Verify that we have a certificate...
2916 */
2917
2918 if (access(ServerKey, 0) || access(ServerCertificate, 0))
2919 {
2920 /*
2921 * Nope, make a self-signed certificate...
2922 */
2923
2924 if (!make_certificate(con))
2925 return (0);
2926 }
2927
2928 /*
2929 * Create the SSL object and perform the SSL handshake...
2930 */
2931
2932 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
2933
2934 if (conn == NULL)
2935 return (0);
2936
2937 credentials = (gnutls_certificate_server_credentials *)
2938 malloc(sizeof(gnutls_certificate_server_credentials));
2939 if (credentials == NULL)
2940 {
2941 cupsdLogMessage(CUPSD_LOG_ERROR,
2942 "encrypt_client: Unable to encrypt connection from %s!",
2943 con->http.hostname);
2944 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s", strerror(errno));
2945
2946 free(conn);
2947 return (0);
2948 }
2949
2950 gnutls_certificate_allocate_credentials(credentials);
2951 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
2952 ServerKey, GNUTLS_X509_FMT_PEM);
2953
2954 gnutls_init(&(conn->session), GNUTLS_SERVER);
2955 gnutls_set_default_priority(conn->session);
2956 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
2957 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)HTTP(con));
2958 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
2959 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
2960
2961 error = gnutls_handshake(conn->session);
2962
2963 if (error != GNUTLS_E_SUCCESS)
2964 {
2965 cupsdLogMessage(CUPSD_LOG_ERROR,
2966 "encrypt_client: Unable to encrypt connection from %s!",
2967 con->http.hostname);
2968 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
2969 gnutls_strerror(error));
2970
2971 gnutls_deinit(conn->session);
2972 gnutls_certificate_free_credentials(*credentials);
2973 free(conn);
2974 free(credentials);
2975 return (0);
2976 }
2977
2978 cupsdLogMessage(CUPSD_LOG_DEBUG,
2979 "encrypt_client: %d Connection from %s now encrypted.",
2980 con->http.fd, con->http.hostname);
2981
2982 conn->credentials = credentials;
2983 con->http.tls = conn;
2984 return (1);
2985
2986 # elif defined(HAVE_CDSASSL)
2987 OSStatus error; /* Error code */
2988 http_tls_t *conn; /* CDSA connection information */
2989
2990
2991 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
2992 return (0);
2993
2994 error = 0;
2995 conn->session = NULL;
2996 conn->certsArray = get_cdsa_certificate(con);
2997
2998 if (!conn->certsArray)
2999 {
3000 /*
3001 * No keychain (yet), make a self-signed certificate...
3002 */
3003
3004 if (make_certificate(con))
3005 conn->certsArray = get_cdsa_certificate(con);
3006 }
3007
3008 if (!conn->certsArray)
3009 {
3010 cupsdLogMessage(CUPSD_LOG_ERROR,
3011 "encrypt_client: Could not find signing key in keychain "
3012 "\"%s\"", ServerCertificate);
3013 error = errSSLBadCert; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3014 }
3015
3016 if (!error)
3017 error = SSLNewContext(true, &conn->session);
3018
3019 if (!error)
3020 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
3021
3022 if (!error)
3023 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
3024
3025 if (!error)
3026 error = SSLSetConnection(conn->session, HTTP(con));
3027
3028 if (!error)
3029 error = SSLSetAllowsExpiredCerts(conn->session, true);
3030
3031 if (!error)
3032 error = SSLSetAllowsAnyRoot(conn->session, true);
3033
3034 if (!error)
3035 error = SSLSetCertificate(conn->session, conn->certsArray);
3036
3037 if (!error)
3038 {
3039 /*
3040 * Perform SSL/TLS handshake
3041 */
3042
3043 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
3044 usleep(1000);
3045 }
3046
3047 if (error)
3048 {
3049 cupsdLogMessage(CUPSD_LOG_ERROR,
3050 "encrypt_client: Unable to encrypt connection from %s!",
3051 con->http.hostname);
3052
3053 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s (%d)",
3054 cssmErrorString(error), (int)error);
3055
3056 con->http.error = error;
3057 con->http.status = HTTP_ERROR;
3058
3059 if (conn->session)
3060 SSLDisposeContext(conn->session);
3061
3062 if (conn->certsArray)
3063 CFRelease(conn->certsArray);
3064
3065 free(conn);
3066
3067 return (0);
3068 }
3069
3070 cupsdLogMessage(CUPSD_LOG_DEBUG,
3071 "encrypt_client: %d Connection from %s now encrypted.",
3072 con->http.fd, con->http.hostname);
3073
3074 con->http.tls = conn;
3075 return (1);
3076
3077 # endif /* HAVE_LIBSSL */
3078 }
3079 #endif /* HAVE_SSL */
3080
3081
3082 #ifdef HAVE_CDSASSL
3083 /*
3084 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3085 */
3086
3087 static CFArrayRef /* O - Array of certificates */
3088 get_cdsa_certificate(cupsd_client_t *con) /* I - Client connection */
3089 {
3090 OSStatus err; /* Error info */
3091 SecKeychainRef keychain; /* Keychain reference */
3092 SecIdentitySearchRef search; /* Search reference */
3093 SecIdentityRef identity; /* Identity */
3094 CFArrayRef certificates = NULL;
3095 /* Certificate array */
3096
3097
3098 if ((err = SecKeychainOpen(ServerCertificate, &keychain)))
3099 {
3100 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\", %s",
3101 ServerCertificate, cssmErrorString(err));
3102 return (NULL);
3103 }
3104
3105 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3106 /*
3107 * Use a policy to search for valid certificates who's common name matches the
3108 * servername...
3109 */
3110
3111 SecPolicySearchRef policy_search; /* Policy search ref */
3112 SecPolicyRef policy; /* Policy ref */
3113 CSSM_DATA options; /* Policy options */
3114 CSSM_APPLE_TP_SSL_OPTIONS
3115 ssl_options; /* SSL Option for hostname */
3116
3117
3118 if ((err = SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL,
3119 NULL, &policy_search)))
3120 {
3121 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create a policy search reference");
3122 CFRelease(keychain);
3123 return (NULL);
3124 }
3125
3126 if ((err = SecPolicySearchCopyNext(policy_search, &policy)))
3127 {
3128 cupsdLogMessage(CUPSD_LOG_ERROR,
3129 "Cannot find a policy to use for searching");
3130 CFRelease(keychain);
3131 CFRelease(policy_search);
3132 return (NULL);
3133 }
3134
3135 memset(&ssl_options, 0, sizeof(ssl_options));
3136 ssl_options.Version = CSSM_APPLE_TP_SSL_OPTS_VERSION;
3137 ssl_options.ServerName = con->servername;
3138 ssl_options.ServerNameLen = strlen(con->servername);
3139
3140 options.Data = (uint8 *)&ssl_options;
3141 options.Length = sizeof(ssl_options);
3142
3143 if ((err = SecPolicySetValue(policy, &options)))
3144 {
3145 cupsdLogMessage(CUPSD_LOG_ERROR,
3146 "Cannot set policy value to use for searching");
3147 CFRelease(keychain);
3148 CFRelease(policy_search);
3149 return (NULL);
3150 }
3151
3152 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3153 keychain, FALSE, &search);
3154 # else
3155 /*
3156 * Assume there is exactly one SecIdentity in the keychain...
3157 */
3158
3159 err = SecIdentitySearchCreate(keychain, CSSM_KEYUSE_SIGN, &search);
3160 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3161
3162 if (err)
3163 cupsdLogMessage(CUPSD_LOG_DEBUG,
3164 "Cannot create keychain search reference: %s",
3165 cssmErrorString(err));
3166 else
3167 {
3168 if ((err = SecIdentitySearchCopyNext(search, &identity)))
3169 {
3170 cupsdLogMessage(CUPSD_LOG_DEBUG,
3171 "Cannot find signing key in keychain \"%s\", error %d",
3172 ServerCertificate, (int)err);
3173 }
3174 else
3175 {
3176 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3177 cupsdLogMessage(CUPSD_LOG_ERROR,
3178 "SecIdentitySearchCopyNext CFTypeID failure!");
3179 else
3180 {
3181 if ((certificates = CFArrayCreate(NULL, (const void **)&identity,
3182 1, &kCFTypeArrayCallBacks)) == NULL)
3183 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create certificate array");
3184 }
3185
3186 CFRelease(identity);
3187 }
3188
3189 CFRelease(search);
3190 }
3191
3192 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3193 CFRelease(policy);
3194 CFRelease(policy_search);
3195 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3196
3197 return (certificates);
3198 }
3199 #endif /* HAVE_CDSASSL */
3200
3201
3202 /*
3203 * 'get_file()' - Get a filename and state info.
3204 */
3205
3206 static char * /* O - Real filename */
3207 get_file(cupsd_client_t *con, /* I - Client connection */
3208 struct stat *filestats, /* O - File information */
3209 char *filename, /* IO - Filename buffer */
3210 int len) /* I - Buffer length */
3211 {
3212 int status; /* Status of filesystem calls */
3213 char *ptr; /* Pointer info filename */
3214 int plen; /* Remaining length after pointer */
3215
3216
3217 /*
3218 * Figure out the real filename...
3219 */
3220
3221 if (!strncmp(con->uri, "/ppd/", 5))
3222 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
3223 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3224 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
3225 else if (!strncmp(con->uri, "/admin/conf/", 12))
3226 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3227 else if (!strncmp(con->uri, "/admin/log/", 11))
3228 {
3229 if (!strcmp(con->uri + 11, "access_log") && AccessLog[0] == '/')
3230 strlcpy(filename, AccessLog, len);
3231 else if (!strcmp(con->uri + 11, "error_log") && ErrorLog[0] == '/')
3232 strlcpy(filename, ErrorLog, len);
3233 else if (!strcmp(con->uri + 11, "page_log") && PageLog[0] == '/')
3234 strlcpy(filename, PageLog, len);
3235 else
3236 return (NULL);
3237 }
3238 else if (con->language)
3239 snprintf(filename, len, "%s/%s%s", DocumentRoot, con->language->language,
3240 con->uri);
3241 else
3242 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3243
3244 if ((ptr = strchr(filename, '?')) != NULL)
3245 *ptr = '\0';
3246
3247 /*
3248 * Grab the status for this language; if there isn't a language-specific file
3249 * then fallback to the default one...
3250 */
3251
3252 if ((status = stat(filename, filestats)) != 0 && con->language &&
3253 strncmp(con->uri, "/ppd/", 5) &&
3254 strncmp(con->uri, "/admin/conf/", 12) &&
3255 strncmp(con->uri, "/admin/log/", 11))
3256 {
3257 /*
3258 * Drop the country code...
3259 */
3260
3261 char ll[3]; /* Short language name */
3262
3263
3264 strlcpy(ll, con->language->language, sizeof(ll));
3265 snprintf(filename, len, "%s/%s%s", DocumentRoot, ll, con->uri);
3266
3267 if ((ptr = strchr(filename, '?')) != NULL)
3268 *ptr = '\0';
3269
3270 if ((status = stat(filename, filestats)) != 0)
3271 {
3272 /*
3273 * Drop the language prefix and try the root directory...
3274 */
3275
3276 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3277
3278 if ((ptr = strchr(filename, '?')) != NULL)
3279 *ptr = '\0';
3280
3281 status = stat(filename, filestats);
3282 }
3283 }
3284
3285 /*
3286 * If we're found a directory, get the index.html file instead...
3287 */
3288
3289 if (!status && S_ISDIR(filestats->st_mode))
3290 {
3291 if (filename[strlen(filename) - 1] != '/')
3292 strlcat(filename, "/", len);
3293
3294 ptr = filename + strlen(filename);
3295 plen = len - (ptr - filename);
3296
3297 strlcpy(ptr, "index.html", plen);
3298 status = stat(filename, filestats);
3299
3300 #ifdef HAVE_JAVA
3301 if (status)
3302 {
3303 strlcpy(ptr, "index.class", plen);
3304 status = stat(filename, filestats);
3305 }
3306 #endif /* HAVE_JAVA */
3307
3308 #ifdef HAVE_PERL
3309 if (status)
3310 {
3311 strlcpy(ptr, "index.pl", plen);
3312 status = stat(filename, filestats);
3313 }
3314 #endif /* HAVE_PERL */
3315
3316 #ifdef HAVE_PHP
3317 if (status)
3318 {
3319 strlcpy(ptr, "index.php", plen);
3320 status = stat(filename, filestats);
3321 }
3322 #endif /* HAVE_PHP */
3323
3324 #ifdef HAVE_PYTHON
3325 if (status)
3326 {
3327 strlcpy(ptr, "index.pyc", plen);
3328 status = stat(filename, filestats);
3329 }
3330
3331 if (status)
3332 {
3333 strlcpy(ptr, "index.py", plen);
3334 status = stat(filename, filestats);
3335 }
3336 #endif /* HAVE_PYTHON */
3337 }
3338
3339 cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_file: %d filename=%s size=%d",
3340 con->http.fd, filename,
3341 status ? -1 : (int)filestats->st_size);
3342
3343 if (!status)
3344 con->http.data_remaining = (int)filestats->st_size;
3345
3346 if (status)
3347 return (NULL);
3348 else
3349 return (filename);
3350 }
3351
3352
3353 /*
3354 * 'install_conf_file()' - Install a configuration file.
3355 */
3356
3357 static http_status_t /* O - Status */
3358 install_conf_file(cupsd_client_t *con) /* I - Connection */
3359 {
3360 cups_file_t *in, /* Input file */
3361 *out; /* Output file */
3362 char buffer[1024]; /* Copy buffer */
3363 int bytes; /* Number of bytes */
3364 char conffile[1024], /* Configuration filename */
3365 newfile[1024], /* New config filename */
3366 oldfile[1024]; /* Old config filename */
3367 struct stat confinfo; /* Config file info */
3368
3369
3370 /*
3371 * First construct the filenames...
3372 */
3373
3374 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3375 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3376 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3377
3378 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3379
3380 /*
3381 * Get the owner, group, and permissions of the configuration file.
3382 * If it doesn't exist, assign it to the User and Group in the
3383 * cupsd.conf file with mode 0640 permissions.
3384 */
3385
3386 if (stat(conffile, &confinfo))
3387 {
3388 confinfo.st_uid = User;
3389 confinfo.st_gid = Group;
3390 confinfo.st_mode = ConfigFilePerm;
3391 }
3392
3393 /*
3394 * Open the request file and new config file...
3395 */
3396
3397 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3398 {
3399 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3400 con->filename, strerror(errno));
3401 return (HTTP_SERVER_ERROR);
3402 }
3403
3404 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3405 {
3406 cupsFileClose(in);
3407 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3408 newfile, strerror(errno));
3409 return (HTTP_SERVER_ERROR);
3410 }
3411
3412 fchmod(cupsFileNumber(out), confinfo.st_mode);
3413 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3414
3415 /*
3416 * Copy from the request to the new config file...
3417 */
3418
3419 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3420 if (cupsFileWrite(out, buffer, bytes) < bytes)
3421 {
3422 cupsdLogMessage(CUPSD_LOG_ERROR,
3423 "Unable to copy to config file \"%s\" - %s",
3424 newfile, strerror(errno));
3425
3426 cupsFileClose(in);
3427 cupsFileClose(out);
3428 unlink(newfile);
3429
3430 return (HTTP_SERVER_ERROR);
3431 }
3432
3433 /*
3434 * Close the files...
3435 */
3436
3437 cupsFileClose(in);
3438 if (cupsFileClose(out))
3439 {
3440 cupsdLogMessage(CUPSD_LOG_ERROR,
3441 "Error file closing config file \"%s\" - %s",
3442 newfile, strerror(errno));
3443
3444 unlink(newfile);
3445
3446 return (HTTP_SERVER_ERROR);
3447 }
3448
3449 /*
3450 * Remove the request file...
3451 */
3452
3453 unlink(con->filename);
3454 cupsdClearString(&con->filename);
3455
3456 /*
3457 * Unlink the old backup, rename the current config file to the backup
3458 * filename, and rename the new config file to the config file name...
3459 */
3460
3461 if (unlink(oldfile))
3462 if (errno != ENOENT)
3463 {
3464 cupsdLogMessage(CUPSD_LOG_ERROR,
3465 "Unable to remove backup config file \"%s\" - %s",
3466 oldfile, strerror(errno));
3467
3468 unlink(newfile);
3469
3470 return (HTTP_SERVER_ERROR);
3471 }
3472
3473 if (rename(conffile, oldfile))
3474 if (errno != ENOENT)
3475 {
3476 cupsdLogMessage(CUPSD_LOG_ERROR,
3477 "Unable to rename old config file \"%s\" - %s",
3478 conffile, strerror(errno));
3479
3480 unlink(newfile);
3481
3482 return (HTTP_SERVER_ERROR);
3483 }
3484
3485 if (rename(newfile, conffile))
3486 {
3487 cupsdLogMessage(CUPSD_LOG_ERROR,
3488 "Unable to rename new config file \"%s\" - %s",
3489 newfile, strerror(errno));
3490
3491 rename(oldfile, conffile);
3492 unlink(newfile);
3493
3494 return (HTTP_SERVER_ERROR);
3495 }
3496
3497 /*
3498 * If the cupsd.conf file was updated, set the NeedReload flag...
3499 */
3500
3501 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3502 NeedReload = RELOAD_CUPSD;
3503 else
3504 NeedReload = RELOAD_ALL;
3505
3506 ReloadTime = time(NULL);
3507
3508 /*
3509 * Return that the file was created successfully...
3510 */
3511
3512 return (HTTP_CREATED);
3513 }
3514
3515
3516 /*
3517 * 'is_cgi()' - Is the resource a CGI script/program?
3518 */
3519
3520 static int /* O - 1 = CGI, 0 = file */
3521 is_cgi(cupsd_client_t *con, /* I - Client connection */
3522 const char *filename, /* I - Real filename */
3523 struct stat *filestats, /* I - File information */
3524 mime_type_t *type) /* I - MIME type */
3525 {
3526 const char *options; /* Options on URL */
3527
3528
3529 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3530 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3531 con, filename, filestats, type ? type->super : "unknown",
3532 type ? type->type : "unknown");
3533
3534 /*
3535 * Get the options, if any...
3536 */
3537
3538 if ((options = strchr(con->uri, '?')) != NULL)
3539 {
3540 options ++;
3541
3542 if (strchr(options, '='))
3543 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3544 }
3545
3546 /*
3547 * Check for known types...
3548 */
3549
3550 if (!type || strcasecmp(type->super, "application"))
3551 {
3552 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3553 return (0);
3554 }
3555
3556 if (!strcasecmp(type->type, "x-httpd-cgi") &&
3557 (filestats->st_mode & 0111))
3558 {
3559 /*
3560 * "application/x-httpd-cgi" is a CGI script.
3561 */
3562
3563 cupsdSetString(&con->command, filename);
3564
3565 filename = strrchr(filename, '/') + 1; /* Filename always absolute */
3566
3567 cupsdSetString(&con->options, options);
3568
3569 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3570 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3571 con->command, con->options);
3572
3573 return (1);
3574 }
3575 #ifdef HAVE_JAVA
3576 else if (!strcasecmp(type->type, "x-httpd-java"))
3577 {
3578 /*
3579 * "application/x-httpd-java" is a Java servlet.
3580 */
3581
3582 cupsdSetString(&con->command, CUPS_JAVA);
3583
3584 if (options)
3585 cupsdSetStringf(&con->options, " %s %s", filename, options);
3586 else
3587 cupsdSetStringf(&con->options, " %s", filename);
3588
3589 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3590 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3591 con->command, con->options);
3592
3593 return (1);
3594 }
3595 #endif /* HAVE_JAVA */
3596 #ifdef HAVE_PERL
3597 else if (!strcasecmp(type->type, "x-httpd-perl"))
3598 {
3599 /*
3600 * "application/x-httpd-perl" is a Perl page.
3601 */
3602
3603 cupsdSetString(&con->command, CUPS_PERL);
3604
3605 if (options)
3606 cupsdSetStringf(&con->options, " %s %s", filename, options);
3607 else
3608 cupsdSetStringf(&con->options, " %s", filename);
3609
3610 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3611 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3612 con->command, con->options);
3613
3614 return (1);
3615 }
3616 #endif /* HAVE_PERL */
3617 #ifdef HAVE_PHP
3618 else if (!strcasecmp(type->type, "x-httpd-php"))
3619 {
3620 /*
3621 * "application/x-httpd-php" is a PHP page.
3622 */
3623
3624 cupsdSetString(&con->command, CUPS_PHP);
3625
3626 if (options)
3627 cupsdSetStringf(&con->options, " %s %s", filename, options);
3628 else
3629 cupsdSetStringf(&con->options, " %s", filename);
3630
3631 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3632 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3633 con->command, con->options);
3634
3635 return (1);
3636 }
3637 #endif /* HAVE_PHP */
3638 #ifdef HAVE_PYTHON
3639 else if (!strcasecmp(type->type, "x-httpd-python"))
3640 {
3641 /*
3642 * "application/x-httpd-python" is a Python page.
3643 */
3644
3645 cupsdSetString(&con->command, CUPS_PYTHON);
3646
3647 if (options)
3648 cupsdSetStringf(&con->options, " %s %s", filename, options);
3649 else
3650 cupsdSetStringf(&con->options, " %s", filename);
3651
3652 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3653 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3654 con->command, con->options);
3655
3656 return (1);
3657 }
3658 #endif /* HAVE_PYTHON */
3659
3660 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3661
3662 return (0);
3663 }
3664
3665
3666 /*
3667 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3668 */
3669
3670 static int /* O - 0 if relative, 1 if absolute */
3671 is_path_absolute(const char *path) /* I - Input path */
3672 {
3673 /*
3674 * Check for a leading slash...
3675 */
3676
3677 if (path[0] != '/')
3678 return (0);
3679
3680 /*
3681 * Check for "/.." in the path...
3682 */
3683
3684 while ((path = strstr(path, "/..")) != NULL)
3685 {
3686 if (!path[3] || path[3] == '/')
3687 return (0);
3688
3689 path ++;
3690 }
3691
3692 /*
3693 * If we haven't found any relative paths, return 1 indicating an
3694 * absolute path...
3695 */
3696
3697 return (1);
3698 }
3699
3700
3701 #ifdef HAVE_SSL
3702 /*
3703 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3704 */
3705
3706 static int /* O - 1 on success, 0 on failure */
3707 make_certificate(cupsd_client_t *con) /* I - Client connection */
3708 {
3709 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3710 int pid, /* Process ID of command */
3711 status; /* Status of command */
3712 char command[1024], /* Command */
3713 *argv[12], /* Command-line arguments */
3714 *envp[MAX_ENV + 1], /* Environment variables */
3715 home[1024], /* HOME environment variable */
3716 infofile[1024], /* Type-in information for cert */
3717 seedfile[1024]; /* Random number seed file */
3718 int envc, /* Number of environment variables */
3719 bytes; /* Bytes written */
3720 cups_file_t *fp; /* Seed/info file */
3721 int infofd; /* Info file descriptor */
3722
3723
3724 /*
3725 * Run the "openssl" command to seed the random number generator and
3726 * generate a self-signed certificate that is good for 10 years:
3727 *
3728 * openssl rand -rand seedfile 1
3729 *
3730 * openssl req -new -x509 -keyout ServerKey \
3731 * -out ServerCertificate -days 3650 -nodes
3732 *
3733 * The seeding step is crucial in ensuring that the openssl command
3734 * does not block on systems without sufficient entropy...
3735 */
3736
3737 if (!cupsFileFind("openssl", getenv("PATH"), 1, command, sizeof(command)))
3738 {
3739 cupsdLogMessage(CUPSD_LOG_ERROR,
3740 "No SSL certificate and openssl command not found!");
3741 return (0);
3742 }
3743
3744 if (access("/dev/urandom", 0))
3745 {
3746 /*
3747 * If the system doesn't provide /dev/urandom, then any random source
3748 * will probably be blocking-style, so generate some random data to
3749 * use as a seed for the certificate. Note that we have already
3750 * seeded the random number generator in cupsdInitCerts()...
3751 */
3752
3753 cupsdLogMessage(CUPSD_LOG_INFO,
3754 "Seeding the random number generator...");
3755
3756 snprintf(home, sizeof(home), "HOME=%s", TempDir);
3757
3758 /*
3759 * Write the seed file...
3760 */
3761
3762 if ((fp = cupsTempFile2(seedfile, sizeof(seedfile))) == NULL)
3763 {
3764 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create seed file %s - %s",
3765 seedfile, strerror(errno));
3766 return (0);
3767 }
3768
3769 for (bytes = 0; bytes < 262144; bytes ++)
3770 cupsFilePutChar(fp, random());
3771
3772 cupsFileClose(fp);
3773
3774 /*
3775 * Run the openssl command to seed its random number generator...
3776 */
3777
3778 argv[0] = "openssl";
3779 argv[1] = "rand";
3780 argv[2] = "-rand";
3781 argv[3] = seedfile;
3782 argv[4] = "1";
3783 argv[5] = NULL;
3784
3785 envc = cupsdLoadEnv(envp, MAX_ENV);
3786 envp[envc++] = home;
3787 envp[envc] = NULL;
3788
3789 if (!cupsdStartProcess(command, argv, envp, -1, -1, -1, -1, -1, 1, &pid))
3790 {
3791 unlink(seedfile);
3792 return (0);
3793 }
3794
3795 while (waitpid(pid, &status, 0) < 0)
3796 if (errno != EINTR)
3797 {
3798 status = 1;
3799 break;
3800 }
3801
3802 cupsdFinishProcess(pid, command, sizeof(command));
3803
3804 /*
3805 * Remove the seed file, as it is no longer needed...
3806 */
3807
3808 unlink(seedfile);
3809
3810 if (status)
3811 {
3812 if (WIFEXITED(status))
3813 cupsdLogMessage(CUPSD_LOG_ERROR,
3814 "Unable to seed random number generator - "
3815 "the openssl command stopped with status %d!",
3816 WEXITSTATUS(status));
3817 else
3818 cupsdLogMessage(CUPSD_LOG_ERROR,
3819 "Unable to seed random number generator - "
3820 "the openssl command crashed on signal %d!",
3821 WTERMSIG(status));
3822
3823 return (0);
3824 }
3825 }
3826
3827 /*
3828 * Create a file with the certificate information fields...
3829 *
3830 * Note: This assumes that the default questions are asked by the openssl
3831 * command...
3832 */
3833
3834 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
3835 {
3836 cupsdLogMessage(CUPSD_LOG_ERROR,
3837 "Unable to create certificate information file %s - %s",
3838 infofile, strerror(errno));
3839 return (0);
3840 }
3841
3842 cupsFilePrintf(fp, ".\n.\n.\n%s\n.\n%s\n%s\n",
3843 ServerName, ServerName, ServerAdmin);
3844 cupsFileClose(fp);
3845
3846 cupsdLogMessage(CUPSD_LOG_INFO,
3847 "Generating SSL server key and certificate...");
3848
3849 argv[0] = "openssl";
3850 argv[1] = "req";
3851 argv[2] = "-new";
3852 argv[3] = "-x509";
3853 argv[4] = "-keyout";
3854 argv[5] = ServerKey;
3855 argv[6] = "-out";
3856 argv[7] = ServerCertificate;
3857 argv[8] = "-days";
3858 argv[9] = "3650";
3859 argv[10] = "-nodes";
3860 argv[11] = NULL;
3861
3862 cupsdLoadEnv(envp, MAX_ENV);
3863
3864 infofd = open(infofile, O_RDONLY);
3865
3866 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, &pid))
3867 {
3868 close(infofd);
3869 unlink(infofile);
3870 return (0);
3871 }
3872
3873 close(infofd);
3874 unlink(infofile);
3875
3876 while (waitpid(pid, &status, 0) < 0)
3877 if (errno != EINTR)
3878 {
3879 status = 1;
3880 break;
3881 }
3882
3883 cupsdFinishProcess(pid, command, sizeof(command));
3884
3885 if (status)
3886 {
3887 if (WIFEXITED(status))
3888 cupsdLogMessage(CUPSD_LOG_ERROR,
3889 "Unable to create SSL server key and certificate - "
3890 "the openssl command stopped with status %d!",
3891 WEXITSTATUS(status));
3892 else
3893 cupsdLogMessage(CUPSD_LOG_ERROR,
3894 "Unable to create SSL server key and certificate - "
3895 "the openssl command crashed on signal %d!",
3896 WTERMSIG(status));
3897 }
3898 else
3899 {
3900 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
3901 ServerKey);
3902 cupsdLogMessage(CUPSD_LOG_INFO,
3903 "Created SSL server certificate file \"%s\"...",
3904 ServerCertificate);
3905 }
3906
3907 return (!status);
3908
3909 #elif defined(HAVE_GNUTLS)
3910 gnutls_x509_crt crt; /* Self-signed certificate */
3911 gnutls_x509_privkey key; /* Encryption key */
3912 cups_lang_t *language; /* Default language info */
3913 cups_file_t *fp; /* Key/cert file */
3914 unsigned char buffer[8192]; /* Buffer for x509 data */
3915 size_t bytes; /* Number of bytes of data */
3916 unsigned char serial[4]; /* Serial number buffer */
3917 time_t curtime; /* Current time */
3918 int result; /* Result of GNU TLS calls */
3919
3920
3921 /*
3922 * Create the encryption key...
3923 */
3924
3925 cupsdLogMessage(CUPSD_LOG_INFO, "Generating SSL server key...");
3926
3927 gnutls_x509_privkey_init(&key);
3928 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
3929
3930 /*
3931 * Save it...
3932 */
3933
3934 bytes = sizeof(buffer);
3935
3936 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM,
3937 buffer, &bytes)) < 0)
3938 {
3939 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to export SSL server key - %s",
3940 gnutls_strerror(result));
3941 gnutls_x509_privkey_deinit(key);
3942 return (0);
3943 }
3944 else if ((fp = cupsFileOpen(ServerKey, "w")) != NULL)
3945 {
3946 cupsFileWrite(fp, (char *)buffer, bytes);
3947 cupsFileClose(fp);
3948
3949 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
3950 ServerKey);
3951 }
3952 else
3953 {
3954 cupsdLogMessage(CUPSD_LOG_ERROR,
3955 "Unable to create SSL server key file \"%s\" - %s",
3956 ServerKey, strerror(errno));
3957 gnutls_x509_privkey_deinit(key);
3958 return (0);
3959 }
3960
3961 /*
3962 * Create the self-signed certificate...
3963 */
3964
3965 cupsdLogMessage(CUPSD_LOG_INFO, "Generating self-signed SSL certificate...");
3966
3967 language = cupsLangDefault();
3968 curtime = time(NULL);
3969 serial[0] = curtime >> 24;
3970 serial[1] = curtime >> 16;
3971 serial[2] = curtime >> 8;
3972 serial[3] = curtime;
3973
3974 gnutls_x509_crt_init(&crt);
3975 if (strlen(language->language) == 5)
3976 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
3977 language->language + 3, 2);
3978 else
3979 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
3980 "US", 2);
3981 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
3982 ServerName, strlen(ServerName));
3983 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
3984 ServerName, strlen(ServerName));
3985 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
3986 0, "Unknown", 7);
3987 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
3988 "Unknown", 7);
3989 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
3990 "Unknown", 7);
3991 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
3992 ServerAdmin, strlen(ServerAdmin));
3993 gnutls_x509_crt_set_key(crt, key);
3994 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
3995 gnutls_x509_crt_set_activation_time(crt, curtime);
3996 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
3997 gnutls_x509_crt_set_ca_status(crt, 0);
3998 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME,
3999 ServerName);
4000 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
4001 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
4002 gnutls_x509_crt_set_version(crt, 3);
4003
4004 bytes = sizeof(buffer);
4005 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
4006 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
4007
4008 gnutls_x509_crt_sign(crt, crt, key);
4009
4010 /*
4011 * Save it...
4012 */
4013
4014 bytes = sizeof(buffer);
4015 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM,
4016 buffer, &bytes)) < 0)
4017 cupsdLogMessage(CUPSD_LOG_ERROR,
4018 "Unable to export SSL server certificate - %s",
4019 gnutls_strerror(result));
4020 else if ((fp = cupsFileOpen(ServerCertificate, "w")) != NULL)
4021 {
4022 cupsFileWrite(fp, (char *)buffer, bytes);
4023 cupsFileClose(fp);
4024
4025 cupsdLogMessage(CUPSD_LOG_INFO,
4026 "Created SSL server certificate file \"%s\"...",
4027 ServerCertificate);
4028 }
4029 else
4030 cupsdLogMessage(CUPSD_LOG_ERROR,
4031 "Unable to create SSL server certificate file \"%s\" - %s",
4032 ServerCertificate, strerror(errno));
4033
4034 /*
4035 * Cleanup...
4036 */
4037
4038 gnutls_x509_crt_deinit(crt);
4039 gnutls_x509_privkey_deinit(key);
4040
4041 return (1);
4042
4043 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4044 int pid, /* Process ID of command */
4045 status; /* Status of command */
4046 char command[1024], /* Command */
4047 *argv[4], /* Command-line arguments */
4048 *envp[MAX_ENV + 1], /* Environment variables */
4049 keychain[1024], /* Keychain argument */
4050 infofile[1024]; /* Type-in information for cert */
4051 cups_file_t *fp; /* Seed/info file */
4052 int infofd; /* Info file descriptor */
4053
4054
4055 /*
4056 * Run the "certtool" command to generate a self-signed certificate...
4057 */
4058
4059 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
4060 {
4061 cupsdLogMessage(CUPSD_LOG_ERROR,
4062 "No SSL certificate and certtool command not found!");
4063 return (0);
4064 }
4065
4066 /*
4067 * Create a file with the certificate information fields...
4068 *
4069 * Note: This assumes that the default questions are asked by the certtool
4070 * command...
4071 */
4072
4073 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4074 {
4075 cupsdLogMessage(CUPSD_LOG_ERROR,
4076 "Unable to create certificate information file %s - %s",
4077 infofile, strerror(errno));
4078 return (0);
4079 }
4080
4081 cupsFilePrintf(fp, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4082 con->servername, con->servername, ServerAdmin);
4083 cupsFileClose(fp);
4084
4085 cupsdLogMessage(CUPSD_LOG_INFO,
4086 "Generating SSL server key and certificate...");
4087
4088 snprintf(keychain, sizeof(keychain), "k=%s", ServerCertificate);
4089
4090 argv[0] = "certtool";
4091 argv[1] = "c";
4092 argv[2] = keychain;
4093 argv[3] = NULL;
4094
4095 cupsdLoadEnv(envp, MAX_ENV);
4096
4097 infofd = open(infofile, O_RDONLY);
4098
4099 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, &pid))
4100 {
4101 close(infofd);
4102 unlink(infofile);
4103 return (0);
4104 }
4105
4106 close(infofd);
4107 unlink(infofile);
4108
4109 while (waitpid(pid, &status, 0) < 0)
4110 if (errno != EINTR)
4111 {
4112 status = 1;
4113 break;
4114 }
4115
4116 cupsdFinishProcess(pid, command, sizeof(command));
4117
4118 if (status)
4119 {
4120 if (WIFEXITED(status))
4121 cupsdLogMessage(CUPSD_LOG_ERROR,
4122 "Unable to create SSL server key and certificate - "
4123 "the certtool command stopped with status %d!",
4124 WEXITSTATUS(status));
4125 else
4126 cupsdLogMessage(CUPSD_LOG_ERROR,
4127 "Unable to create SSL server key and certificate - "
4128 "the certtool command crashed on signal %d!",
4129 WTERMSIG(status));
4130 }
4131 else
4132 {
4133 cupsdLogMessage(CUPSD_LOG_INFO,
4134 "Created SSL server certificate file \"%s\"...",
4135 ServerCertificate);
4136 }
4137
4138 return (!status);
4139
4140 #else
4141 return (0);
4142 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4143 }
4144 #endif /* HAVE_SSL */
4145
4146
4147 /*
4148 * 'pipe_command()' - Pipe the output of a command to the remote client.
4149 */
4150
4151 static int /* O - Process ID */
4152 pipe_command(cupsd_client_t *con, /* I - Client connection */
4153 int infile, /* I - Standard input for command */
4154 int *outfile, /* O - Standard output for command */
4155 char *command, /* I - Command to run */
4156 char *options, /* I - Options for command */
4157 int root) /* I - Run as root? */
4158 {
4159 int i; /* Looping var */
4160 int pid; /* Process ID */
4161 char *commptr, /* Command string pointer */
4162 commch; /* Command string character */
4163 char *uriptr; /* URI string pointer */
4164 int fds[2]; /* Pipe FDs */
4165 int argc; /* Number of arguments */
4166 int envc; /* Number of environment variables */
4167 char argbuf[10240], /* Argument buffer */
4168 *argv[100], /* Argument strings */
4169 *envp[MAX_ENV + 20]; /* Environment variables */
4170 char auth_type[256], /* AUTH_TYPE environment variable */
4171 content_length[1024], /* CONTENT_LENGTH environment variable */
4172 content_type[1024], /* CONTENT_TYPE environment variable */
4173 http_cookie[32768], /* HTTP_COOKIE environment variable */
4174 http_referer[1024], /* HTTP_REFERER environment variable */
4175 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
4176 lang[1024], /* LANG environment variable */
4177 path_info[1024], /* PATH_INFO environment variable */
4178 remote_addr[1024], /* REMOTE_ADDR environment variable */
4179 remote_host[1024], /* REMOTE_HOST environment variable */
4180 remote_user[1024], /* REMOTE_USER environment variable */
4181 script_filename[1024], /* SCRIPT_FILENAME environment variable */
4182 script_name[1024], /* SCRIPT_NAME environment variable */
4183 server_name[1024], /* SERVER_NAME environment variable */
4184 server_port[1024]; /* SERVER_PORT environment variable */
4185
4186
4187 /*
4188 * Parse a copy of the options string, which is of the form:
4189 *
4190 * argument+argument+argument
4191 * ?argument+argument+argument
4192 * param=value&param=value
4193 * ?param=value&param=value
4194 * /name?argument+argument+argument
4195 * /name?param=value&param=value
4196 *
4197 * If the string contains an "=" character after the initial name,
4198 * then we treat it as a HTTP GET form request and make a copy of
4199 * the remaining string for the environment variable.
4200 *
4201 * The string is always parsed out as command-line arguments, to
4202 * be consistent with Apache...
4203 */
4204
4205 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4206 "pipe_command: command=\"%s\", options=\"%s\"",
4207 command, options ? options : "(null)");
4208
4209 argv[0] = command;
4210
4211 if (options)
4212 strlcpy(argbuf, options, sizeof(argbuf));
4213 else
4214 argbuf[0] = '\0';
4215
4216 if (argbuf[0] == '/')
4217 {
4218 /*
4219 * Found some trailing path information, set PATH_INFO...
4220 */
4221
4222 if ((commptr = strchr(argbuf, '?')) == NULL)
4223 commptr = argbuf + strlen(argbuf);
4224
4225 commch = *commptr;
4226 *commptr = '\0';
4227 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
4228 *commptr = commch;
4229 }
4230 else
4231 {
4232 commptr = argbuf;
4233 path_info[0] = '\0';
4234
4235 if (*commptr == ' ')
4236 commptr ++;
4237 }
4238
4239 cupsdLogMessage(CUPSD_LOG_INFO, "commptr=\"%s\"", commptr);
4240
4241 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
4242 {
4243 commptr ++;
4244 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
4245 }
4246
4247 argc = 1;
4248
4249 if (*commptr)
4250 {
4251 argv[argc ++] = commptr;
4252
4253 for (; *commptr && argc < 99; commptr ++)
4254 {
4255 /*
4256 * Break arguments whenever we see a + or space...
4257 */
4258
4259 if (*commptr == ' ' || *commptr == '+')
4260 {
4261 while (*commptr == ' ' || *commptr == '+')
4262 *commptr++ = '\0';
4263
4264 /*
4265 * If we don't have a blank string, save it as another argument...
4266 */
4267
4268 if (*commptr)
4269 {
4270 argv[argc] = commptr;
4271 argc ++;
4272 }
4273 else
4274 break;
4275 }
4276 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
4277 isxdigit(commptr[2] & 255))
4278 {
4279 /*
4280 * Convert the %xx notation to the individual character.
4281 */
4282
4283 if (commptr[1] >= '0' && commptr[1] <= '9')
4284 *commptr = (commptr[1] - '0') << 4;
4285 else
4286 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
4287
4288 if (commptr[2] >= '0' && commptr[2] <= '9')
4289 *commptr |= commptr[2] - '0';
4290 else
4291 *commptr |= tolower(commptr[2]) - 'a' + 10;
4292
4293 _cups_strcpy(commptr + 1, commptr + 3);
4294
4295 /*
4296 * Check for a %00 and break if that is the case...
4297 */
4298
4299 if (!*commptr)
4300 break;
4301 }
4302 }
4303 }
4304
4305 argv[argc] = NULL;
4306
4307 /*
4308 * Setup the environment variables as needed...
4309 */
4310
4311 if (con->username[0])
4312 {
4313 snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
4314 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
4315
4316 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
4317 *uriptr = '\0';
4318 }
4319 else
4320 auth_type[0] = '\0';
4321
4322 if (con->language)
4323 snprintf(lang, sizeof(lang), "LANG=%s.UTF-8", con->language->language);
4324 else
4325 strcpy(lang, "LANG=C");
4326
4327 strcpy(remote_addr, "REMOTE_ADDR=");
4328 httpAddrString(con->http.hostaddr, remote_addr + 12,
4329 sizeof(remote_addr) - 12);
4330
4331 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
4332 con->http.hostname);
4333
4334 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
4335 if ((uriptr = strchr(script_name, '?')) != NULL)
4336 *uriptr = '\0';
4337
4338 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
4339 DocumentRoot, script_name + 12);
4340
4341 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
4342
4343 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
4344 con->servername);
4345
4346 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
4347
4348 if (auth_type[0])
4349 envp[envc ++] = auth_type;
4350
4351 envp[envc ++] = lang;
4352 envp[envc ++] = "REDIRECT_STATUS=1";
4353 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
4354 envp[envc ++] = server_name;
4355 envp[envc ++] = server_port;
4356 envp[envc ++] = remote_addr;
4357 envp[envc ++] = remote_host;
4358 envp[envc ++] = script_name;
4359 envp[envc ++] = script_filename;
4360
4361 if (path_info[0])
4362 envp[envc ++] = path_info;
4363
4364 if (con->username[0])
4365 {
4366 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
4367
4368 envp[envc ++] = remote_user;
4369 }
4370
4371 if (con->http.version == HTTP_1_1)
4372 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
4373 else if (con->http.version == HTTP_1_0)
4374 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
4375 else
4376 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
4377
4378 if (con->http.cookie)
4379 {
4380 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
4381 con->http.cookie);
4382 envp[envc ++] = http_cookie;
4383 }
4384
4385 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
4386 {
4387 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
4388 con->http.fields[HTTP_FIELD_USER_AGENT]);
4389 envp[envc ++] = http_user_agent;
4390 }
4391
4392 if (con->http.fields[HTTP_FIELD_REFERER][0])
4393 {
4394 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
4395 con->http.fields[HTTP_FIELD_REFERER]);
4396 envp[envc ++] = http_referer;
4397 }
4398
4399 if (con->operation == HTTP_GET)
4400 {
4401 envp[envc ++] = "REQUEST_METHOD=GET";
4402
4403 if (con->query_string)
4404 {
4405 /*
4406 * Add GET form variables after ?...
4407 */
4408
4409 envp[envc ++] = con->query_string;
4410 }
4411 }
4412 else
4413 {
4414 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
4415 CUPS_LLCAST con->bytes);
4416 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
4417 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
4418
4419 envp[envc ++] = "REQUEST_METHOD=POST";
4420 envp[envc ++] = content_length;
4421 envp[envc ++] = content_type;
4422 }
4423
4424 /*
4425 * Tell the CGI if we are using encryption...
4426 */
4427
4428 if (con->http.tls)
4429 envp[envc ++] = "HTTPS=ON";
4430
4431 /*
4432 * Terminate the environment array...
4433 */
4434
4435 envp[envc] = NULL;
4436
4437 if (LogLevel == CUPSD_LOG_DEBUG2)
4438 {
4439 for (i = 0; i < argc; i ++)
4440 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4441 "pipe_command: argv[%d] = \"%s\"", i, argv[i]);
4442 for (i = 0; i < envc; i ++)
4443 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4444 "pipe_command: envp[%d] = \"%s\"", i, envp[i]);
4445 }
4446
4447 /*
4448 * Create a pipe for the output...
4449 */
4450
4451 if (cupsdOpenPipe(fds))
4452 {
4453 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create pipes for CGI %s - %s",
4454 argv[0], strerror(errno));
4455 return (0);
4456 }
4457
4458 /*
4459 * Then execute the command...
4460 */
4461
4462 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
4463 -1, -1, root, &pid) < 0)
4464 {
4465 /*
4466 * Error - can't fork!
4467 */
4468
4469 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork for CGI %s - %s", argv[0],
4470 strerror(errno));
4471
4472 cupsdClosePipe(fds);
4473 pid = 0;
4474 }
4475 else
4476 {
4477 /*
4478 * Fork successful - return the PID...
4479 */
4480
4481 if (con->username[0])
4482 cupsdAddCert(pid, con->username);
4483
4484 cupsdLogMessage(CUPSD_LOG_DEBUG, "CGI %s started - PID = %d", command, pid);
4485
4486 *outfile = fds[0];
4487 close(fds[1]);
4488 }
4489
4490 return (pid);
4491 }
4492
4493
4494 /*
4495 * 'write_file()' - Send a file via HTTP.
4496 */
4497
4498 static int /* O - 0 on failure, 1 on success */
4499 write_file(cupsd_client_t *con, /* I - Client connection */
4500 http_status_t code, /* I - HTTP status */
4501 char *filename, /* I - Filename */
4502 char *type, /* I - File type */
4503 struct stat *filestats) /* O - File information */
4504 {
4505 con->file = open(filename, O_RDONLY);
4506
4507 cupsdLogMessage(CUPSD_LOG_DEBUG, "write_file: %d file=%d", con->http.fd,
4508 con->file);
4509
4510 if (con->file < 0)
4511 return (0);
4512
4513 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4514
4515 con->pipe_pid = 0;
4516
4517 if (!cupsdSendHeader(con, code, type, AUTH_NONE))
4518 return (0);
4519
4520 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
4521 httpGetDateString(filestats->st_mtime)) < 0)
4522 return (0);
4523 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
4524 CUPS_LLCAST filestats->st_size) < 0)
4525 return (0);
4526 if (httpPrintf(HTTP(con), "\r\n") < 0)
4527 return (0);
4528
4529 if (cupsdFlushHeader(con) < 0)
4530 return (0);
4531
4532 con->http.data_encoding = HTTP_ENCODE_LENGTH;
4533 con->http.data_remaining = filestats->st_size;
4534
4535 if (con->http.data_remaining <= INT_MAX)
4536 con->http._data_remaining = con->http.data_remaining;
4537 else
4538 con->http._data_remaining = INT_MAX;
4539
4540 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
4541 (cupsd_selfunc_t)cupsdWriteClient, con);
4542
4543 return (1);
4544 }
4545
4546
4547 /*
4548 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4549 */
4550
4551 static void
4552 write_pipe(cupsd_client_t *con) /* I - Client connection */
4553 {
4554 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d...",
4555 con->file);
4556
4557 con->file_ready = 1;
4558
4559 cupsdRemoveSelect(con->file);
4560 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4561 }
4562
4563
4564 /*
4565 * End of "$Id: client.c 6504 2007-05-02 00:14:56Z mike $".
4566 */