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