]> 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 4950 2006-01-19 16:07:57Z mike $"
3 *
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
5 *
6 * Copyright 1997-2006 by Easy Software Products, all rights reserved.
7 *
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
13 * at:
14 *
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
19 *
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
23 *
24 * Contents:
25 *
26 * cupsdAcceptClient() - Accept a new client.
27 * cupsdCloseAllClients() - Close all remote clients immediately.
28 * cupsdCloseClient() - Close a remote client.
29 * cupsdEncryptClient() - Enable encryption for the client...
30 * cupsdIsCGI() - Is the resource a CGI script/program?
31 * cupsdReadClient() - Read data from a client.
32 * cupsdSendCommand() - Send output from a command via HTTP.
33 * cupsdSendError() - Send an error message via HTTP.
34 * cupsdSendFile() - Send a file via HTTP.
35 * cupsdSendHeader() - Send an HTTP request.
36 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
37 * cupsdWriteClient() - Write data to a client as needed.
38 * check_if_modified() - Decode an "If-Modified-Since" line.
39 * get_cdsa_server_certs() - Convert a keychain name into the CFArrayRef
40 * required by SSLSetCertificate.
41 * get_file() - Get a filename and state info.
42 * install_conf_file() - Install a configuration file.
43 * is_path_absolute() - Is a path absolute and free of relative elements.
44 * pipe_command() - Pipe the output of a command to the remote client.
45 */
46
47 /*
48 * Include necessary headers...
49 */
50
51 #include <cups/http-private.h>
52 #include "cupsd.h"
53
54 #ifdef HAVE_CDSASSL
55 # include <Security/Security.h>
56 #endif /* HAVE_CDSASSL */
57
58
59 /*
60 * Local functions...
61 */
62
63 static int check_if_modified(cupsd_client_t *con,
64 struct stat *filestats);
65 #ifdef HAVE_CDSASSL
66 static CFArrayRef get_cdsa_server_certs(void);
67 #endif /* HAVE_CDSASSL */
68 static char *get_file(cupsd_client_t *con, struct stat *filestats,
69 char *filename, int len);
70 static http_status_t install_conf_file(cupsd_client_t *con);
71 static int is_path_absolute(const char *path);
72 static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
73 char *command, char *options, int root);
74
75
76 /*
77 * 'cupsdAcceptClient()' - Accept a new client.
78 */
79
80 void
81 cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
82 {
83 int i; /* Looping var */
84 int count; /* Count of connections on a host */
85 int val; /* Parameter value */
86 cupsd_client_t *con; /* New client pointer */
87 http_addrlist_t *addrlist, /* List of adddresses for host */
88 *addr; /* Current address */
89 socklen_t addrlen; /* Length of address */
90 char *hostname; /* Hostname for address */
91 http_addr_t temp; /* Temporary address variable */
92 static time_t last_dos = 0; /* Time of last DoS attack */
93
94
95 cupsdLogMessage(CUPSD_LOG_DEBUG2,
96 "cupsdAcceptClient(lis=%p) %d NumClients = %d",
97 lis, lis->fd, NumClients);
98
99 /*
100 * Make sure we don't have a full set of clients already...
101 */
102
103 if (NumClients == MaxClients)
104 return;
105
106 /*
107 * Get a pointer to the next available client...
108 */
109
110 con = Clients + NumClients;
111
112 memset(con, 0, sizeof(cupsd_client_t));
113 con->http.activity = time(NULL);
114 con->file = -1;
115 con->http.hostaddr = &(con->clientaddr);
116
117 /*
118 * Accept the client and get the remote address...
119 */
120
121 addrlen = sizeof(http_addr_t);
122
123 if ((con->http.fd = accept(lis->fd, (struct sockaddr *)con->http.hostaddr,
124 &addrlen)) < 0)
125 {
126 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
127 strerror(errno));
128 return;
129 }
130
131 #ifdef AF_INET6
132 if (lis->address.addr.sa_family == AF_INET6)
133 {
134 /*
135 * Save the connected port number...
136 */
137
138 con->http.hostaddr->ipv6.sin6_port = lis->address.ipv6.sin6_port;
139
140 /*
141 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
142 * can more easily use...
143 */
144
145 if (con->http.hostaddr->ipv6.sin6_addr.s6_addr32[0] == 0 &&
146 con->http.hostaddr->ipv6.sin6_addr.s6_addr32[1] == 0 &&
147 ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2]) == 0xffff)
148 con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2] = 0;
149 }
150 else
151 #endif /* AF_INET6 */
152 if (lis->address.addr.sa_family == AF_INET)
153 con->http.hostaddr->ipv4.sin_port = lis->address.ipv4.sin_port;
154
155 /*
156 * Check the number of clients on the same address...
157 */
158
159 for (i = 0, count = 0; i < NumClients; i ++)
160 if (httpAddrEqual(Clients[i].http.hostaddr, con->http.hostaddr))
161 {
162 count ++;
163 if (count >= MaxClientsPerHost)
164 break;
165 }
166
167 if (count >= MaxClientsPerHost)
168 {
169 if ((time(NULL) - last_dos) >= 60)
170 {
171 last_dos = time(NULL);
172 cupsdLogMessage(CUPSD_LOG_WARN,
173 "Possible DoS attack - more than %d clients connecting from %s!",
174 MaxClientsPerHost, Clients[i].http.hostname);
175 }
176
177 #ifdef WIN32
178 closesocket(con->http.fd);
179 #else
180 close(con->http.fd);
181 #endif /* WIN32 */
182
183 return;
184 }
185
186 /*
187 * Get the hostname or format the IP address as needed...
188 */
189
190 if (httpAddrLocalhost(con->http.hostaddr))
191 {
192 /*
193 * Map accesses from the loopback interface to "localhost"...
194 */
195
196 strlcpy(con->http.hostname, "localhost", sizeof(con->http.hostname));
197 hostname = con->http.hostname;
198 }
199 else
200 {
201 /*
202 * Map accesses from the same host to the server name.
203 */
204
205 for (addr = ServerAddrs; addr; addr = addr->next)
206 if (httpAddrEqual(con->http.hostaddr, &(addr->addr)))
207 break;
208
209 if (addr)
210 {
211 strlcpy(con->http.hostname, ServerName, sizeof(con->http.hostname));
212 hostname = con->http.hostname;
213 }
214 else if (HostNameLookups)
215 hostname = httpAddrLookup(con->http.hostaddr, con->http.hostname,
216 sizeof(con->http.hostname));
217 else
218 {
219 hostname = NULL;
220 httpAddrString(con->http.hostaddr, con->http.hostname,
221 sizeof(con->http.hostname));
222 }
223 }
224
225 if (hostname == NULL && HostNameLookups == 2)
226 {
227 /*
228 * Can't have an unresolved IP address with double-lookups enabled...
229 */
230
231 cupsdLogMessage(CUPSD_LOG_DEBUG2,
232 "cupsdAcceptClient: Closing connection %d...",
233 con->http.fd);
234
235 #ifdef WIN32
236 closesocket(con->http.fd);
237 #else
238 close(con->http.fd);
239 #endif /* WIN32 */
240
241 cupsdLogMessage(CUPSD_LOG_WARN,
242 "Name lookup failed - connection from %s closed!",
243 con->http.hostname);
244 return;
245 }
246
247 if (HostNameLookups == 2)
248 {
249 /*
250 * Do double lookups as needed...
251 */
252
253 if ((addrlist = httpAddrGetList(con->http.hostname, AF_UNSPEC, NULL)) != NULL)
254 {
255 /*
256 * See if the hostname maps to the same IP address...
257 */
258
259 for (addr = addrlist; addr; addr = addr->next)
260 if (httpAddrEqual(con->http.hostaddr, &(addr->addr)))
261 break;
262 }
263 else
264 addr = NULL;
265
266 httpAddrFreeList(addrlist);
267
268 if (!addr)
269 {
270 /*
271 * Can't have a hostname that doesn't resolve to the same IP address
272 * with double-lookups enabled...
273 */
274
275 cupsdLogMessage(CUPSD_LOG_DEBUG2,
276 "cupsdAcceptClient: Closing connection %d...",
277 con->http.fd);
278
279 #ifdef WIN32
280 closesocket(con->http.fd);
281 #else
282 close(con->http.fd);
283 #endif /* WIN32 */
284
285 cupsdLogMessage(CUPSD_LOG_WARN,
286 "IP lookup failed - connection from %s closed!",
287 con->http.hostname);
288 return;
289 }
290 }
291
292 #ifdef AF_INET6
293 if (con->http.hostaddr->addr.sa_family == AF_INET6)
294 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s:%d (IPv6)",
295 con->http.fd, con->http.hostname,
296 ntohs(con->http.hostaddr->ipv6.sin6_port));
297 else
298 #endif /* AF_INET6 */
299 #ifdef AF_LOCAL
300 if (con->http.hostaddr->addr.sa_family == AF_LOCAL)
301 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s (Domain)",
302 con->http.fd, con->http.hostname);
303 else
304 #endif /* AF_LOCAL */
305 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s:%d (IPv4)",
306 con->http.fd, con->http.hostname,
307 ntohs(con->http.hostaddr->ipv4.sin_port));
308
309 /*
310 * Get the local address the client connected to...
311 */
312
313 addrlen = sizeof(temp);
314 if (getsockname(con->http.fd, (struct sockaddr *)&temp, &addrlen))
315 {
316 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get local address - %s",
317 strerror(errno));
318
319 strcpy(con->servername, "localhost");
320 con->serverport = LocalPort;
321 }
322 else
323 {
324 #ifdef AF_INET6
325 if (temp.addr.sa_family == AF_INET6)
326 {
327 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
328 con->serverport = ntohs(lis->address.ipv6.sin6_port);
329 }
330 else
331 #endif /* AF_INET6 */
332 if (temp.addr.sa_family == AF_INET)
333 {
334 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
335 con->serverport = ntohs(lis->address.ipv4.sin_port);
336 }
337 else
338 {
339 strcpy(con->servername, "localhost");
340 con->serverport = LocalPort;
341 }
342 }
343
344 cupsdLogMessage(CUPSD_LOG_DEBUG2,
345 "cupsdAcceptClient: %d connected to server on %s:%d",
346 con->http.fd, con->servername, con->serverport);
347
348 /*
349 * Using TCP_NODELAY improves responsiveness, especially on systems
350 * with a slow loopback interface... Since we write large buffers
351 * when sending print files and requests, there shouldn't be any
352 * performance penalty for this...
353 */
354
355 val = 1;
356 setsockopt(con->http.fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
357
358 /*
359 * Close this file on all execs...
360 */
361
362 fcntl(con->http.fd, F_SETFD, fcntl(con->http.fd, F_GETFD) | FD_CLOEXEC);
363
364 /*
365 * Add the socket to the select() input mask.
366 */
367
368 cupsdLogMessage(CUPSD_LOG_DEBUG2,
369 "cupsdAcceptClient: Adding fd %d to InputSet...",
370 con->http.fd);
371 FD_SET(con->http.fd, InputSet);
372
373 NumClients ++;
374
375 /*
376 * Temporarily suspend accept()'s until we lose a client...
377 */
378
379 if (NumClients == MaxClients)
380 cupsdPauseListening();
381
382 #ifdef HAVE_SSL
383 /*
384 * See if we are connecting on a secure port...
385 */
386
387 if (lis->encryption == HTTP_ENCRYPT_ALWAYS)
388 {
389 /*
390 * https connection; go secure...
391 */
392
393 con->http.encryption = HTTP_ENCRYPT_ALWAYS;
394
395 cupsdEncryptClient(con);
396 }
397 else
398 con->auto_ssl = 1;
399 #endif /* HAVE_SSL */
400 }
401
402
403 /*
404 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
405 */
406
407 void
408 cupsdCloseAllClients(void)
409 {
410 while (NumClients > 0)
411 cupsdCloseClient(Clients);
412 }
413
414
415 /*
416 * 'cupsdCloseClient()' - Close a remote client.
417 */
418
419 int /* O - 1 if partial close, 0 if fully closed */
420 cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
421 {
422 int partial; /* Do partial close for SSL? */
423 #ifdef HAVE_LIBSSL
424 SSL_CTX *context; /* Context for encryption */
425 SSL *conn; /* Connection for encryption */
426 unsigned long error; /* Error code */
427 #elif defined(HAVE_GNUTLS)
428 http_tls_t *conn; /* TLS connection information */
429 int error; /* Error code */
430 gnutls_certificate_server_credentials *credentials;
431 /* TLS credentials */
432 #endif /* HAVE_LIBSSL */
433
434
435 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdCloseClient: %d", con->http.fd);
436
437 /*
438 * Flush pending writes before closing...
439 */
440
441 httpFlushWrite(HTTP(con));
442
443 partial = 0;
444
445 #ifdef HAVE_SSL
446 /*
447 * Shutdown encryption as needed...
448 */
449
450 if (con->http.tls)
451 {
452 partial = 1;
453
454 # ifdef HAVE_LIBSSL
455 conn = (SSL *)(con->http.tls);
456 context = SSL_get_SSL_CTX(conn);
457
458 switch (SSL_shutdown(conn))
459 {
460 case 1 :
461 cupsdLogMessage(CUPSD_LOG_INFO,
462 "cupsdCloseClient: SSL shutdown successful!");
463 break;
464 case -1 :
465 cupsdLogMessage(CUPSD_LOG_ERROR,
466 "cupsdCloseClient: Fatal error during SSL shutdown!");
467 default :
468 while ((error = ERR_get_error()) != 0)
469 cupsdLogMessage(CUPSD_LOG_ERROR, "cupsdCloseClient: %s",
470 ERR_error_string(error, NULL));
471 break;
472 }
473
474 SSL_CTX_free(context);
475 SSL_free(conn);
476
477 # elif defined(HAVE_GNUTLS)
478 conn = (http_tls_t *)(con->http.tls);
479 credentials = (gnutls_certificate_server_credentials *)(conn->credentials);
480
481 error = gnutls_bye(conn->session, GNUTLS_SHUT_WR);
482 switch (error)
483 {
484 case GNUTLS_E_SUCCESS:
485 cupsdLogMessage(CUPSD_LOG_INFO,
486 "cupsdCloseClient: SSL shutdown successful!");
487 break;
488 default:
489 cupsdLogMessage(CUPSD_LOG_ERROR,
490 "cupsdCloseClient: %s", gnutls_strerror(error));
491 break;
492 }
493
494 gnutls_deinit(conn->session);
495 gnutls_certificate_free_credentials(*credentials);
496 free(credentials);
497 free(conn);
498
499 # elif defined(HAVE_CDSASSL)
500 SSLClose((SSLContextRef)con->http.tls);
501 SSLDisposeContext((SSLContextRef)con->http.tls);
502 # endif /* HAVE_LIBSSL */
503
504 con->http.tls = NULL;
505 }
506 #endif /* HAVE_SSL */
507
508 if (con->pipe_pid != 0)
509 {
510 /*
511 * Stop any CGI process...
512 */
513
514 cupsdLogMessage(CUPSD_LOG_DEBUG2,
515 "cupsdCloseClient: %d Killing process ID %d...",
516 con->http.fd, con->pipe_pid);
517 cupsdEndProcess(con->pipe_pid, 1);
518 con->pipe_pid = 0;
519 }
520
521 if (con->file >= 0)
522 {
523 if (FD_ISSET(con->file, InputSet))
524 {
525 cupsdLogMessage(CUPSD_LOG_DEBUG2,
526 "cupsdCloseClient: %d Removing fd %d from InputSet...",
527 con->http.fd, con->file);
528 FD_CLR(con->file, InputSet);
529 }
530
531 cupsdLogMessage(CUPSD_LOG_DEBUG2,
532 "cupsdCloseClient: %d Closing data file %d.",
533 con->http.fd, con->file);
534
535 close(con->file);
536 con->file = -1;
537 }
538
539 /*
540 * Close the socket and clear the file from the input set for select()...
541 */
542
543 if (con->http.fd > 0)
544 {
545 if (partial)
546 {
547 /*
548 * Only do a partial close so that the encrypted client gets everything.
549 */
550
551 cupsdLogMessage(CUPSD_LOG_DEBUG2,
552 "cupsdCloseClient: Removing fd %d from OutputSet...",
553 con->http.fd);
554 shutdown(con->http.fd, 0);
555 FD_CLR(con->http.fd, OutputSet);
556 }
557 else
558 {
559 /*
560 * Shut the socket down fully...
561 */
562
563 cupsdLogMessage(CUPSD_LOG_DEBUG2,
564 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
565 con->http.fd);
566 close(con->http.fd);
567 FD_CLR(con->http.fd, InputSet);
568 FD_CLR(con->http.fd, OutputSet);
569 con->http.fd = -1;
570 }
571 }
572
573 if (!partial)
574 {
575 /*
576 * Free memory...
577 */
578
579 if (con->http.input_set)
580 free(con->http.input_set);
581
582 httpClearCookie(HTTP(con));
583
584 cupsdClearString(&con->filename);
585 cupsdClearString(&con->command);
586 cupsdClearString(&con->options);
587
588 if (con->request)
589 {
590 ippDelete(con->request);
591 con->request = NULL;
592 }
593
594 if (con->response)
595 {
596 ippDelete(con->response);
597 con->response = NULL;
598 }
599
600 if (con->language)
601 {
602 cupsLangFree(con->language);
603 con->language = NULL;
604 }
605
606 /*
607 * Re-enable new client connections if we are going back under the
608 * limit...
609 */
610
611 if (NumClients == MaxClients)
612 cupsdResumeListening();
613
614 /*
615 * Compact the list of clients as necessary...
616 */
617
618 NumClients --;
619
620 if (con < (Clients + NumClients))
621 memmove(con, con + 1, (Clients + NumClients - con) * sizeof(cupsd_client_t));
622 }
623
624 return (partial);
625 }
626
627
628 /*
629 * 'cupsdEncryptClient()' - Enable encryption for the client...
630 */
631
632 int /* O - 1 on success, 0 on error */
633 cupsdEncryptClient(cupsd_client_t *con) /* I - Client to encrypt */
634 {
635 #ifdef HAVE_LIBSSL
636 SSL_CTX *context; /* Context for encryption */
637 SSL *conn; /* Connection for encryption */
638 unsigned long error; /* Error code */
639
640
641 /*
642 * Create the SSL context and accept the connection...
643 */
644
645 context = SSL_CTX_new(SSLv23_server_method());
646
647 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
648 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
649 SSL_CTX_use_certificate_file(context, ServerCertificate, SSL_FILETYPE_PEM);
650
651 conn = SSL_new(context);
652
653 SSL_set_fd(conn, con->http.fd);
654 if (SSL_accept(conn) != 1)
655 {
656 cupsdLogMessage(CUPSD_LOG_ERROR,
657 "cupsdEncryptClient: Unable to encrypt connection from %s!",
658 con->http.hostname);
659
660 while ((error = ERR_get_error()) != 0)
661 cupsdLogMessage(CUPSD_LOG_ERROR, "cupsdEncryptClient: %s",
662 ERR_error_string(error, NULL));
663
664 SSL_CTX_free(context);
665 SSL_free(conn);
666 return (0);
667 }
668
669 cupsdLogMessage(CUPSD_LOG_DEBUG,
670 "cupsdEncryptClient: %d Connection from %s now encrypted.",
671 con->http.fd, con->http.hostname);
672
673 con->http.tls = conn;
674 return (1);
675
676 #elif defined(HAVE_GNUTLS)
677 http_tls_t *conn; /* TLS session object */
678 int error; /* Error code */
679 gnutls_certificate_server_credentials *credentials;
680 /* TLS credentials */
681
682 /*
683 * Create the SSL object and perform the SSL handshake...
684 */
685
686 conn = (http_tls_t *)malloc(sizeof(gnutls_session));
687
688 if (conn == NULL)
689 return (0);
690
691 credentials = (gnutls_certificate_server_credentials *)
692 malloc(sizeof(gnutls_certificate_server_credentials));
693 if (credentials == NULL)
694 {
695 cupsdLogMessage(CUPSD_LOG_ERROR,
696 "cupsdEncryptClient: Unable to encrypt connection from %s!",
697 con->http.hostname);
698 cupsdLogMessage(CUPSD_LOG_ERROR, "cupsdEncryptClient: %s", strerror(errno));
699
700 free(conn);
701 return (0);
702 }
703
704 gnutls_certificate_allocate_credentials(credentials);
705 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
706 ServerKey, GNUTLS_X509_FMT_PEM);
707
708 gnutls_init(&(conn->session), GNUTLS_SERVER);
709 gnutls_set_default_priority(conn->session);
710 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
711 gnutls_transport_set_ptr(conn->session, con->http.fd);
712
713 error = gnutls_handshake(conn->session);
714
715 if (error != GNUTLS_E_SUCCESS)
716 {
717 cupsdLogMessage(CUPSD_LOG_ERROR,
718 "cupsdEncryptClient: Unable to encrypt connection from %s!",
719 con->http.hostname);
720 cupsdLogMessage(CUPSD_LOG_ERROR, "cupsdEncryptClient: %s",
721 gnutls_strerror(error));
722
723 gnutls_deinit(conn->session);
724 gnutls_certificate_free_credentials(*credentials);
725 free(conn);
726 free(credentials);
727 return (0);
728 }
729
730 cupsdLogMessage(CUPSD_LOG_DEBUG,
731 "cupsdEncryptClient: %d Connection from %s now encrypted.",
732 con->http.fd, con->http.hostname);
733
734 conn->credentials = credentials;
735 con->http.tls = conn;
736 return (1);
737
738 #elif defined(HAVE_CDSASSL)
739 OSStatus error; /* Error info */
740 SSLContextRef conn; /* New connection */
741 int allowExpired; /* Allow expired certificates? */
742 int allowAnyRoot; /* Allow any root certificate? */
743
744
745 conn = NULL;
746 error = SSLNewContext(true, &conn);
747 allowExpired = 1;
748 allowAnyRoot = 1;
749
750 if (!ServerCertificatesArray)
751 ServerCertificatesArray = get_cdsa_server_certs();
752
753 if (!ServerCertificatesArray)
754 {
755 cupsdLogMessage(CUPSD_LOG_ERROR,
756 "EncryptClient: Could not find signing key in keychain "
757 "\"%s\"", ServerCertificate);
758 error = errSSLBadConfiguration;
759 }
760
761 if (!error)
762 error = SSLSetIOFuncs(conn, _httpReadCDSA, _httpWriteCDSA);
763
764 if (!error)
765 error = SSLSetProtocolVersion(conn, kSSLProtocol3);
766
767 if (!error)
768 error = SSLSetConnection(conn, (SSLConnectionRef)con->http.fd);
769
770 if (!error)
771 error = SSLSetPeerDomainName(conn, ServerName, strlen(ServerName) + 1);
772
773 /* have to do these options before setting server certs */
774 if (!error && allowExpired)
775 error = SSLSetAllowsExpiredCerts(conn, true);
776
777 if (!error && allowAnyRoot)
778 error = SSLSetAllowsAnyRoot(conn, true);
779
780 if (!error && ServerCertificatesArray)
781 {
782 error = SSLSetCertificate(conn, ServerCertificatesArray);
783
784 /*
785 * Perform SSL/TLS handshake
786 */
787
788 if (!error)
789 {
790 do
791 {
792 error = SSLHandshake(conn);
793 }
794 while (error == errSSLWouldBlock);
795 }
796 }
797
798 if (error)
799 {
800 cupsdLogMessage(CUPSD_LOG_ERROR,
801 "cupsdEncryptClient: Unable to encrypt connection from %s!",
802 con->http.hostname);
803
804 cupsdLogMessage(CUPSD_LOG_ERROR,
805 "cupsdEncryptClient: CDSA error code is %d", (int)error);
806
807 con->http.error = error;
808 con->http.status = HTTP_ERROR;
809
810 if (conn != NULL)
811 SSLDisposeContext(conn);
812
813 return (0);
814 }
815
816 cupsdLogMessage(CUPSD_LOG_DEBUG,
817 "cupsdEncryptClient: %d Connection from %s now encrypted.",
818 con->http.fd, con->http.hostname);
819
820 con->http.tls = conn;
821 return (1);
822
823 #else
824 return (0);
825 #endif /* HAVE_LIBSSL */
826 }
827
828
829 /*
830 * 'cupsdIsCGI()' - Is the resource a CGI script/program?
831 */
832
833 int /* O - 1 = CGI, 0 = file */
834 cupsdIsCGI(cupsd_client_t *con, /* I - Client connection */
835 const char *filename, /* I - Real filename */
836 struct stat *filestats, /* I - File information */
837 mime_type_t *type) /* I - MIME type */
838 {
839 const char *options; /* Options on URL */
840
841
842 cupsdLogMessage(CUPSD_LOG_DEBUG2,
843 "cupsdIsCGI(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
844 con, filename, filestats, type ? type->super : "unknown",
845 type ? type->type : "unknown");
846
847 /*
848 * Get the options, if any...
849 */
850
851 if ((options = strchr(con->uri, '?')) != NULL)
852 options ++;
853
854 /*
855 * Check for known types...
856 */
857
858 if (!type || strcasecmp(type->super, "application"))
859 {
860 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsCGI: Returning 0...");
861 return (0);
862 }
863
864 if (!strcasecmp(type->type, "x-httpd-cgi") &&
865 (filestats->st_mode & 0111))
866 {
867 /*
868 * "application/x-httpd-cgi" is a CGI script.
869 */
870
871 cupsdSetString(&con->command, filename);
872
873 filename = strrchr(filename, '/') + 1; /* Filename always absolute */
874
875 if (options)
876 cupsdSetStringf(&con->options, "%s %s", filename, options);
877 else
878 cupsdSetStringf(&con->options, "%s", filename);
879
880 cupsdLogMessage(CUPSD_LOG_DEBUG2,
881 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
882 con->command, con->options);
883
884 return (1);
885 }
886 #ifdef HAVE_JAVA
887 else if (!strcasecmp(type->type, "x-httpd-java"))
888 {
889 /*
890 * "application/x-httpd-java" is a Java servlet.
891 */
892
893 cupsdSetString(&con->command, CUPS_JAVA);
894
895 if (options)
896 cupsdSetStringf(&con->options, "java %s %s", filename, options);
897 else
898 cupsdSetStringf(&con->options, "java %s", filename);
899
900 cupsdLogMessage(CUPSD_LOG_DEBUG2,
901 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
902 con->command, con->options);
903
904 return (1);
905 }
906 #endif /* HAVE_JAVA */
907 #ifdef HAVE_PERL
908 else if (!strcasecmp(type->type, "x-httpd-perl"))
909 {
910 /*
911 * "application/x-httpd-perl" is a Perl page.
912 */
913
914 cupsdSetString(&con->command, CUPS_PERL);
915
916 if (options)
917 cupsdSetStringf(&con->options, "perl %s %s", filename, options);
918 else
919 cupsdSetStringf(&con->options, "perl %s", filename);
920
921 cupsdLogMessage(CUPSD_LOG_DEBUG2,
922 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
923 con->command, con->options);
924
925 return (1);
926 }
927 #endif /* HAVE_PERL */
928 #ifdef HAVE_PHP
929 else if (!strcasecmp(type->type, "x-httpd-php"))
930 {
931 /*
932 * "application/x-httpd-php" is a PHP page.
933 */
934
935 cupsdSetString(&con->command, CUPS_PHP);
936
937 if (options)
938 cupsdSetStringf(&con->options, "php %s %s", filename, options);
939 else
940 cupsdSetStringf(&con->options, "php %s", filename);
941
942 cupsdLogMessage(CUPSD_LOG_DEBUG2,
943 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
944 con->command, con->options);
945
946 return (1);
947 }
948 #endif /* HAVE_PHP */
949 #ifdef HAVE_PYTHON
950 else if (!strcasecmp(type->type, "x-httpd-python"))
951 {
952 /*
953 * "application/x-httpd-python" is a Python page.
954 */
955
956 cupsdSetString(&con->command, CUPS_PYTHON);
957
958 if (options)
959 cupsdSetStringf(&con->options, "python %s %s", filename, options);
960 else
961 cupsdSetStringf(&con->options, "python %s", filename);
962
963 cupsdLogMessage(CUPSD_LOG_DEBUG2,
964 "cupsdIsCGI: Returning 1 with command=\"%s\" and options=\"%s\"",
965 con->command, con->options);
966
967 return (1);
968 }
969 #endif /* HAVE_PYTHON */
970
971 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdIsCGI: Returning 0...");
972
973 return (0);
974 }
975
976
977 /*
978 * 'cupsdReadClient()' - Read data from a client.
979 */
980
981 int /* O - 1 on success, 0 on error */
982 cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
983 {
984 char line[32768], /* Line from client... */
985 operation[64], /* Operation code from socket */
986 version[64], /* HTTP version number string */
987 locale[64], /* Locale */
988 *ptr; /* Pointer into strings */
989 int major, minor; /* HTTP version numbers */
990 http_status_t status; /* Transfer status */
991 ipp_state_t ipp_state; /* State of IPP transfer */
992 int bytes; /* Number of bytes to POST */
993 char *filename; /* Name of file for GET/HEAD */
994 char buf[1024]; /* Buffer for real filename */
995 struct stat filestats; /* File information */
996 mime_type_t *type; /* MIME type of file */
997 cupsd_printer_t *p; /* Printer */
998 static unsigned request_id = 0; /* Request ID for temp files */
999
1000
1001 status = HTTP_CONTINUE;
1002
1003 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1004 "cupsdReadClient: %d, used=%d, file=%d state=%d",
1005 con->http.fd, con->http.used, con->file, con->http.state);
1006
1007 if (con->http.error)
1008 {
1009 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadClient: http error seen...");
1010 return (cupsdCloseClient(con));
1011 }
1012
1013 #ifdef HAVE_SSL
1014 if (con->auto_ssl)
1015 {
1016 /*
1017 * Automatically check for a SSL/TLS handshake...
1018 */
1019
1020 con->auto_ssl = 0;
1021
1022 if (recv(con->http.fd, buf, 1, MSG_PEEK) == 1 &&
1023 (!buf[0] || !strchr("DGHOPT", buf[0])))
1024 {
1025 /*
1026 * Encrypt this connection...
1027 */
1028
1029 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1030 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
1031 buf[0] & 255);
1032
1033 cupsdEncryptClient(con);
1034 return (1);
1035 }
1036 }
1037 #endif /* HAVE_SSL */
1038
1039 switch (con->http.state)
1040 {
1041 case HTTP_WAITING :
1042 /*
1043 * See if we've received a request line...
1044 */
1045
1046 if (httpGets(line, sizeof(line) - 1, HTTP(con)) == NULL)
1047 {
1048 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1049 "cupsdReadClient: httpGets returned EOF...");
1050 return (cupsdCloseClient(con));
1051 }
1052
1053 /*
1054 * Ignore blank request lines...
1055 */
1056
1057 if (line[0] == '\0')
1058 break;
1059
1060 /*
1061 * Clear other state variables...
1062 */
1063
1064 httpClearFields(HTTP(con));
1065
1066 con->http.activity = time(NULL);
1067 con->http.version = HTTP_1_0;
1068 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1069 con->http.data_encoding = HTTP_ENCODE_LENGTH;
1070 con->http.data_remaining = 0;
1071 con->http._data_remaining = 0;
1072 con->operation = HTTP_WAITING;
1073 con->bytes = 0;
1074 con->file = -1;
1075 con->file_ready = 0;
1076 con->pipe_pid = 0;
1077 con->username[0] = '\0';
1078 con->password[0] = '\0';
1079 con->uri[0] = '\0';
1080
1081 cupsdClearString(&con->command);
1082 cupsdClearString(&con->options);
1083
1084 if (con->language != NULL)
1085 {
1086 cupsLangFree(con->language);
1087 con->language = NULL;
1088 }
1089
1090 /*
1091 * Grab the request line...
1092 */
1093
1094 switch (sscanf(line, "%63s%1023s%63s", operation, con->uri, version))
1095 {
1096 case 1 :
1097 cupsdLogMessage(CUPSD_LOG_ERROR,
1098 "Bad request line \"%s\" from %s!", line,
1099 con->http.hostname);
1100 cupsdSendError(con, HTTP_BAD_REQUEST);
1101 return (cupsdCloseClient(con));
1102 case 2 :
1103 con->http.version = HTTP_0_9;
1104 break;
1105 case 3 :
1106 if (sscanf(version, "HTTP/%d.%d", &major, &minor) != 2)
1107 {
1108 cupsdLogMessage(CUPSD_LOG_ERROR,
1109 "Bad request line \"%s\" from %s!", line,
1110 con->http.hostname);
1111 cupsdSendError(con, HTTP_BAD_REQUEST);
1112 return (cupsdCloseClient(con));
1113 }
1114
1115 if (major < 2)
1116 {
1117 con->http.version = (http_version_t)(major * 100 + minor);
1118 if (con->http.version == HTTP_1_1 && KeepAlive)
1119 con->http.keep_alive = HTTP_KEEPALIVE_ON;
1120 else
1121 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1122 }
1123 else
1124 {
1125 cupsdSendError(con, HTTP_NOT_SUPPORTED);
1126 return (cupsdCloseClient(con));
1127 }
1128 break;
1129 }
1130
1131 /*
1132 * Handle full URLs in the request line...
1133 */
1134
1135 if (strcmp(con->uri, "*"))
1136 {
1137 char method[HTTP_MAX_URI], /* Method/scheme */
1138 userpass[HTTP_MAX_URI], /* Username:password */
1139 hostname[HTTP_MAX_URI], /* Hostname */
1140 resource[HTTP_MAX_URI]; /* Resource path */
1141 int port; /* Port number */
1142
1143
1144 /*
1145 * Separate the URI into its components...
1146 */
1147
1148 httpSeparateURI(con->uri, method, sizeof(method),
1149 userpass, sizeof(userpass),
1150 hostname, sizeof(hostname), &port,
1151 resource, sizeof(resource));
1152
1153 /*
1154 * Only allow URIs with the servername, localhost, or an IP
1155 * address...
1156 */
1157
1158 if (strcmp(method, "file") &&
1159 strcasecmp(hostname, ServerName) &&
1160 strcasecmp(hostname, "localhost") &&
1161 !isdigit(hostname[0]))
1162 {
1163 /*
1164 * Nope, we don't do proxies...
1165 */
1166
1167 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad URI \"%s\" in request!",
1168 con->uri);
1169 cupsdSendError(con, HTTP_METHOD_NOT_ALLOWED);
1170 return (cupsdCloseClient(con));
1171 }
1172
1173 /*
1174 * Copy the resource portion back into the URI; both resource and
1175 * con->uri are HTTP_MAX_URI bytes in size...
1176 */
1177
1178 strcpy(con->uri, resource);
1179 }
1180
1181 /*
1182 * Process the request...
1183 */
1184
1185 if (!strcmp(operation, "GET"))
1186 con->http.state = HTTP_GET;
1187 else if (!strcmp(operation, "PUT"))
1188 con->http.state = HTTP_PUT;
1189 else if (!strcmp(operation, "POST"))
1190 con->http.state = HTTP_POST;
1191 else if (!strcmp(operation, "DELETE"))
1192 con->http.state = HTTP_DELETE;
1193 else if (!strcmp(operation, "TRACE"))
1194 con->http.state = HTTP_TRACE;
1195 else if (!strcmp(operation, "OPTIONS"))
1196 con->http.state = HTTP_OPTIONS;
1197 else if (!strcmp(operation, "HEAD"))
1198 con->http.state = HTTP_HEAD;
1199 else
1200 {
1201 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad operation \"%s\"!", operation);
1202 cupsdSendError(con, HTTP_BAD_REQUEST);
1203 return (cupsdCloseClient(con));
1204 }
1205
1206 con->start = time(NULL);
1207 con->operation = con->http.state;
1208
1209 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdReadClient: %d %s %s HTTP/%d.%d", con->http.fd,
1210 operation, con->uri,
1211 con->http.version / 100, con->http.version % 100);
1212
1213 con->http.status = HTTP_OK;
1214
1215 case HTTP_OPTIONS :
1216 case HTTP_DELETE :
1217 case HTTP_GET :
1218 case HTTP_HEAD :
1219 case HTTP_POST :
1220 case HTTP_PUT :
1221 case HTTP_TRACE :
1222 /*
1223 * Parse incoming parameters until the status changes...
1224 */
1225
1226 status = httpUpdate(HTTP(con));
1227
1228 if (status != HTTP_OK && status != HTTP_CONTINUE)
1229 {
1230 cupsdSendError(con, HTTP_BAD_REQUEST);
1231 return (cupsdCloseClient(con));
1232 }
1233 break;
1234
1235 default :
1236 break; /* Anti-compiler-warning-code */
1237 }
1238
1239 /*
1240 * Handle new transfers...
1241 */
1242
1243 if (status == HTTP_OK)
1244 {
1245 if (con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE][0])
1246 {
1247 /*
1248 * Figure out the locale from the Accept-Language and Content-Type
1249 * fields...
1250 */
1251
1252 if ((ptr = strchr(con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ',')) != NULL)
1253 *ptr = '\0';
1254
1255 if ((ptr = strchr(con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ';')) != NULL)
1256 *ptr = '\0';
1257
1258 if ((ptr = strstr(con->http.fields[HTTP_FIELD_CONTENT_TYPE], "charset=")) != NULL)
1259 {
1260 /*
1261 * Combine language and charset, and trim any extra params in the
1262 * content-type.
1263 */
1264
1265 snprintf(locale, sizeof(locale), "%s.%s",
1266 con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ptr + 8);
1267
1268 if ((ptr = strchr(locale, ',')) != NULL)
1269 *ptr = '\0';
1270 }
1271 else
1272 snprintf(locale, sizeof(locale), "%s.%s",
1273 con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], DefaultCharset);
1274
1275 con->language = cupsLangGet(locale);
1276 }
1277 else
1278 con->language = cupsLangGet(DefaultLocale);
1279
1280 cupsdAuthorize(con);
1281
1282 if (!strncmp(con->http.fields[HTTP_FIELD_CONNECTION], "Keep-Alive", 10) &&
1283 KeepAlive)
1284 con->http.keep_alive = HTTP_KEEPALIVE_ON;
1285
1286 if (!con->http.fields[HTTP_FIELD_HOST][0] &&
1287 con->http.version >= HTTP_1_1)
1288 {
1289 /*
1290 * HTTP/1.1 and higher require the "Host:" field...
1291 */
1292
1293 if (!cupsdSendError(con, HTTP_BAD_REQUEST))
1294 return (cupsdCloseClient(con));
1295 }
1296 else if (con->operation == HTTP_OPTIONS)
1297 {
1298 /*
1299 * Do OPTIONS command...
1300 */
1301
1302 if (con->best && con->best->type != AUTH_NONE)
1303 {
1304 if (!cupsdSendHeader(con, HTTP_UNAUTHORIZED, NULL))
1305 return (cupsdCloseClient(con));
1306 }
1307
1308 if (!strcasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Upgrade") &&
1309 con->http.tls == NULL)
1310 {
1311 #ifdef HAVE_SSL
1312 /*
1313 * Do encryption stuff...
1314 */
1315
1316 if (!cupsdSendHeader(con, HTTP_SWITCHING_PROTOCOLS, NULL))
1317 return (cupsdCloseClient(con));
1318
1319 httpPrintf(HTTP(con), "Connection: Upgrade\r\n");
1320 httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1321 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1322 httpPrintf(HTTP(con), "\r\n");
1323
1324 cupsdEncryptClient(con);
1325 #else
1326 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED))
1327 return (cupsdCloseClient(con));
1328 #endif /* HAVE_SSL */
1329 }
1330
1331 if (con->http.expect)
1332 {
1333 /**** TODO: send expected header ****/
1334 }
1335
1336 if (!cupsdSendHeader(con, HTTP_OK, NULL))
1337 return (cupsdCloseClient(con));
1338
1339 httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1340 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1341 httpPrintf(HTTP(con), "\r\n");
1342 }
1343 else if (!is_path_absolute(con->uri))
1344 {
1345 /*
1346 * Protect against malicious users!
1347 */
1348
1349 if (!cupsdSendError(con, HTTP_FORBIDDEN))
1350 return (cupsdCloseClient(con));
1351 }
1352 else
1353 {
1354 if (!strcasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Upgrade") &&
1355 con->http.tls == NULL)
1356 {
1357 #ifdef HAVE_SSL
1358 /*
1359 * Do encryption stuff...
1360 */
1361
1362 if (!cupsdSendHeader(con, HTTP_SWITCHING_PROTOCOLS, NULL))
1363 return (cupsdCloseClient(con));
1364
1365 httpPrintf(HTTP(con), "Connection: Upgrade\r\n");
1366 httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1367 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1368 httpPrintf(HTTP(con), "\r\n");
1369
1370 cupsdEncryptClient(con);
1371 #else
1372 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED))
1373 return (cupsdCloseClient(con));
1374 #endif /* HAVE_SSL */
1375 }
1376
1377 if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_OK)
1378 {
1379 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1380 "cupsdReadClient: Unauthorized request for %s...\n",
1381 con->uri);
1382 cupsdSendError(con, status);
1383 return (cupsdCloseClient(con));
1384 }
1385
1386 if (con->http.expect)
1387 {
1388 /**** TODO: send expected header ****/
1389 }
1390
1391 switch (con->http.state)
1392 {
1393 case HTTP_GET_SEND :
1394 if (!strncmp(con->uri, "/printers/", 10) &&
1395 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1396 {
1397 /*
1398 * Send PPD file - get the real printer name since printer
1399 * names are not case sensitive but filenames can be...
1400 */
1401
1402 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1403
1404 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1405 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1406 else
1407 {
1408 if (!cupsdSendError(con, HTTP_NOT_FOUND))
1409 return (cupsdCloseClient(con));
1410
1411 break;
1412 }
1413 }
1414
1415 if ((!strncmp(con->uri, "/admin", 6) &&
1416 strncmp(con->uri, "/admin/conf/", 12) &&
1417 strncmp(con->uri, "/admin/log/", 11)) ||
1418 !strncmp(con->uri, "/printers", 9) ||
1419 !strncmp(con->uri, "/classes", 8) ||
1420 !strncmp(con->uri, "/help", 5) ||
1421 !strncmp(con->uri, "/jobs", 5))
1422 {
1423 /*
1424 * Send CGI output...
1425 */
1426
1427 if (!strncmp(con->uri, "/admin", 6))
1428 {
1429 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1430 ServerBin);
1431
1432 if ((ptr = strchr(con->uri + 6, '?')) != NULL)
1433 cupsdSetStringf(&con->options, "admin%s", ptr);
1434 else
1435 cupsdSetString(&con->options, "admin");
1436 }
1437 else if (!strncmp(con->uri, "/printers", 9))
1438 {
1439 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1440 ServerBin);
1441 cupsdSetString(&con->options, con->uri + 9);
1442 }
1443 else if (!strncmp(con->uri, "/classes", 8))
1444 {
1445 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1446 ServerBin);
1447 cupsdSetString(&con->options, con->uri + 8);
1448 }
1449 else if (!strncmp(con->uri, "/jobs", 5))
1450 {
1451 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1452 ServerBin);
1453 cupsdSetString(&con->options, con->uri + 5);
1454 }
1455 else
1456 {
1457 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1458 ServerBin);
1459 cupsdSetString(&con->options, con->uri + 5);
1460 }
1461
1462 if (con->options[0] == '/')
1463 _cups_strcpy(con->options, con->options + 1);
1464
1465 if (!cupsdSendCommand(con, con->command, con->options, 0))
1466 {
1467 if (!cupsdSendError(con, HTTP_NOT_FOUND))
1468 return (cupsdCloseClient(con));
1469 }
1470 else
1471 cupsdLogRequest(con, HTTP_OK);
1472
1473 if (con->http.version <= HTTP_1_0)
1474 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1475 }
1476 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1477 (strchr(con->uri + 12, '/') ||
1478 strlen(con->uri) == 12)) ||
1479 (!strncmp(con->uri, "/admin/log/", 11) &&
1480 (strchr(con->uri + 11, '/') ||
1481 strlen(con->uri) == 11)))
1482 {
1483 /*
1484 * GET can only be done to configuration files under
1485 * /admin/conf...
1486 */
1487
1488 if (!cupsdSendError(con, HTTP_FORBIDDEN))
1489 return (cupsdCloseClient(con));
1490
1491 break;
1492 }
1493 else
1494 {
1495 /*
1496 * Serve a file...
1497 */
1498
1499 if ((filename = get_file(con, &filestats, buf,
1500 sizeof(buf))) == NULL)
1501 {
1502 if (!cupsdSendError(con, HTTP_NOT_FOUND))
1503 return (cupsdCloseClient(con));
1504
1505 break;
1506 }
1507
1508 type = mimeFileType(MimeDatabase, filename, NULL);
1509
1510 if (cupsdIsCGI(con, filename, &filestats, type))
1511 {
1512 /*
1513 * Note: con->command and con->options were set by
1514 * cupsdIsCGI()...
1515 */
1516
1517 if (!cupsdSendCommand(con, con->command, con->options, 0))
1518 {
1519 if (!cupsdSendError(con, HTTP_NOT_FOUND))
1520 return (cupsdCloseClient(con));
1521 }
1522 else
1523 cupsdLogRequest(con, HTTP_OK);
1524
1525 if (con->http.version <= HTTP_1_0)
1526 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1527 break;
1528 }
1529
1530 if (!check_if_modified(con, &filestats))
1531 {
1532 if (!cupsdSendError(con, HTTP_NOT_MODIFIED))
1533 return (cupsdCloseClient(con));
1534 }
1535 else
1536 {
1537 if (type == NULL)
1538 strcpy(line, "text/plain");
1539 else
1540 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1541
1542 if (!cupsdSendFile(con, HTTP_OK, filename, line, &filestats))
1543 return (cupsdCloseClient(con));
1544 }
1545 }
1546 break;
1547
1548 case HTTP_POST_RECV :
1549 /*
1550 * See if the POST request includes a Content-Length field, and if
1551 * so check the length against any limits that are set...
1552 */
1553
1554 cupsdLogMessage(CUPSD_LOG_DEBUG2, "POST %s", con->uri);
1555 cupsdLogMessage(CUPSD_LOG_DEBUG2, "CONTENT_TYPE = %s",
1556 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
1557
1558 if (con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1559 MaxRequestSize > 0 &&
1560 con->http.data_remaining > MaxRequestSize)
1561 {
1562 /*
1563 * Request too large...
1564 */
1565
1566 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
1567 return (cupsdCloseClient(con));
1568
1569 break;
1570 }
1571 else if (con->http.data_remaining < 0)
1572 {
1573 /*
1574 * Negative content lengths are invalid!
1575 */
1576
1577 if (!cupsdSendError(con, HTTP_BAD_REQUEST))
1578 return (cupsdCloseClient(con));
1579
1580 break;
1581 }
1582
1583 /*
1584 * See what kind of POST request this is; for IPP requests the
1585 * content-type field will be "application/ipp"...
1586 */
1587
1588 if (!strcmp(con->http.fields[HTTP_FIELD_CONTENT_TYPE],
1589 "application/ipp"))
1590 con->request = ippNew();
1591 else if ((!strncmp(con->uri, "/admin", 6) &&
1592 strncmp(con->uri, "/admin/conf/", 12) &&
1593 strncmp(con->uri, "/admin/log/", 11)) ||
1594 !strncmp(con->uri, "/printers", 9) ||
1595 !strncmp(con->uri, "/classes", 8) ||
1596 !strncmp(con->uri, "/help", 5) ||
1597 !strncmp(con->uri, "/jobs", 5))
1598 {
1599 /*
1600 * CGI request...
1601 */
1602
1603 if (!strncmp(con->uri, "/admin", 6))
1604 {
1605 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1606 ServerBin);
1607
1608 if ((ptr = strchr(con->uri + 6, '?')) != NULL)
1609 cupsdSetStringf(&con->options, "admin%s", ptr);
1610 else
1611 cupsdSetString(&con->options, "admin");
1612 }
1613 else if (!strncmp(con->uri, "/printers", 9))
1614 {
1615 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1616 ServerBin);
1617 cupsdSetString(&con->options, con->uri + 9);
1618 }
1619 else if (!strncmp(con->uri, "/classes", 8))
1620 {
1621 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1622 ServerBin);
1623 cupsdSetString(&con->options, con->uri + 8);
1624 }
1625 else if (!strncmp(con->uri, "/jobs", 5))
1626 {
1627 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1628 ServerBin);
1629 cupsdSetString(&con->options, con->uri + 5);
1630 }
1631 else
1632 {
1633 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1634 ServerBin);
1635 cupsdSetString(&con->options, con->uri + 5);
1636 }
1637
1638 if (con->options[0] == '/')
1639 _cups_strcpy(con->options, con->options + 1);
1640
1641 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1642 "cupsdReadClient: %d command=\"%s\", options = \"%s\"",
1643 con->http.fd, con->command, con->options);
1644
1645 if (con->http.version <= HTTP_1_0)
1646 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1647 }
1648 else
1649 {
1650 /*
1651 * POST to a file...
1652 */
1653
1654 if ((filename = get_file(con, &filestats, buf,
1655 sizeof(buf))) == NULL)
1656 {
1657 if (!cupsdSendError(con, HTTP_NOT_FOUND))
1658 return (cupsdCloseClient(con));
1659
1660 break;
1661 }
1662
1663 type = mimeFileType(MimeDatabase, filename, NULL);
1664
1665 if (!cupsdIsCGI(con, filename, &filestats, type))
1666 {
1667 /*
1668 * Only POST to CGI's...
1669 */
1670
1671 if (!cupsdSendError(con, HTTP_UNAUTHORIZED))
1672 return (cupsdCloseClient(con));
1673 }
1674 }
1675 break;
1676
1677 case HTTP_PUT_RECV :
1678 /*
1679 * Validate the resource name...
1680 */
1681
1682 if (strncmp(con->uri, "/admin/conf/", 12) ||
1683 strchr(con->uri + 12, '/') ||
1684 strlen(con->uri) == 12)
1685 {
1686 /*
1687 * PUT can only be done to configuration files under
1688 * /admin/conf...
1689 */
1690
1691 if (!cupsdSendError(con, HTTP_FORBIDDEN))
1692 return (cupsdCloseClient(con));
1693
1694 break;
1695 }
1696
1697 /*
1698 * See if the PUT request includes a Content-Length field, and if
1699 * so check the length against any limits that are set...
1700 */
1701
1702 cupsdLogMessage(CUPSD_LOG_DEBUG2, "PUT %s", con->uri);
1703 cupsdLogMessage(CUPSD_LOG_DEBUG2, "CONTENT_TYPE = %s",
1704 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
1705
1706 if (con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1707 MaxRequestSize > 0 &&
1708 con->http.data_remaining > MaxRequestSize)
1709 {
1710 /*
1711 * Request too large...
1712 */
1713
1714 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
1715 return (cupsdCloseClient(con));
1716
1717 break;
1718 }
1719 else if (con->http.data_remaining < 0)
1720 {
1721 /*
1722 * Negative content lengths are invalid!
1723 */
1724
1725 if (!cupsdSendError(con, HTTP_BAD_REQUEST))
1726 return (cupsdCloseClient(con));
1727
1728 break;
1729 }
1730
1731 /*
1732 * Open a temporary file to hold the request...
1733 */
1734
1735 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1736 request_id ++);
1737 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1738
1739 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1740 "cupsdReadClient: %d REQUEST %s=%d", con->http.fd,
1741 con->filename, con->file);
1742
1743 if (con->file < 0)
1744 {
1745 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
1746 return (cupsdCloseClient(con));
1747 }
1748
1749 fchmod(con->file, 0640);
1750 fchown(con->file, RunUser, Group);
1751 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1752 break;
1753
1754 case HTTP_DELETE :
1755 case HTTP_TRACE :
1756 cupsdSendError(con, HTTP_NOT_IMPLEMENTED);
1757 return (cupsdCloseClient(con));
1758
1759 case HTTP_HEAD :
1760 if (!strncmp(con->uri, "/printers/", 10) &&
1761 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1762 {
1763 /*
1764 * Send PPD file - get the real printer name since printer
1765 * names are not case sensitive but filenames can be...
1766 */
1767
1768 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1769
1770 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1771 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1772 else
1773 {
1774 if (!cupsdSendError(con, HTTP_NOT_FOUND))
1775 return (cupsdCloseClient(con));
1776
1777 break;
1778 }
1779 }
1780
1781 if ((!strncmp(con->uri, "/admin", 6) &&
1782 strncmp(con->uri, "/admin/conf/", 12) &&
1783 strncmp(con->uri, "/admin/log/", 11)) ||
1784 !strncmp(con->uri, "/printers", 9) ||
1785 !strncmp(con->uri, "/classes", 8) ||
1786 !strncmp(con->uri, "/help", 5) ||
1787 !strncmp(con->uri, "/jobs", 5))
1788 {
1789 /*
1790 * CGI output...
1791 */
1792
1793 if (!cupsdSendHeader(con, HTTP_OK, "text/html"))
1794 return (cupsdCloseClient(con));
1795
1796 if (httpPrintf(HTTP(con), "\r\n") < 0)
1797 return (cupsdCloseClient(con));
1798
1799 cupsdLogRequest(con, HTTP_OK);
1800 }
1801 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1802 (strchr(con->uri + 12, '/') ||
1803 strlen(con->uri) == 12)) ||
1804 (!strncmp(con->uri, "/admin/log/", 11) &&
1805 (strchr(con->uri + 11, '/') ||
1806 strlen(con->uri) == 11)))
1807 {
1808 /*
1809 * HEAD can only be done to configuration files under
1810 * /admin/conf...
1811 */
1812
1813 if (!cupsdSendError(con, HTTP_FORBIDDEN))
1814 return (cupsdCloseClient(con));
1815
1816 break;
1817 }
1818 else if ((filename = get_file(con, &filestats, buf,
1819 sizeof(buf))) == NULL)
1820 {
1821 if (!cupsdSendHeader(con, HTTP_NOT_FOUND, "text/html"))
1822 return (cupsdCloseClient(con));
1823
1824 cupsdLogRequest(con, HTTP_NOT_FOUND);
1825 }
1826 else if (!check_if_modified(con, &filestats))
1827 {
1828 if (!cupsdSendError(con, HTTP_NOT_MODIFIED))
1829 return (cupsdCloseClient(con));
1830
1831 cupsdLogRequest(con, HTTP_NOT_MODIFIED);
1832 }
1833 else
1834 {
1835 /*
1836 * Serve a file...
1837 */
1838
1839 type = mimeFileType(MimeDatabase, filename, NULL);
1840 if (type == NULL)
1841 strcpy(line, "text/plain");
1842 else
1843 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1844
1845 if (!cupsdSendHeader(con, HTTP_OK, line))
1846 return (cupsdCloseClient(con));
1847
1848 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
1849 httpGetDateString(filestats.st_mtime)) < 0)
1850 return (cupsdCloseClient(con));
1851
1852 if (httpPrintf(HTTP(con), "Content-Length: %lu\r\n",
1853 (unsigned long)filestats.st_size) < 0)
1854 return (cupsdCloseClient(con));
1855
1856 cupsdLogRequest(con, HTTP_OK);
1857 }
1858
1859 if (httpPrintf(HTTP(con), "\r\n") < 0)
1860 return (cupsdCloseClient(con));
1861
1862 con->http.state = HTTP_WAITING;
1863 break;
1864
1865 default :
1866 break; /* Anti-compiler-warning-code */
1867 }
1868 }
1869 }
1870
1871 /*
1872 * Handle any incoming data...
1873 */
1874
1875 switch (con->http.state)
1876 {
1877 case HTTP_PUT_RECV :
1878 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1879 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1880 "con->data_remaining=" CUPS_LLFMT ", con->file=%d",
1881 con->http.fd,
1882 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
1883 "CHUNKED" : "LENGTH",
1884 CUPS_LLCAST con->http.data_remaining, con->file);
1885
1886 if ((bytes = httpRead(HTTP(con), line, sizeof(line))) < 0)
1887 return (cupsdCloseClient(con));
1888 else if (bytes > 0)
1889 {
1890 con->bytes += bytes;
1891
1892 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1893 "cupsdReadClient: %d writing %d bytes to %d",
1894 con->http.fd, bytes, con->file);
1895
1896 if (write(con->file, line, bytes) < bytes)
1897 {
1898 cupsdLogMessage(CUPSD_LOG_ERROR,
1899 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1900 bytes, con->filename, strerror(errno));
1901
1902 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1903 "cupsdReadClient: Closing data file %d...",
1904 con->file);
1905
1906 close(con->file);
1907 con->file = -1;
1908 unlink(con->filename);
1909 cupsdClearString(&con->filename);
1910
1911 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
1912 return (cupsdCloseClient(con));
1913 }
1914 }
1915
1916 if (con->http.state == HTTP_WAITING)
1917 {
1918 /*
1919 * End of file, see how big it is...
1920 */
1921
1922 fstat(con->file, &filestats);
1923
1924 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1925 "cupsdReadClient: %d Closing data file %d, size="
1926 CUPS_LLFMT ".",
1927 con->http.fd, con->file,
1928 CUPS_LLCAST filestats.st_size);
1929
1930 close(con->file);
1931 con->file = -1;
1932
1933 if (filestats.st_size > MaxRequestSize &&
1934 MaxRequestSize > 0)
1935 {
1936 /*
1937 * Request is too big; remove it and send an error...
1938 */
1939
1940 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1941 "cupsdReadClient: %d Removing temp file %s",
1942 con->http.fd, con->filename);
1943 unlink(con->filename);
1944 cupsdClearString(&con->filename);
1945
1946 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
1947 return (cupsdCloseClient(con));
1948 }
1949
1950 /*
1951 * Install the configuration file...
1952 */
1953
1954 status = install_conf_file(con);
1955
1956 /*
1957 * Return the status to the client...
1958 */
1959
1960 if (!cupsdSendError(con, status))
1961 return (cupsdCloseClient(con));
1962 }
1963 break;
1964
1965 case HTTP_POST_RECV :
1966 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1967 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1968 "%s, con->data_remaining=" CUPS_LLFMT ", con->file=%d",
1969 con->http.fd,
1970 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
1971 "CHUNKED" : "LENGTH",
1972 CUPS_LLCAST con->http.data_remaining, con->file);
1973
1974 if (con->request != NULL)
1975 {
1976 /*
1977 * Grab any request data from the connection...
1978 */
1979
1980 if ((ipp_state = ippRead(&(con->http), con->request)) == IPP_ERROR)
1981 {
1982 cupsdLogMessage(CUPSD_LOG_ERROR,
1983 "cupsdReadClient: %d IPP Read Error!",
1984 con->http.fd);
1985
1986 cupsdSendError(con, HTTP_BAD_REQUEST);
1987 return (cupsdCloseClient(con));
1988 }
1989 else if (ipp_state != IPP_DATA)
1990 {
1991 if (con->http.state == HTTP_POST_SEND)
1992 {
1993 cupsdSendError(con, HTTP_BAD_REQUEST);
1994 return (cupsdCloseClient(con));
1995 }
1996
1997 break;
1998 }
1999 else
2000 con->bytes += ippLength(con->request);
2001 }
2002
2003 if (con->file < 0 && con->http.state != HTTP_POST_SEND)
2004 {
2005 /*
2006 * Create a file as needed for the request data...
2007 */
2008
2009 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot, request_id ++);
2010 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
2011
2012 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadClient: %d REQUEST %s=%d", con->http.fd,
2013 con->filename, con->file);
2014
2015 if (con->file < 0)
2016 {
2017 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
2018 return (cupsdCloseClient(con));
2019 }
2020
2021 fchmod(con->file, 0640);
2022 fchown(con->file, RunUser, Group);
2023 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2024 }
2025
2026 if (con->http.state != HTTP_POST_SEND)
2027 {
2028 if ((bytes = httpRead(HTTP(con), line, sizeof(line))) < 0)
2029 return (cupsdCloseClient(con));
2030 else if (bytes > 0)
2031 {
2032 con->bytes += bytes;
2033
2034 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2035 "cupsdReadClient: %d writing %d bytes to %d",
2036 con->http.fd, bytes, con->file);
2037
2038 if (write(con->file, line, bytes) < bytes)
2039 {
2040 cupsdLogMessage(CUPSD_LOG_ERROR,
2041 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2042 bytes, con->filename, strerror(errno));
2043
2044 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2045 "cupsdReadClient: Closing file %d...",
2046 con->file);
2047
2048 close(con->file);
2049 con->file = -1;
2050 unlink(con->filename);
2051 cupsdClearString(&con->filename);
2052
2053 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
2054 return (cupsdCloseClient(con));
2055 }
2056 }
2057 else if (con->http.state == HTTP_POST_RECV)
2058 return (1); /* ??? */
2059 else if (con->http.state != HTTP_POST_SEND)
2060 return (cupsdCloseClient(con));
2061 }
2062
2063 if (con->http.state == HTTP_POST_SEND)
2064 {
2065 if (con->file >= 0)
2066 {
2067 fstat(con->file, &filestats);
2068
2069 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2070 "cupsdReadClient: %d Closing data file %d, "
2071 "size=" CUPS_LLFMT ".",
2072 con->http.fd, con->file,
2073 CUPS_LLCAST filestats.st_size);
2074
2075 close(con->file);
2076 con->file = -1;
2077
2078 if (filestats.st_size > MaxRequestSize &&
2079 MaxRequestSize > 0)
2080 {
2081 /*
2082 * Request is too big; remove it and send an error...
2083 */
2084
2085 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2086 "cupsdReadClient: %d Removing temp file %s",
2087 con->http.fd, con->filename);
2088 unlink(con->filename);
2089 cupsdClearString(&con->filename);
2090
2091 if (con->request)
2092 {
2093 /*
2094 * Delete any IPP request data...
2095 */
2096
2097 ippDelete(con->request);
2098 con->request = NULL;
2099 }
2100
2101 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE))
2102 return (cupsdCloseClient(con));
2103 }
2104
2105 if (con->command)
2106 {
2107 if (!cupsdSendCommand(con, con->command, con->options, 0))
2108 {
2109 if (!cupsdSendError(con, HTTP_NOT_FOUND))
2110 return (cupsdCloseClient(con));
2111 }
2112 else
2113 cupsdLogRequest(con, HTTP_OK);
2114 }
2115 }
2116
2117 if (con->request)
2118 return (cupsdProcessIPPRequest(con));
2119 }
2120 break;
2121
2122 default :
2123 break; /* Anti-compiler-warning-code */
2124 }
2125
2126 if (!con->http.keep_alive && con->http.state == HTTP_WAITING)
2127 return (cupsdCloseClient(con));
2128 else
2129 return (1);
2130 }
2131
2132
2133 /*
2134 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2135 */
2136
2137 int /* O - 1 on success, 0 on failure */
2138 cupsdSendCommand(
2139 cupsd_client_t *con, /* I - Client connection */
2140 char *command, /* I - Command to run */
2141 char *options, /* I - Command-line options */
2142 int root) /* I - Run as root? */
2143 {
2144 int fd; /* Standard input file descriptor */
2145
2146
2147 if (con->filename)
2148 fd = open(con->filename, O_RDONLY);
2149 else
2150 fd = open("/dev/null", O_RDONLY);
2151
2152 if (fd < 0)
2153 {
2154 cupsdLogMessage(CUPSD_LOG_ERROR,
2155 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2156 con->http.fd, con->filename ? con->filename : "/dev/null",
2157 strerror(errno));
2158 return (0);
2159 }
2160
2161 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
2162
2163 con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
2164
2165 close(fd);
2166
2167 cupsdLogMessage(CUPSD_LOG_INFO, "Started \"%s\" (pid=%d)", command,
2168 con->pipe_pid);
2169
2170 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendCommand: %d file=%d",
2171 con->http.fd, con->file);
2172
2173 if (con->pipe_pid == 0)
2174 return (0);
2175
2176 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2177
2178 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2179 "cupsdSendCommand: Adding fd %d to InputSet...", con->file);
2180 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2181 "cupsdSendCommand: Adding fd %d to OutputSet...",
2182 con->http.fd);
2183
2184 FD_SET(con->file, InputSet);
2185 FD_SET(con->http.fd, OutputSet);
2186
2187 con->sent_header = 0;
2188 con->file_ready = 0;
2189 con->got_fields = 0;
2190 con->field_col = 0;
2191
2192 return (1);
2193 }
2194
2195
2196 /*
2197 * 'cupsdSendError()' - Send an error message via HTTP.
2198 */
2199
2200 int /* O - 1 if successful, 0 otherwise */
2201 cupsdSendError(cupsd_client_t *con, /* I - Connection */
2202 http_status_t code) /* I - Error code */
2203 {
2204 /*
2205 * Put the request in the access_log file...
2206 */
2207
2208 cupsdLogRequest(con, code);
2209
2210 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendError: %d code=%d (%s)",
2211 con->http.fd, code, httpStatus(code));
2212
2213 /*
2214 * To work around bugs in some proxies, don't use Keep-Alive for some
2215 * error messages...
2216 */
2217
2218 if (code >= HTTP_BAD_REQUEST)
2219 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
2220
2221 /*
2222 * Send an error message back to the client. If the error code is a
2223 * 400 or 500 series, make sure the message contains some text, too!
2224 */
2225
2226 if (!cupsdSendHeader(con, code, NULL))
2227 return (0);
2228
2229 #ifdef HAVE_SSL
2230 if (code == HTTP_UPGRADE_REQUIRED)
2231 if (httpPrintf(HTTP(con), "Connection: Upgrade\r\n") < 0)
2232 return (0);
2233
2234 if (httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2235 return (0);
2236 #endif /* HAVE_SSL */
2237
2238 if ((con->http.version >= HTTP_1_1 && !con->http.keep_alive) ||
2239 (code >= HTTP_BAD_REQUEST && code != HTTP_UPGRADE_REQUIRED))
2240 {
2241 if (httpPrintf(HTTP(con), "Connection: close\r\n") < 0)
2242 return (0);
2243 }
2244
2245 if (code >= HTTP_BAD_REQUEST)
2246 {
2247 /*
2248 * Send a human-readable error message.
2249 */
2250
2251 char message[1024]; /* Message for user */
2252 const char *text; /* Status-specific text */
2253
2254 if (code == HTTP_UNAUTHORIZED)
2255 text = _cupsLangString(con->language,
2256 _("Enter your username and password or the "
2257 "root username and password to access this "
2258 "page."));
2259 else if (code == HTTP_UPGRADE_REQUIRED)
2260 text = _cupsLangString(con->language,
2261 _("You must use a https: URL to access this "
2262 "page."));
2263 else
2264 text = "";
2265
2266 snprintf(message, sizeof(message),
2267 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2268 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2269 "<HTML>\n"
2270 "<HEAD>\n"
2271 "\t<META HTTP-EQUIV=\"Content-Type\" "
2272 "CONTENT=\"text/html; charset=utf-8\">\n"
2273 "\t<TITLE>%d %s</TITLE>\n"
2274 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2275 "HREF=\"/cups.css\">\n"
2276 "</HEAD>\n"
2277 "<BODY>\n"
2278 "<H1>%d %s</H1>\n"
2279 "<P>%s</P>\n"
2280 "</BODY>\n"
2281 "</HTML>\n",
2282 code, httpStatus(code), code, httpStatus(code), text);
2283
2284 if (httpPrintf(HTTP(con), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2285 return (0);
2286 if (httpPrintf(HTTP(con), "Content-Length: %d\r\n",
2287 (int)strlen(message)) < 0)
2288 return (0);
2289 if (httpPrintf(HTTP(con), "\r\n") < 0)
2290 return (0);
2291 if (httpPrintf(HTTP(con), "%s", message) < 0)
2292 return (0);
2293 }
2294 else if (httpPrintf(HTTP(con), "\r\n") < 0)
2295 return (0);
2296
2297 con->http.state = HTTP_WAITING;
2298
2299 return (1);
2300 }
2301
2302
2303 /*
2304 * 'cupsdSendFile()' - Send a file via HTTP.
2305 */
2306
2307 int /* O - 0 on failure, 1 on success */
2308 cupsdSendFile(cupsd_client_t *con, /* I - Client connection */
2309 http_status_t code, /* I - HTTP status */
2310 char *filename, /* I - Filename */
2311 char *type, /* I - File type */
2312 struct stat *filestats)/* O - File information */
2313 {
2314 con->file = open(filename, O_RDONLY);
2315
2316 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendFile: %d file=%d", con->http.fd,
2317 con->file);
2318
2319 if (con->file < 0)
2320 return (0);
2321
2322 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2323
2324 con->pipe_pid = 0;
2325
2326 if (!cupsdSendHeader(con, code, type))
2327 return (0);
2328
2329 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
2330 httpGetDateString(filestats->st_mtime)) < 0)
2331 return (0);
2332 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
2333 CUPS_LLCAST filestats->st_size) < 0)
2334 return (0);
2335 if (httpPrintf(HTTP(con), "\r\n") < 0)
2336 return (0);
2337
2338 con->http.data_encoding = HTTP_ENCODE_LENGTH;
2339 con->http.data_remaining = filestats->st_size;
2340
2341 if (con->http.data_remaining <= INT_MAX)
2342 con->http._data_remaining = con->http.data_remaining;
2343 else
2344 con->http._data_remaining = INT_MAX;
2345
2346 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2347 "cupsdSendFile: Adding fd %d to OutputSet...", con->http.fd);
2348
2349 FD_SET(con->http.fd, OutputSet);
2350
2351 return (1);
2352 }
2353
2354
2355 /*
2356 * 'cupsdSendHeader()' - Send an HTTP request.
2357 */
2358
2359 int /* O - 1 on success, 0 on failure */
2360 cupsdSendHeader(cupsd_client_t *con, /* I - Client to send to */
2361 http_status_t code, /* I - HTTP status code */
2362 char *type) /* I - MIME type of document */
2363 {
2364 if (httpPrintf(HTTP(con), "HTTP/%d.%d %d %s\r\n", con->http.version / 100,
2365 con->http.version % 100, code, httpStatus(code)) < 0)
2366 return (0);
2367 if (httpPrintf(HTTP(con), "Date: %s\r\n", httpGetDateString(time(NULL))) < 0)
2368 return (0);
2369 if (ServerHeader)
2370 if (httpPrintf(HTTP(con), "Server: %s\r\n", ServerHeader) < 0)
2371 return (0);
2372 if (con->http.keep_alive && con->http.version >= HTTP_1_0)
2373 {
2374 if (httpPrintf(HTTP(con), "Connection: Keep-Alive\r\n") < 0)
2375 return (0);
2376 if (httpPrintf(HTTP(con), "Keep-Alive: timeout=%d\r\n",
2377 KeepAliveTimeout) < 0)
2378 return (0);
2379 }
2380 if (code == HTTP_METHOD_NOT_ALLOWED)
2381 if (httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2382 return (0);
2383
2384 if (code == HTTP_UNAUTHORIZED)
2385 {
2386 int auth_type; /* Authentication type */
2387
2388
2389 if (!con->best || con->best->type == AUTH_NONE)
2390 auth_type = DefaultAuthType;
2391 else
2392 auth_type = con->best->type;
2393
2394 if (auth_type != AUTH_DIGEST)
2395 {
2396 if (httpPrintf(HTTP(con),
2397 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2398 return (0);
2399 }
2400 else
2401 {
2402 if (httpPrintf(HTTP(con),
2403 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2404 con->http.hostname) < 0)
2405 return (0);
2406 }
2407 }
2408
2409 if (con->language != NULL)
2410 {
2411 if (httpPrintf(HTTP(con), "Content-Language: %s\r\n",
2412 con->language->language) < 0)
2413 return (0);
2414 }
2415
2416 if (type != NULL)
2417 {
2418 if (!strcmp(type, "text/html"))
2419 {
2420 if (httpPrintf(HTTP(con),
2421 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2422 return (0);
2423 }
2424 else if (httpPrintf(HTTP(con), "Content-Type: %s\r\n", type) < 0)
2425 return (0);
2426 }
2427
2428 return (1);
2429 }
2430
2431
2432 /*
2433 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2434 */
2435
2436 void
2437 cupsdUpdateCGI(void)
2438 {
2439 char *ptr, /* Pointer to end of line in buffer */
2440 message[1024]; /* Pointer to message text */
2441 int loglevel; /* Log level for message */
2442
2443
2444 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2445 message, sizeof(message))) != NULL)
2446 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2447 break;
2448
2449 if (ptr == NULL && errno)
2450 {
2451 /*
2452 * Fatal error on pipe - should never happen!
2453 */
2454
2455 cupsdLogMessage(CUPSD_LOG_CRIT,
2456 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2457 strerror(errno));
2458 }
2459 }
2460
2461
2462 /*
2463 * 'cupsdWriteClient()' - Write data to a client as needed.
2464 */
2465
2466 int /* O - 1 if success, 0 if fail */
2467 cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2468 {
2469 int bytes; /* Number of bytes written */
2470 char buf[16385]; /* Data buffer */
2471 char *bufptr; /* Pointer into buffer */
2472 ipp_state_t ipp_state; /* IPP state value */
2473
2474
2475 #ifdef DEBUG
2476 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2477 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2478 "pipe_pid=%d state=%d",
2479 con, con->http.fd, con->response, con->file, con->pipe_pid,
2480 con->http.state);
2481 #endif /* DEBUG */
2482
2483 if (con->http.state != HTTP_GET_SEND &&
2484 con->http.state != HTTP_POST_SEND)
2485 return (1);
2486
2487 if (con->response != NULL)
2488 {
2489 ipp_state = ippWrite(&(con->http), con->response);
2490 bytes = ipp_state != IPP_ERROR && ipp_state != IPP_DATA;
2491 }
2492 else if ((bytes = read(con->file, buf, sizeof(buf) - 1)) > 0)
2493 {
2494 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2495 "cupsdWriteClient: Read %d bytes from file %d...",
2496 bytes, con->file);
2497
2498 if (con->pipe_pid && !con->got_fields)
2499 {
2500 /*
2501 * Inspect the data for Content-Type and other fields.
2502 */
2503
2504 buf[bytes] = '\0';
2505
2506 for (bufptr = buf; !con->got_fields && *bufptr; bufptr ++)
2507 if (*bufptr == '\n')
2508 {
2509 /*
2510 * Send line to client...
2511 */
2512
2513 if (bufptr > buf && bufptr[-1] == '\r')
2514 bufptr[-1] = '\0';
2515 *bufptr++ = '\0';
2516
2517 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Script header: %s", buf);
2518
2519 if (!con->sent_header)
2520 {
2521 /*
2522 * Handle redirection and CGI status codes...
2523 */
2524
2525 if (!strncasecmp(buf, "Location:", 9))
2526 cupsdSendHeader(con, HTTP_SEE_OTHER, NULL);
2527 else if (!strncasecmp(buf, "Status:", 7))
2528 cupsdSendHeader(con, atoi(buf + 7), NULL);
2529 else
2530 cupsdSendHeader(con, HTTP_OK, NULL);
2531
2532 if (con->http.version == HTTP_1_1)
2533 {
2534 con->http.data_encoding = HTTP_ENCODE_CHUNKED;
2535
2536 if (httpPrintf(HTTP(con), "Transfer-Encoding: chunked\r\n") < 0)
2537 return (0);
2538 }
2539
2540 con->sent_header = 1;
2541 }
2542
2543 if (strncasecmp(buf, "Status:", 7))
2544 httpPrintf(HTTP(con), "%s\r\n", buf);
2545
2546 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d %s",
2547 con->http.fd, buf);
2548
2549 /*
2550 * Update buffer...
2551 */
2552
2553 bytes -= (bufptr - buf);
2554 memmove(buf, bufptr, bytes + 1);
2555 bufptr = buf - 1;
2556
2557 /*
2558 * See if the line was empty...
2559 */
2560
2561 if (con->field_col == 0)
2562 con->got_fields = 1;
2563 else
2564 con->field_col = 0;
2565 }
2566 else if (*bufptr != '\r')
2567 con->field_col ++;
2568
2569 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2570 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2571 con->http.fd, bytes, con->got_fields);
2572
2573 if (bytes > 0 && !con->got_fields)
2574 {
2575 /*
2576 * Remaining text needs to go out...
2577 */
2578
2579 httpPrintf(HTTP(con), "%s", buf);
2580
2581 con->http.activity = time(NULL);
2582 return (1);
2583 }
2584 else if (bytes == 0)
2585 {
2586 con->http.activity = time(NULL);
2587 return (1);
2588 }
2589 }
2590
2591 if (httpWrite(HTTP(con), buf, bytes) < 0)
2592 {
2593 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2594 "cupsdWriteClient: %d Write of %d bytes failed!",
2595 con->http.fd, bytes);
2596
2597 cupsdCloseClient(con);
2598 return (0);
2599 }
2600
2601 con->bytes += bytes;
2602
2603 if (con->http.state == HTTP_WAITING)
2604 bytes = 0;
2605 }
2606
2607 if (bytes <= 0)
2608 {
2609 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d bytes < 0",
2610 con->http.fd);
2611
2612 cupsdLogRequest(con, HTTP_OK);
2613
2614 httpFlushWrite(HTTP(con));
2615
2616 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED)
2617 {
2618 if (httpPrintf(HTTP(con), "0\r\n\r\n") < 0)
2619 {
2620 cupsdCloseClient(con);
2621 return (0);
2622 }
2623 }
2624
2625 con->http.state = HTTP_WAITING;
2626
2627 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2628 "cupsdWriteClient: Removing fd %d from OutputSet...",
2629 con->http.fd);
2630
2631 FD_CLR(con->http.fd, OutputSet);
2632
2633 if (con->file >= 0)
2634 {
2635 if (FD_ISSET(con->file, InputSet))
2636 {
2637 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2638 "cupsdWriteClient: Removing fd %d from InputSet...",
2639 con->file);
2640 FD_CLR(con->file, InputSet);
2641 }
2642
2643 if (con->pipe_pid)
2644 cupsdEndProcess(con->pipe_pid, 0);
2645
2646 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2647 "cupsdWriteClient: %d Closing data file %d.",
2648 con->http.fd, con->file);
2649
2650 close(con->file);
2651 con->file = -1;
2652 con->pipe_pid = 0;
2653 }
2654
2655 if (con->filename)
2656 {
2657 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2658 "cupsdWriteClient: %d Removing temp file %s",
2659 con->http.fd, con->filename);
2660 unlink(con->filename);
2661 cupsdClearString(&con->filename);
2662 }
2663
2664 if (con->request != NULL)
2665 {
2666 ippDelete(con->request);
2667 con->request = NULL;
2668 }
2669
2670 if (con->response != NULL)
2671 {
2672 ippDelete(con->response);
2673 con->response = NULL;
2674 }
2675
2676 cupsdClearString(&con->command);
2677 cupsdClearString(&con->options);
2678
2679 if (!con->http.keep_alive)
2680 {
2681 cupsdCloseClient(con);
2682 return (0);
2683 }
2684 }
2685 else
2686 {
2687 con->file_ready = 0;
2688
2689 if (con->pipe_pid && !FD_ISSET(con->file, InputSet))
2690 {
2691 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2692 "cupsdWriteClient: Adding fd %d to InputSet...",
2693 con->file);
2694 FD_SET(con->file, InputSet);
2695 }
2696 }
2697
2698 con->http.activity = time(NULL);
2699
2700 return (1);
2701 }
2702
2703
2704 /*
2705 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2706 */
2707
2708 static int /* O - 1 if modified since */
2709 check_if_modified(
2710 cupsd_client_t *con, /* I - Client connection */
2711 struct stat *filestats) /* I - File information */
2712 {
2713 char *ptr; /* Pointer into field */
2714 time_t date; /* Time/date value */
2715 off_t size; /* Size/length value */
2716
2717
2718 size = 0;
2719 date = 0;
2720 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
2721
2722 if (*ptr == '\0')
2723 return (1);
2724
2725 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2726 "check_if_modified: %d If-Modified-Since=\"%s\"",
2727 con->http.fd, ptr);
2728
2729 while (*ptr != '\0')
2730 {
2731 while (isspace(*ptr) || *ptr == ';')
2732 ptr ++;
2733
2734 if (strncasecmp(ptr, "length=", 7) == 0)
2735 {
2736 ptr += 7;
2737 size = strtoll(ptr, NULL, 10);
2738
2739 while (isdigit(*ptr))
2740 ptr ++;
2741 }
2742 else if (isalpha(*ptr))
2743 {
2744 date = httpGetDateTime(ptr);
2745 while (*ptr != '\0' && *ptr != ';')
2746 ptr ++;
2747 }
2748 }
2749
2750 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2751 "check_if_modified: %d sizes=" CUPS_LLFMT ","
2752 CUPS_LLFMT " dates=%d,%d",
2753 con->http.fd, CUPS_LLCAST size,
2754 CUPS_LLCAST filestats->st_size, (int)date,
2755 (int)filestats->st_mtime);
2756
2757 return ((size != filestats->st_size && size != 0) ||
2758 (date < filestats->st_mtime && date != 0) ||
2759 (size == 0 && date == 0));
2760 }
2761
2762
2763 #ifdef HAVE_CDSASSL
2764 /*
2765 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2766 * required by SSLSetCertificate.
2767 *
2768 * For now we assumes that there is exactly one SecIdentity in the
2769 * keychain - i.e. there is exactly one matching cert/private key pair.
2770 * In the future we will search a keychain for a SecIdentity matching a
2771 * specific criteria. We also skip the operation of adding additional
2772 * non-signing certs from the keychain to the CFArrayRef.
2773 *
2774 * To create a self-signed certificate for testing use the certtool.
2775 * Executing the following as root will do it:
2776 *
2777 * certtool c c v k=CUPS
2778 */
2779
2780 static CFArrayRef /* O - Array of certificates */
2781 get_cdsa_server_certs(void)
2782 {
2783 OSStatus err; /* Error info */
2784 SecKeychainRef kcRef; /* Keychain reference */
2785 SecIdentitySearchRef srchRef; /* Search reference */
2786 SecIdentityRef identity; /* Identity */
2787 CFArrayRef ca; /* Certificate array */
2788
2789
2790 kcRef = NULL;
2791 srchRef = NULL;
2792 identity = NULL;
2793 ca = NULL;
2794 err = SecKeychainOpen(ServerCertificate, &kcRef);
2795
2796 if (err)
2797 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\", error %d.",
2798 ServerCertificate, (int)err);
2799 else
2800 {
2801 /*
2802 * Search for "any" identity matching specified key use;
2803 * in this app, we expect there to be exactly one.
2804 */
2805
2806 err = SecIdentitySearchCreate(kcRef, CSSM_KEYUSE_SIGN, &srchRef);
2807
2808 if (err)
2809 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2810 "Cannot find signing key in keychain \"%s\", error %d",
2811 ServerCertificate, (int)err);
2812 else
2813 {
2814 err = SecIdentitySearchCopyNext(srchRef, &identity);
2815
2816 if (err)
2817 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2818 "Cannot find signing key in keychain \"%s\", error %d",
2819 ServerCertificate, (int)err);
2820 else
2821 {
2822 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
2823 cupsdLogMessage(CUPSD_LOG_ERROR,
2824 "SecIdentitySearchCopyNext CFTypeID failure!");
2825 else
2826 {
2827 /*
2828 * Found one. Place it in a CFArray.
2829 * TBD: snag other (non-identity) certs from keychain and add them
2830 * to array as well.
2831 */
2832
2833 ca = CFArrayCreate(NULL, (const void **)&identity, 1, NULL);
2834
2835 if (ca == nil)
2836 cupsdLogMessage(CUPSD_LOG_ERROR, "CFArrayCreate error");
2837 }
2838
2839 /*CFRelease(identity);*/
2840 }
2841
2842 /*CFRelease(srchRef);*/
2843 }
2844
2845 /*CFRelease(kcRef);*/
2846 }
2847
2848 return (ca);
2849 }
2850 #endif /* HAVE_CDSASSL */
2851
2852
2853 /*
2854 * 'get_file()' - Get a filename and state info.
2855 */
2856
2857 static char * /* O - Real filename */
2858 get_file(cupsd_client_t *con, /* I - Client connection */
2859 struct stat *filestats, /* O - File information */
2860 char *filename, /* IO - Filename buffer */
2861 int len) /* I - Buffer length */
2862 {
2863 int status; /* Status of filesystem calls */
2864 char *ptr; /* Pointer info filename */
2865 int plen; /* Remaining length after pointer */
2866
2867
2868 /*
2869 * Need to add DocumentRoot global...
2870 */
2871
2872 if (!strncmp(con->uri, "/ppd/", 5))
2873 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
2874 else if (!strncmp(con->uri, "/admin/conf/", 12))
2875 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
2876 else if (!strncmp(con->uri, "/admin/log/", 11))
2877 {
2878 if (!strcmp(con->uri + 11, "access_log") && AccessLog[0] == '/')
2879 strlcpy(filename, AccessLog, len);
2880 else if (!strcmp(con->uri + 11, "error_log") && ErrorLog[0] == '/')
2881 strlcpy(filename, ErrorLog, len);
2882 else if (!strcmp(con->uri + 11, "page_log") && PageLog[0] == '/')
2883 strlcpy(filename, PageLog, len);
2884 else
2885 return (NULL);
2886 }
2887 else if (con->language != NULL)
2888 snprintf(filename, len, "%s/%s%s", DocumentRoot, con->language->language,
2889 con->uri);
2890 else
2891 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
2892
2893 if ((ptr = strchr(filename, '?')) != NULL)
2894 *ptr = '\0';
2895
2896 /*
2897 * Grab the status for this language; if there isn't a language-specific file
2898 * then fallback to the default one...
2899 */
2900
2901 if ((status = stat(filename, filestats)) != 0 && con->language != NULL)
2902 {
2903 /*
2904 * Drop the language prefix and try the current directory...
2905 */
2906
2907 if (strncmp(con->uri, "/ppd/", 5) &&
2908 strncmp(con->uri, "/admin/conf/", 12) &&
2909 strncmp(con->uri, "/admin/log/", 11))
2910 {
2911 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
2912
2913 if ((ptr = strchr(filename, '?')) != NULL)
2914 *ptr = '\0';
2915
2916 status = stat(filename, filestats);
2917 }
2918 }
2919
2920 /*
2921 * If we're found a directory, get the index.html file instead...
2922 */
2923
2924 if (!status && S_ISDIR(filestats->st_mode))
2925 {
2926 if (filename[strlen(filename) - 1] != '/')
2927 strlcat(filename, "/", len);
2928
2929 ptr = filename + strlen(filename);
2930 plen = len - (ptr - filename);
2931
2932 strlcpy(ptr, "index.html", plen);
2933 status = stat(filename, filestats);
2934
2935 #ifdef HAVE_JAVA
2936 if (status)
2937 {
2938 strlcpy(ptr, "index.class", plen);
2939 status = stat(filename, filestats);
2940 }
2941 #endif /* HAVE_JAVA */
2942
2943 #ifdef HAVE_PERL
2944 if (status)
2945 {
2946 strlcpy(ptr, "index.pl", plen);
2947 status = stat(filename, filestats);
2948 }
2949 #endif /* HAVE_PERL */
2950
2951 #ifdef HAVE_PHP
2952 if (status)
2953 {
2954 strlcpy(ptr, "index.php", plen);
2955 status = stat(filename, filestats);
2956 }
2957 #endif /* HAVE_PHP */
2958
2959 #ifdef HAVE_PYTHON
2960 if (status)
2961 {
2962 strlcpy(ptr, "index.pyc", plen);
2963 status = stat(filename, filestats);
2964 }
2965
2966 if (status)
2967 {
2968 strlcpy(ptr, "index.py", plen);
2969 status = stat(filename, filestats);
2970 }
2971 #endif /* HAVE_PYTHON */
2972 }
2973
2974 cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_file: %d filename=%s size=%d",
2975 con->http.fd, filename,
2976 status ? -1 : (int)filestats->st_size);
2977
2978 if (!status)
2979 con->http.data_remaining = (int)filestats->st_size;
2980
2981 if (status)
2982 return (NULL);
2983 else
2984 return (filename);
2985 }
2986
2987
2988 /*
2989 * 'install_conf_file()' - Install a configuration file.
2990 */
2991
2992 static http_status_t /* O - Status */
2993 install_conf_file(cupsd_client_t *con) /* I - Connection */
2994 {
2995 cups_file_t *in, /* Input file */
2996 *out; /* Output file */
2997 char buffer[1024]; /* Copy buffer */
2998 int bytes; /* Number of bytes */
2999 char conffile[1024], /* Configuration filename */
3000 newfile[1024], /* New config filename */
3001 oldfile[1024]; /* Old config filename */
3002 struct stat confinfo; /* Config file info */
3003
3004
3005 /*
3006 * First construct the filenames...
3007 */
3008
3009 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3010 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3011 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3012
3013 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3014
3015 /*
3016 * Get the owner, group, and permissions of the configuration file.
3017 * If it doesn't exist, assign it to the User and Group in the
3018 * cupsd.conf file with mode 0640 permissions.
3019 */
3020
3021 if (stat(conffile, &confinfo))
3022 {
3023 confinfo.st_uid = User;
3024 confinfo.st_gid = Group;
3025 confinfo.st_mode = ConfigFilePerm;
3026 }
3027
3028 /*
3029 * Open the request file and new config file...
3030 */
3031
3032 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3033 {
3034 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3035 con->filename, strerror(errno));
3036 return (HTTP_SERVER_ERROR);
3037 }
3038
3039 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3040 {
3041 cupsFileClose(in);
3042 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3043 newfile, strerror(errno));
3044 return (HTTP_SERVER_ERROR);
3045 }
3046
3047 fchmod(cupsFileNumber(out), confinfo.st_mode);
3048 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3049
3050 /*
3051 * Copy from the request to the new config file...
3052 */
3053
3054 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3055 if (cupsFileWrite(out, buffer, bytes) < bytes)
3056 {
3057 cupsdLogMessage(CUPSD_LOG_ERROR,
3058 "Unable to copy to config file \"%s\" - %s",
3059 newfile, strerror(errno));
3060
3061 cupsFileClose(in);
3062 cupsFileClose(out);
3063 unlink(newfile);
3064
3065 return (HTTP_SERVER_ERROR);
3066 }
3067
3068 /*
3069 * Close the files...
3070 */
3071
3072 cupsFileClose(in);
3073 if (cupsFileClose(out))
3074 {
3075 cupsdLogMessage(CUPSD_LOG_ERROR,
3076 "Error file closing config file \"%s\" - %s",
3077 newfile, strerror(errno));
3078
3079 unlink(newfile);
3080
3081 return (HTTP_SERVER_ERROR);
3082 }
3083
3084 /*
3085 * Remove the request file...
3086 */
3087
3088 unlink(con->filename);
3089 cupsdClearString(&con->filename);
3090
3091 /*
3092 * Unlink the old backup, rename the current config file to the backup
3093 * filename, and rename the new config file to the config file name...
3094 */
3095
3096 if (unlink(oldfile))
3097 if (errno != ENOENT)
3098 {
3099 cupsdLogMessage(CUPSD_LOG_ERROR,
3100 "Unable to remove backup config file \"%s\" - %s",
3101 oldfile, strerror(errno));
3102
3103 unlink(newfile);
3104
3105 return (HTTP_SERVER_ERROR);
3106 }
3107
3108 if (rename(conffile, oldfile))
3109 if (errno != ENOENT)
3110 {
3111 cupsdLogMessage(CUPSD_LOG_ERROR,
3112 "Unable to rename old config file \"%s\" - %s",
3113 conffile, strerror(errno));
3114
3115 unlink(newfile);
3116
3117 return (HTTP_SERVER_ERROR);
3118 }
3119
3120 if (rename(newfile, conffile))
3121 {
3122 cupsdLogMessage(CUPSD_LOG_ERROR,
3123 "Unable to rename new config file \"%s\" - %s",
3124 newfile, strerror(errno));
3125
3126 rename(oldfile, conffile);
3127 unlink(newfile);
3128
3129 return (HTTP_SERVER_ERROR);
3130 }
3131
3132 /*
3133 * If the cupsd.conf file was updated, set the NeedReload flag...
3134 */
3135
3136 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3137 NeedReload = RELOAD_CUPSD;
3138 else
3139 NeedReload = RELOAD_ALL;
3140
3141 ReloadTime = time(NULL);
3142
3143 /*
3144 * Return that the file was created successfully...
3145 */
3146
3147 return (HTTP_CREATED);
3148 }
3149
3150
3151 /*
3152 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3153 */
3154
3155 static int /* O - 0 if relative, 1 if absolute */
3156 is_path_absolute(const char *path) /* I - Input path */
3157 {
3158 /*
3159 * Check for a leading slash...
3160 */
3161
3162 if (path[0] != '/')
3163 return (0);
3164
3165 /*
3166 * Check for "/.." in the path...
3167 */
3168
3169 while ((path = strstr(path, "/..")) != NULL)
3170 {
3171 if (!path[3] || path[3] == '/')
3172 return (0);
3173
3174 path ++;
3175 }
3176
3177 /*
3178 * If we haven't found any relative paths, return 1 indicating an
3179 * absolute path...
3180 */
3181
3182 return (1);
3183 }
3184
3185
3186 /*
3187 * 'pipe_command()' - Pipe the output of a command to the remote client.
3188 */
3189
3190 static int /* O - Process ID */
3191 pipe_command(cupsd_client_t *con, /* I - Client connection */
3192 int infile, /* I - Standard input for command */
3193 int *outfile, /* O - Standard output for command */
3194 char *command, /* I - Command to run */
3195 char *options, /* I - Options for command */
3196 int root) /* I - Run as root? */
3197 {
3198 int i; /* Looping var */
3199 int pid; /* Process ID */
3200 char *commptr; /* Command string pointer */
3201 char *uriptr; /* URI string pointer */
3202 int fds[2]; /* Pipe FDs */
3203 int argc; /* Number of arguments */
3204 int envc; /* Number of environment variables */
3205 char argbuf[10240], /* Argument buffer */
3206 *argv[100], /* Argument strings */
3207 *envp[100]; /* Environment variables */
3208 char content_length[1024], /* CONTENT_LENGTH environment variable */
3209 content_type[1024], /* CONTENT_TYPE environment variable */
3210 http_cookie[32768], /* HTTP_COOKIE environment variable */
3211 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
3212 lang[1024], /* LANG environment variable */
3213 *query_string, /* QUERY_STRING env variable */
3214 remote_addr[1024], /* REMOTE_ADDR environment variable */
3215 remote_host[1024], /* REMOTE_HOST environment variable */
3216 remote_user[1024], /* REMOTE_USER environment variable */
3217 script_name[1024], /* SCRIPT_NAME environment variable */
3218 server_name[1024], /* SERVER_NAME environment variable */
3219 server_port[1024]; /* SERVER_PORT environment variable */
3220
3221
3222 /*
3223 * Parse a copy of the options string, which is of the form:
3224 *
3225 * name argument+argument+argument
3226 * name?argument+argument+argument
3227 * name param=value&param=value
3228 * name?param=value&param=value
3229 *
3230 * If the string contains an "=" character after the initial name,
3231 * then we treat it as a HTTP GET form request and make a copy of
3232 * the remaining string for the environment variable.
3233 *
3234 * The string is always parsed out as command-line arguments, to
3235 * be consistent with Apache...
3236 */
3237
3238 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3239 "pipe_command: command=\"%s\", options=\"%s\"",
3240 command, options);
3241
3242 strlcpy(argbuf, options, sizeof(argbuf));
3243
3244 argv[0] = argbuf;
3245 query_string = NULL;
3246
3247 for (commptr = argbuf, argc = 1; *commptr != '\0' && argc < 99; commptr ++)
3248 {
3249 /*
3250 * Break arguments whenever we see a + or space...
3251 */
3252
3253 if (*commptr == ' ' || *commptr == '+' || (*commptr == '?' && argc == 1))
3254 {
3255 /*
3256 * Terminate the current string and skip trailing whitespace...
3257 */
3258
3259 *commptr++ = '\0';
3260
3261 while (*commptr == ' ')
3262 commptr ++;
3263
3264 /*
3265 * If we don't have a blank string, save it as another argument...
3266 */
3267
3268 if (*commptr)
3269 {
3270 argv[argc] = commptr;
3271 argc ++;
3272 }
3273 else
3274 break;
3275
3276 /*
3277 * If we see an "=" in the remaining string, make a copy of it since
3278 * it will be query data...
3279 */
3280
3281 if (argc == 2 && strchr(commptr, '=') && con->operation == HTTP_GET)
3282 cupsdSetStringf(&query_string, "QUERY_STRING=%s", commptr);
3283
3284 /*
3285 * Don't skip the first non-blank character...
3286 */
3287
3288 commptr --;
3289 }
3290 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
3291 isxdigit(commptr[2] & 255))
3292 {
3293 /*
3294 * Convert the %xx notation to the individual character.
3295 */
3296
3297 if (commptr[1] >= '0' && commptr[1] <= '9')
3298 *commptr = (commptr[1] - '0') << 4;
3299 else
3300 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
3301
3302 if (commptr[2] >= '0' && commptr[2] <= '9')
3303 *commptr |= commptr[2] - '0';
3304 else
3305 *commptr |= tolower(commptr[2]) - 'a' + 10;
3306
3307 _cups_strcpy(commptr + 1, commptr + 3);
3308
3309 /*
3310 * Check for a %00 and break if that is the case...
3311 */
3312
3313 if (!*commptr)
3314 break;
3315 }
3316 }
3317
3318 argv[argc] = NULL;
3319
3320 if (argv[0][0] == '\0')
3321 argv[0] = strrchr(command, '/') + 1;
3322
3323 /*
3324 * Setup the environment variables as needed...
3325 */
3326
3327 if (con->language)
3328 snprintf(lang, sizeof(lang), "LANG=%s.UTF-8", con->language->language);
3329 else
3330 strcpy(lang, "LANG=C");
3331
3332 strcpy(remote_addr, "REMOTE_ADDR=");
3333 httpAddrString(con->http.hostaddr, remote_addr + 12,
3334 sizeof(remote_addr) - 12);
3335
3336 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
3337 con->http.hostname);
3338
3339 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
3340 if ((uriptr = strchr(script_name, '?')) != NULL)
3341 *uriptr = '\0';
3342
3343 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
3344
3345 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3346 con->servername);
3347
3348 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
3349
3350 envp[envc ++] = lang;
3351 envp[envc ++] = "REDIRECT_STATUS=1";
3352 envp[envc ++] = server_name;
3353 envp[envc ++] = server_port;
3354 envp[envc ++] = remote_addr;
3355 envp[envc ++] = remote_host;
3356 envp[envc ++] = script_name;
3357
3358 if (con->username[0])
3359 {
3360 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
3361
3362 envp[envc ++] = remote_user;
3363 }
3364
3365 if (con->http.version == HTTP_1_1)
3366 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
3367 else if (con->http.version == HTTP_1_0)
3368 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
3369 else
3370 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
3371
3372 if (con->http.cookie)
3373 {
3374 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
3375 con->http.cookie);
3376 envp[envc ++] = http_cookie;
3377 }
3378
3379 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
3380 {
3381 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
3382 con->http.fields[HTTP_FIELD_USER_AGENT]);
3383 envp[envc ++] = http_user_agent;
3384 }
3385
3386 if (con->operation == HTTP_GET)
3387 {
3388 for (i = 0; i < argc; i ++)
3389 cupsdLogMessage(CUPSD_LOG_DEBUG2, "argv[%d] = \"%s\"", i, argv[i]);
3390
3391 envp[envc ++] = "REQUEST_METHOD=GET";
3392
3393 if (query_string)
3394 {
3395 /*
3396 * Add GET form variables after ?...
3397 */
3398
3399 envp[envc ++] = query_string;
3400 }
3401 }
3402 else
3403 {
3404 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT, con->bytes);
3405 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
3406 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
3407
3408 envp[envc ++] = "REQUEST_METHOD=POST";
3409 envp[envc ++] = content_length;
3410 envp[envc ++] = content_type;
3411 }
3412
3413 /*
3414 * Tell the CGI if we are using encryption...
3415 */
3416
3417 if (con->http.encryption == HTTP_ENCRYPT_ALWAYS)
3418 envp[envc ++] = "HTTPS=ON";
3419
3420 /*
3421 * Terminate the environment array...
3422 */
3423
3424 envp[envc] = NULL;
3425
3426 if (LogLevel == CUPSD_LOG_DEBUG2)
3427 {
3428 for (i = 0; i < argc; i ++)
3429 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3430 "pipe_command: argv[%d] = \"%s\"", i, argv[i]);
3431 for (i = 0; i < envc; i ++)
3432 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3433 "pipe_command: envp[%d] = \"%s\"", i, envp[i]);
3434 }
3435
3436 /*
3437 * Create a pipe for the output...
3438 */
3439
3440 if (cupsdOpenPipe(fds))
3441 {
3442 cupsdClearString(&query_string);
3443
3444 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create pipes for CGI %s - %s",
3445 argv[0], strerror(errno));
3446 return (0);
3447 }
3448
3449 /*
3450 * Then execute the command...
3451 */
3452
3453 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
3454 -1, root, &pid) < 0)
3455 {
3456 /*
3457 * Error - can't fork!
3458 */
3459
3460 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork for CGI %s - %s", argv[0],
3461 strerror(errno));
3462
3463 cupsdClosePipe(fds);
3464 pid = 0;
3465 }
3466 else
3467 {
3468 /*
3469 * Fork successful - return the PID...
3470 */
3471
3472 if (con->username[0])
3473 cupsdAddCert(pid, con->username);
3474
3475 cupsdLogMessage(CUPSD_LOG_DEBUG, "CGI %s started - PID = %d", command, pid);
3476
3477 *outfile = fds[0];
3478 close(fds[1]);
3479 }
3480
3481 cupsdClearString(&query_string);
3482
3483 return (pid);
3484 }
3485
3486
3487 /*
3488 * End of "$Id: client.c 4950 2006-01-19 16:07:57Z mike $".
3489 */