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