]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/client.c
Save work - almost have "make check" working again (some logging and cups-driverd
[thirdparty/cups.git] / scheduler / client.c
1 /*
2 * "$Id$"
3 *
4 * Client routines for the CUPS scheduler.
5 *
6 * Copyright 2007-2013 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
19 /*
20 * Include necessary headers...
21 */
22
23 #define _CUPS_NO_DEPRECATED
24 #define _HTTP_NO_PRIVATE
25 #include "cupsd.h"
26
27 #ifdef __APPLE__
28 # include <libproc.h>
29 #endif /* __APPLE__ */
30 #ifdef HAVE_TCPD_H
31 # include <tcpd.h>
32 #endif /* HAVE_TCPD_H */
33
34
35 /*
36 * Local globals...
37 */
38
39 static const char * const ipp_states[] =
40 { /* IPP state strings */
41 "IPP_IDLE",
42 "IPP_HEADER",
43 "IPP_ATTRIBUTE",
44 "IPP_STATE_DATA"
45 };
46
47
48 /*
49 * Local functions...
50 */
51
52 static int check_if_modified(cupsd_client_t *con,
53 struct stat *filestats);
54 static int compare_clients(cupsd_client_t *a, cupsd_client_t *b,
55 void *data);
56 static char *get_file(cupsd_client_t *con, struct stat *filestats,
57 char *filename, int len);
58 static http_status_t install_cupsd_conf(cupsd_client_t *con);
59 static int is_cgi(cupsd_client_t *con, const char *filename,
60 struct stat *filestats, mime_type_t *type);
61 static int is_path_absolute(const char *path);
62 static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
63 char *command, char *options, int root);
64 static int valid_host(cupsd_client_t *con);
65 static int write_file(cupsd_client_t *con, http_status_t code,
66 char *filename, char *type,
67 struct stat *filestats);
68 static void write_pipe(cupsd_client_t *con);
69
70
71 /*
72 * 'cupsdAcceptClient()' - Accept a new client.
73 */
74
75 void
76 cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
77 {
78 const char *hostname; /* Hostname of client */
79 char name[256]; /* Hostname of client */
80 int count; /* Count of connections on a host */
81 cupsd_client_t *con, /* New client pointer */
82 *tempcon; /* Temporary client pointer */
83 socklen_t addrlen; /* Length of address */
84 http_addr_t temp; /* Temporary address variable */
85 static time_t last_dos = 0; /* Time of last DoS attack */
86 #ifdef HAVE_TCPD_H
87 struct request_info wrap_req; /* TCP wrappers request information */
88 #endif /* HAVE_TCPD_H */
89
90
91 cupsdLogMessage(CUPSD_LOG_DEBUG2,
92 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
93 lis, lis->fd, cupsArrayCount(Clients));
94
95 /*
96 * Make sure we don't have a full set of clients already...
97 */
98
99 if (cupsArrayCount(Clients) == MaxClients)
100 return;
101
102 /*
103 * Get a pointer to the next available client...
104 */
105
106 if (!Clients)
107 Clients = cupsArrayNew(NULL, NULL);
108
109 if (!Clients)
110 {
111 cupsdLogMessage(CUPSD_LOG_ERROR,
112 "Unable to allocate memory for clients array!");
113 cupsdPauseListening();
114 return;
115 }
116
117 if (!ActiveClients)
118 ActiveClients = cupsArrayNew((cups_array_func_t)compare_clients, NULL);
119
120 if (!ActiveClients)
121 {
122 cupsdLogMessage(CUPSD_LOG_ERROR,
123 "Unable to allocate memory for active clients array!");
124 cupsdPauseListening();
125 return;
126 }
127
128 if ((con = calloc(1, sizeof(cupsd_client_t))) == NULL)
129 {
130 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to allocate memory for client!");
131 cupsdPauseListening();
132 return;
133 }
134
135 /*
136 * Accept the client and get the remote address...
137 */
138
139 con->number = ++ LastClientNumber;
140 con->file = -1;
141
142 if ((con->http = httpAcceptConnection(lis->fd, 0)) == NULL)
143 {
144 if (errno == ENFILE || errno == EMFILE)
145 cupsdPauseListening();
146
147 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
148 strerror(errno));
149 free(con);
150
151 return;
152 }
153
154 /*
155 * Save the connected address and port number...
156 */
157
158 con->clientaddr = lis->address;
159
160 #if 0 /* ifdef AF_INET6 */
161 /* FIXME: I don't believe this is recommended any longer, and we specifically
162 * disable IPv4-over-IPv6 when we listen...
163 */
164 /*
165 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
166 * can more easily use...
167 */
168
169 if (lis->address.addr.sa_family == AF_INET6 &&
170 httpGetAddress(con->http)->ipv6.sin6_addr.s6_addr32[0] == 0 &&
171 httpGetAddress(con->http)->ipv6.sin6_addr.s6_addr32[1] == 0 &&
172 ntohl(httpGetAddress(con->http)->ipv6.sin6_addr.s6_addr32[2]) == 0xffff)
173 httpGetAddress(con->http)->ipv6.sin6_addr.s6_addr32[2] = 0;
174 #endif /* AF_INET6 */
175
176 /*
177 * Check the number of clients on the same address...
178 */
179
180 for (count = 0, tempcon = (cupsd_client_t *)cupsArrayFirst(Clients);
181 tempcon;
182 tempcon = (cupsd_client_t *)cupsArrayNext(Clients))
183 if (httpAddrEqual(httpGetAddress(tempcon->http), httpGetAddress(con->http)))
184 {
185 count ++;
186 if (count >= MaxClientsPerHost)
187 break;
188 }
189
190 if (count >= MaxClientsPerHost)
191 {
192 if ((time(NULL) - last_dos) >= 60)
193 {
194 last_dos = time(NULL);
195 cupsdLogMessage(CUPSD_LOG_WARN,
196 "Possible DoS attack - more than %d clients connecting "
197 "from %s.",
198 MaxClientsPerHost,
199 httpGetHostname(con->http, name, sizeof(name)));
200 }
201
202 httpClose(con->http);
203 free(con);
204 return;
205 }
206
207 /*
208 * Get the hostname or format the IP address as needed...
209 */
210
211 if (HostNameLookups)
212 hostname = httpResolveHostname(con->http, NULL, 0);
213 else
214 hostname = httpGetHostname(con->http, NULL, 0);
215
216 if (hostname == NULL && HostNameLookups == 2)
217 {
218 /*
219 * Can't have an unresolved IP address with double-lookups enabled...
220 */
221
222 httpClose(con->http);
223
224 cupsdLogClient(con, CUPSD_LOG_WARN,
225 "Name lookup failed - connection from %s closed!",
226 httpGetHostname(con->http, NULL, 0));
227
228 free(con);
229 return;
230 }
231
232 if (HostNameLookups == 2)
233 {
234 /*
235 * Do double lookups as needed...
236 */
237
238 http_addrlist_t *addrlist, /* List of addresses */
239 *addr; /* Current address */
240
241 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, NULL)) != NULL)
242 {
243 /*
244 * See if the hostname maps to the same IP address...
245 */
246
247 for (addr = addrlist; addr; addr = addr->next)
248 if (httpAddrEqual(httpGetAddress(con->http), &(addr->addr)))
249 break;
250 }
251 else
252 addr = NULL;
253
254 httpAddrFreeList(addrlist);
255
256 if (!addr)
257 {
258 /*
259 * Can't have a hostname that doesn't resolve to the same IP address
260 * with double-lookups enabled...
261 */
262
263 httpClose(con->http);
264
265 cupsdLogClient(con, CUPSD_LOG_WARN,
266 "IP lookup failed - connection from %s closed!",
267 httpGetHostname(con->http, NULL, 0));
268 free(con);
269 return;
270 }
271 }
272
273 #ifdef HAVE_TCPD_H
274 /*
275 * See if the connection is denied by TCP wrappers...
276 */
277
278 request_init(&wrap_req, RQ_DAEMON, "cupsd", RQ_FILE, httpGetFd(con->http),
279 NULL);
280 fromhost(&wrap_req);
281
282 if (!hosts_access(&wrap_req))
283 {
284 httpClose(con->http);
285
286 cupsdLogClient(con, CUPSD_LOG_WARN,
287 "Connection from %s refused by /etc/hosts.allow and "
288 "/etc/hosts.deny rules.", httpGetHostname(con->http, NULL, 0));
289 free(con);
290 return;
291 }
292 #endif /* HAVE_TCPD_H */
293
294 #ifdef AF_LOCAL
295 if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
296 {
297 # ifdef __APPLE__
298 socklen_t peersize; /* Size of peer credentials */
299 pid_t peerpid; /* Peer process ID */
300 char peername[256]; /* Name of process */
301
302 peersize = sizeof(peerpid);
303 if (!getsockopt(con->number, SOL_LOCAL, LOCAL_PEERPID, &peerpid,
304 &peersize))
305 {
306 if (!proc_name(peerpid, peername, sizeof(peername)))
307 cupsdLogClient(con, CUPSD_LOG_DEBUG,
308 "Accepted from %s (Domain ???[%d])",
309 httpGetHostname(con->http, NULL, 0), (int)peerpid);
310 else
311 cupsdLogClient(con, CUPSD_LOG_DEBUG,
312 "Accepted from %s (Domain %s[%d])",
313 httpGetHostname(con->http, NULL, 0), name, (int)peerpid);
314 }
315 else
316 # endif /* __APPLE__ */
317
318 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s (Domain)",
319 httpGetHostname(con->http, NULL, 0));
320 }
321 else
322 #endif /* AF_LOCAL */
323 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s:%d (IPv%d)",
324 httpGetHostname(con->http, NULL, 0),
325 httpAddrPort(httpGetAddress(con->http)),
326 httpAddrFamily(httpGetAddress(con->http)) == AF_INET ? 4 : 6);
327
328 /*
329 * Get the local address the client connected to...
330 */
331
332 addrlen = sizeof(temp);
333 if (getsockname(httpGetFd(con->http), (struct sockaddr *)&temp, &addrlen))
334 {
335 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get local address - %s",
336 strerror(errno));
337
338 strlcpy(con->servername, "localhost", sizeof(con->servername));
339 con->serverport = LocalPort;
340 }
341 #ifdef AF_LOCAL
342 else if (httpAddrFamily(&temp) == AF_LOCAL)
343 {
344 strlcpy(con->servername, "localhost", sizeof(con->servername));
345 con->serverport = LocalPort;
346 }
347 #endif /* AF_LOCAL */
348 else
349 {
350 if (httpAddrLocalhost(&temp))
351 strlcpy(con->servername, "localhost", sizeof(con->servername));
352 else if (HostNameLookups)
353 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
354 else
355 httpAddrString(&temp, con->servername, sizeof(con->servername));
356
357 con->serverport = httpAddrPort(&(lis->address));
358 }
359
360 /*
361 * Add the connection to the array of active clients...
362 */
363
364 cupsArrayAdd(Clients, con);
365
366 /*
367 * Add the socket to the server select.
368 */
369
370 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL,
371 con);
372
373 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
374
375 /*
376 * Temporarily suspend accept()'s until we lose a client...
377 */
378
379 if (cupsArrayCount(Clients) == MaxClients)
380 cupsdPauseListening();
381
382 #ifdef HAVE_SSL
383 /*
384 * See if we are connecting on a secure port...
385 */
386
387 if (lis->encryption == HTTP_ENCRYPTION_ALWAYS)
388 {
389 /*
390 * https connection; go secure...
391 */
392
393 if (!cupsdStartTLS(con))
394 cupsdCloseClient(con);
395 }
396 else
397 con->auto_ssl = 1;
398 #endif /* HAVE_SSL */
399 }
400
401
402 /*
403 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
404 */
405
406 void
407 cupsdCloseAllClients(void)
408 {
409 cupsd_client_t *con; /* Current client */
410
411
412 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCloseAllClients() Clients=%d",
413 cupsArrayCount(Clients));
414
415 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
416 con;
417 con = (cupsd_client_t *)cupsArrayNext(Clients))
418 if (cupsdCloseClient(con))
419 cupsdCloseClient(con);
420 }
421
422
423 /*
424 * 'cupsdCloseClient()' - Close a remote client.
425 */
426
427 int /* O - 1 if partial close, 0 if fully closed */
428 cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
429 {
430 int partial; /* Do partial close for SSL? */
431 #ifdef HAVE_LIBSSL
432 #elif defined(HAVE_GNUTLS)
433 # elif defined(HAVE_CDSASSL)
434 #endif /* HAVE_LIBSSL */
435
436
437 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing connection.");
438
439 /*
440 * Flush pending writes before closing...
441 */
442
443 httpFlushWrite(con->http);
444
445 partial = 0;
446
447 if (con->pipe_pid != 0)
448 {
449 /*
450 * Stop any CGI process...
451 */
452
453 cupsdEndProcess(con->pipe_pid, 1);
454 con->pipe_pid = 0;
455 }
456
457 if (con->file >= 0)
458 {
459 cupsdRemoveSelect(con->file);
460
461 close(con->file);
462 con->file = -1;
463 }
464
465 /*
466 * Close the socket and clear the file from the input set for select()...
467 */
468
469 if (httpGetFd(con->http) >= 0)
470 {
471 cupsArrayRemove(ActiveClients, con);
472 cupsdSetBusyState();
473
474 #ifdef HAVE_SSL
475 /*
476 * Shutdown encryption as needed...
477 */
478
479 if (httpIsEncrypted(con->http))
480 partial = 1;
481 #endif /* HAVE_SSL */
482
483 if (partial)
484 {
485 /*
486 * Only do a partial close so that the encrypted client gets everything.
487 */
488
489 httpShutdown(con->http);
490 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
491 NULL, con);
492
493 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for socket close.");
494 }
495 else
496 {
497 /*
498 * Shut the socket down fully...
499 */
500
501 cupsdRemoveSelect(httpGetFd(con->http));
502 httpClose(con->http);
503 con->http = NULL;
504 }
505 }
506
507 if (!partial)
508 {
509 /*
510 * Free memory...
511 */
512
513 cupsdRemoveSelect(httpGetFd(con->http));
514
515 httpClose(con->http);
516
517 cupsdClearString(&con->filename);
518 cupsdClearString(&con->command);
519 cupsdClearString(&con->options);
520 cupsdClearString(&con->query_string);
521
522 if (con->request)
523 {
524 ippDelete(con->request);
525 con->request = NULL;
526 }
527
528 if (con->response)
529 {
530 ippDelete(con->response);
531 con->response = NULL;
532 }
533
534 if (con->language)
535 {
536 cupsLangFree(con->language);
537 con->language = NULL;
538 }
539
540 #ifdef HAVE_AUTHORIZATION_H
541 if (con->authref)
542 {
543 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
544 con->authref = NULL;
545 }
546 #endif /* HAVE_AUTHORIZATION_H */
547
548 /*
549 * Re-enable new client connections if we are going back under the
550 * limit...
551 */
552
553 if (cupsArrayCount(Clients) == MaxClients)
554 cupsdResumeListening();
555
556 /*
557 * Compact the list of clients as necessary...
558 */
559
560 cupsArrayRemove(Clients, con);
561
562 free(con);
563 }
564
565 return (partial);
566 }
567
568
569 #if 0
570 /*
571 * 'cupsdFlushHeader()' - Flush the header fields to the client.
572 */
573
574 int /* I - Bytes written or -1 on error */
575 cupsdFlushHeader(cupsd_client_t *con) /* I - Client to flush to */
576 {
577 int bytes = httpFlushWrite(con->http);
578
579 // TODO: Need to use httpSendResponse
580 con->http->data_encoding = HTTP_ENCODING_LENGTH;
581
582 return (bytes);
583 }
584 #endif /* 0 */
585
586
587 /*
588 * 'cupsdReadClient()' - Read data from a client.
589 */
590
591 void
592 cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
593 {
594 char line[32768], /* Line from client... */
595 operation[64], /* Operation code from socket */
596 locale[64], /* Locale */
597 *ptr; /* Pointer into strings */
598 http_status_t status; /* Transfer status */
599 ipp_state_t ipp_state; /* State of IPP transfer */
600 int bytes; /* Number of bytes to POST */
601 char *filename; /* Name of file for GET/HEAD */
602 char buf[1024]; /* Buffer for real filename */
603 struct stat filestats; /* File information */
604 mime_type_t *type; /* MIME type of file */
605 cupsd_printer_t *p; /* Printer */
606 static unsigned request_id = 0; /* Request ID for temp files */
607
608
609 status = HTTP_STATUS_CONTINUE;
610
611 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
612 "cupsdReadClient "
613 "error=%d, "
614 "used=%d, "
615 "state=%s, "
616 "data_encoding=HTTP_ENCODING_%s, "
617 "data_remaining=" CUPS_LLFMT ", "
618 "request=%p(%s), "
619 "file=%d",
620 httpError(con->http), (int)httpGetReady(con->http),
621 httpStateString(httpGetState(con->http)),
622 httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
623 CUPS_LLCAST httpGetRemaining(con->http),
624 con->request,
625 con->request ? ipp_states[con->request->state] : "",
626 con->file);
627
628 #ifdef HAVE_SSL
629 if (con->auto_ssl)
630 {
631 /*
632 * Automatically check for a SSL/TLS handshake...
633 */
634
635 con->auto_ssl = 0;
636
637 if (recv(httpGetFd(con->http), buf, 1, MSG_PEEK) == 1 &&
638 (!buf[0] || !strchr("DGHOPT", buf[0])))
639 {
640 /*
641 * Encrypt this connection...
642 */
643
644 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
645 "Saw first byte %02X, auto-negotiating "
646 "SSL/TLS session.", buf[0] & 255);
647
648 if (!cupsdStartTLS(con))
649 cupsdCloseClient(con);
650
651 return;
652 }
653 }
654 #endif /* HAVE_SSL */
655
656 switch (httpGetState(con->http))
657 {
658 case HTTP_STATE_WAITING :
659 /*
660 * See if we've received a request line...
661 */
662
663 con->operation = httpReadRequest(con->http, con->uri, sizeof(con->uri));
664 if (con->operation == HTTP_STATE_ERROR ||
665 con->operation == HTTP_STATE_UNKNOWN_METHOD ||
666 con->operation == HTTP_STATE_UNKNOWN_VERSION)
667 {
668 if (httpError(con->http))
669 cupsdLogClient(con, CUPSD_LOG_DEBUG,
670 "HTTP_STATE_WAITING Closing for error %d (%s)",
671 httpError(con->http), strerror(httpError(con->http)));
672 else
673 cupsdLogClient(con, CUPSD_LOG_DEBUG,
674 "HTTP_STATE_WAITING Closing on error: %s",
675 cupsLastErrorString());
676
677 cupsdCloseClient(con);
678 return;
679 }
680
681 /*
682 * Ignore blank request lines...
683 */
684
685 if (con->operation == HTTP_STATE_WAITING)
686 break;
687
688 /*
689 * Clear other state variables...
690 */
691
692 con->bytes = 0;
693 con->file = -1;
694 con->file_ready = 0;
695 con->pipe_pid = 0;
696 con->username[0] = '\0';
697 con->password[0] = '\0';
698
699 cupsdClearString(&con->command);
700 cupsdClearString(&con->options);
701 cupsdClearString(&con->query_string);
702
703 if (con->request)
704 {
705 ippDelete(con->request);
706 con->request = NULL;
707 }
708
709 if (con->response)
710 {
711 ippDelete(con->response);
712 con->response = NULL;
713 }
714
715 if (con->language)
716 {
717 cupsLangFree(con->language);
718 con->language = NULL;
719 }
720
721 #ifdef HAVE_GSSAPI
722 con->have_gss = 0;
723 con->gss_uid = 0;
724 #endif /* HAVE_GSSAPI */
725
726 /*
727 * Handle full URLs in the request line...
728 */
729
730 if (strcmp(con->uri, "*"))
731 {
732 char scheme[HTTP_MAX_URI], /* Method/scheme */
733 userpass[HTTP_MAX_URI], /* Username:password */
734 hostname[HTTP_MAX_URI], /* Hostname */
735 resource[HTTP_MAX_URI]; /* Resource path */
736 int port; /* Port number */
737
738 /*
739 * Separate the URI into its components...
740 */
741
742 if (httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
743 scheme, sizeof(scheme),
744 userpass, sizeof(userpass),
745 hostname, sizeof(hostname), &port,
746 resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
747 {
748 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
749 con->uri);
750 cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
751 cupsdCloseClient(con);
752 return;
753 }
754
755 /*
756 * Only allow URIs with the servername, localhost, or an IP
757 * address...
758 */
759
760 if (strcmp(scheme, "file") &&
761 _cups_strcasecmp(hostname, ServerName) &&
762 _cups_strcasecmp(hostname, "localhost") &&
763 !cupsArrayFind(ServerAlias, hostname) &&
764 !isdigit(hostname[0]) && hostname[0] != '[')
765 {
766 /*
767 * Nope, we don't do proxies...
768 */
769
770 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
771 con->uri);
772 cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
773 cupsdCloseClient(con);
774 return;
775 }
776
777 /*
778 * Copy the resource portion back into the URI; both resource and
779 * con->uri are HTTP_MAX_URI bytes in size...
780 */
781
782 strlcpy(con->uri, resource, sizeof(con->uri));
783 }
784
785 /*
786 * Process the request...
787 */
788
789 gettimeofday(&(con->start), NULL);
790
791 cupsdLogClient(con, CUPSD_LOG_DEBUG, "%s %s HTTP/%d.%d",
792 operation, con->uri,
793 httpGetVersion(con->http) / 100,
794 httpGetVersion(con->http) % 100);
795
796 if (!cupsArrayFind(ActiveClients, con))
797 {
798 cupsArrayAdd(ActiveClients, con);
799 cupsdSetBusyState();
800 }
801
802 case HTTP_STATE_OPTIONS :
803 case HTTP_STATE_DELETE :
804 case HTTP_STATE_GET :
805 case HTTP_STATE_HEAD :
806 case HTTP_STATE_POST :
807 case HTTP_STATE_PUT :
808 case HTTP_STATE_TRACE :
809 /*
810 * Parse incoming parameters until the status changes...
811 */
812
813 while ((status = httpUpdate(con->http)) == HTTP_STATUS_CONTINUE)
814 if (!httpGetReady(con->http))
815 break;
816
817 if (status != HTTP_STATUS_OK && status != HTTP_STATUS_CONTINUE)
818 {
819 if (httpError(con->http) && httpError(con->http) != EPIPE)
820 cupsdLogClient(con, CUPSD_LOG_DEBUG,
821 "Closing for error %d (%s) while reading headers.",
822 httpError(con->http), strerror(httpError(con->http)));
823 else
824 cupsdLogClient(con, CUPSD_LOG_DEBUG,
825 "Closing on EOF while reading headers.");
826
827 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
828 cupsdCloseClient(con);
829 return;
830 }
831 break;
832
833 default :
834 if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
835 {
836 /*
837 * Connection closed...
838 */
839
840 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
841 cupsdCloseClient(con);
842 return;
843 }
844 break; /* Anti-compiler-warning-code */
845 }
846
847 /*
848 * Handle new transfers...
849 */
850
851 if (status == HTTP_STATUS_OK)
852 {
853 if (httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE)[0])
854 {
855 /*
856 * Figure out the locale from the Accept-Language and Content-Type
857 * fields...
858 */
859
860 if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
861 ',')) != NULL)
862 *ptr = '\0';
863
864 if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
865 ';')) != NULL)
866 *ptr = '\0';
867
868 if ((ptr = strstr(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
869 "charset=")) != NULL)
870 {
871 /*
872 * Combine language and charset, and trim any extra params in the
873 * content-type.
874 */
875
876 snprintf(locale, sizeof(locale), "%s.%s",
877 httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE), ptr + 8);
878
879 if ((ptr = strchr(locale, ',')) != NULL)
880 *ptr = '\0';
881 }
882 else
883 snprintf(locale, sizeof(locale), "%s.UTF-8",
884 httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE));
885
886 con->language = cupsLangGet(locale);
887 }
888 else
889 con->language = cupsLangGet(DefaultLocale);
890
891 cupsdAuthorize(con);
892
893 if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
894 "Keep-Alive", 10) && KeepAlive)
895 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_ON);
896 else if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
897 "close", 5))
898 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
899
900 if (!httpGetField(con->http, HTTP_FIELD_HOST)[0] &&
901 httpGetVersion(con->http) >= HTTP_VERSION_1_1)
902 {
903 /*
904 * HTTP/1.1 and higher require the "Host:" field...
905 */
906
907 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
908 {
909 cupsdLogClient(con, CUPSD_LOG_ERROR, "Missing Host: field in request.");
910 cupsdCloseClient(con);
911 return;
912 }
913 }
914 else if (!valid_host(con))
915 {
916 /*
917 * Access to localhost must use "localhost" or the corresponding IPv4
918 * or IPv6 values in the Host: field.
919 */
920
921 cupsdLogClient(con, CUPSD_LOG_ERROR,
922 "Request from \"%s\" using invalid Host: field \"%s\".",
923 httpGetHostname(con->http, NULL, 0), httpGetField(con->http, HTTP_FIELD_HOST));
924
925 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
926 {
927 cupsdCloseClient(con);
928 return;
929 }
930 }
931 else if (con->operation == HTTP_STATE_OPTIONS)
932 {
933 /*
934 * Do OPTIONS command...
935 */
936
937 if (con->best && con->best->type != CUPSD_AUTH_NONE)
938 {
939 if (!cupsdSendHeader(con, HTTP_STATUS_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
940 {
941 cupsdCloseClient(con);
942 return;
943 }
944 }
945
946 if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION), "Upgrade") &&
947 !httpIsEncrypted(con->http))
948 {
949 #ifdef HAVE_SSL
950 /*
951 * Do encryption stuff...
952 */
953
954 # if 0
955 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
956 {
957 cupsdCloseClient(con);
958 return;
959 }
960
961 httpPrintf(con->http, "Connection: Upgrade\r\n");
962 httpPrintf(con->http, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
963 httpPrintf(con->http, "Content-Length: 0\r\n");
964 httpPrintf(con->http, "\r\n");
965
966 if (cupsdFlushHeader(con) < 0)
967 {
968 cupsdCloseClient(con);
969 return;
970 }
971
972 #else
973 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
974 {
975 cupsdCloseClient(con);
976 return;
977 }
978 # endif /* 0 */
979
980 if (!cupsdStartTLS(con))
981 {
982 cupsdCloseClient(con);
983 return;
984 }
985 #else
986 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
987 {
988 cupsdCloseClient(con);
989 return;
990 }
991 #endif /* HAVE_SSL */
992 }
993
994 #if 0
995 if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
996 {
997 cupsdCloseClient(con);
998 return;
999 }
1000
1001 httpPrintf(con->http, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1002 httpPrintf(con->http, "Content-Length: 0\r\n");
1003 httpPrintf(con->http, "\r\n");
1004
1005 if (cupsdFlushHeader(con) < 0)
1006 {
1007 cupsdCloseClient(con);
1008 return;
1009 }
1010 #else
1011 httpSetField(con->http, HTTP_FIELD_ALLOW,
1012 "GET, HEAD, OPTIONS, POST, PUT");
1013 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
1014
1015 if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
1016 {
1017 cupsdCloseClient(con);
1018 return;
1019 }
1020 #endif /* 0 */
1021 }
1022 else if (!is_path_absolute(con->uri))
1023 {
1024 /*
1025 * Protect against malicious users!
1026 */
1027
1028 cupsdLogClient(con, CUPSD_LOG_ERROR,
1029 "Request for non-absolute resource \"%s\".", con->uri);
1030
1031 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1032 {
1033 cupsdCloseClient(con);
1034 return;
1035 }
1036 }
1037 else
1038 {
1039 if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
1040 "Upgrade") && !httpIsEncrypted(con->http))
1041 {
1042 #ifdef HAVE_SSL
1043 /*
1044 * Do encryption stuff...
1045 */
1046
1047 # if 0
1048 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,
1049 CUPSD_AUTH_NONE))
1050 {
1051 cupsdCloseClient(con);
1052 return;
1053 }
1054
1055 httpPrintf(con->http, "Connection: Upgrade\r\n");
1056 httpPrintf(con->http, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1057 httpPrintf(con->http, "Content-Length: 0\r\n");
1058 httpPrintf(con->http, "\r\n");
1059
1060 if (cupsdFlushHeader(con) < 0)
1061 {
1062 cupsdCloseClient(con);
1063 return;
1064 }
1065 # else
1066 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,
1067 CUPSD_AUTH_NONE))
1068 {
1069 cupsdCloseClient(con);
1070 return;
1071 }
1072 # endif /* 0 */
1073
1074 if (!cupsdStartTLS(con))
1075 {
1076 cupsdCloseClient(con);
1077 return;
1078 }
1079 #else
1080 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
1081 {
1082 cupsdCloseClient(con);
1083 return;
1084 }
1085 #endif /* HAVE_SSL */
1086 }
1087
1088 if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_STATUS_OK)
1089 {
1090 cupsdSendError(con, status, CUPSD_AUTH_NONE);
1091 cupsdCloseClient(con);
1092 return;
1093 }
1094
1095 if (httpGetExpect(con->http) &&
1096 (con->operation == HTTP_STATE_POST || con->operation == HTTP_STATE_PUT))
1097 {
1098 if (httpGetExpect(con->http) == HTTP_STATUS_CONTINUE)
1099 {
1100 /*
1101 * Send 100-continue header...
1102 */
1103
1104 if (!cupsdSendHeader(con, HTTP_STATUS_CONTINUE, NULL, CUPSD_AUTH_NONE))
1105 {
1106 cupsdCloseClient(con);
1107 return;
1108 }
1109 }
1110 else
1111 {
1112 /*
1113 * Send 417-expectation-failed header...
1114 */
1115
1116 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
1117
1118 if (!cupsdSendHeader(con, HTTP_STATUS_EXPECTATION_FAILED, NULL,
1119 CUPSD_AUTH_NONE))
1120 {
1121 cupsdCloseClient(con);
1122 return;
1123 }
1124 }
1125 }
1126
1127 switch (httpGetState(con->http))
1128 {
1129 case HTTP_STATE_GET_SEND :
1130 if ((!strncmp(con->uri, "/ppd/", 5) ||
1131 !strncmp(con->uri, "/printers/", 10) ||
1132 !strncmp(con->uri, "/classes/", 9)) &&
1133 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1134 {
1135 /*
1136 * Send PPD file - get the real printer name since printer
1137 * names are not case sensitive but filenames can be...
1138 */
1139
1140 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1141
1142 if (!strncmp(con->uri, "/ppd/", 5))
1143 p = cupsdFindPrinter(con->uri + 5);
1144 else if (!strncmp(con->uri, "/printers/", 10))
1145 p = cupsdFindPrinter(con->uri + 10);
1146 else
1147 {
1148 p = cupsdFindClass(con->uri + 9);
1149
1150 if (p)
1151 {
1152 int i; /* Looping var */
1153
1154 for (i = 0; i < p->num_printers; i ++)
1155 {
1156 if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
1157 {
1158 char ppdname[1024];/* PPD filename */
1159
1160 snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
1161 ServerRoot, p->printers[i]->name);
1162 if (!access(ppdname, 0))
1163 {
1164 p = p->printers[i];
1165 break;
1166 }
1167 }
1168 }
1169
1170 if (i >= p->num_printers)
1171 p = NULL;
1172 }
1173 }
1174
1175 if (p)
1176 {
1177 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1178 }
1179 else
1180 {
1181 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1182 {
1183 cupsdCloseClient(con);
1184 return;
1185 }
1186
1187 break;
1188 }
1189 }
1190 else if ((!strncmp(con->uri, "/icons/", 7) ||
1191 !strncmp(con->uri, "/printers/", 10) ||
1192 !strncmp(con->uri, "/classes/", 9)) &&
1193 !strcmp(con->uri + strlen(con->uri) - 4, ".png"))
1194 {
1195 /*
1196 * Send icon file - get the real queue name since queue names are
1197 * not case sensitive but filenames can be...
1198 */
1199
1200 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".png" */
1201
1202 if (!strncmp(con->uri, "/icons/", 7))
1203 p = cupsdFindPrinter(con->uri + 7);
1204 else if (!strncmp(con->uri, "/printers/", 10))
1205 p = cupsdFindPrinter(con->uri + 10);
1206 else
1207 {
1208 p = cupsdFindClass(con->uri + 9);
1209
1210 if (p)
1211 {
1212 int i; /* Looping var */
1213
1214 for (i = 0; i < p->num_printers; i ++)
1215 {
1216 if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
1217 {
1218 char ppdname[1024];/* PPD filename */
1219
1220 snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
1221 ServerRoot, p->printers[i]->name);
1222 if (!access(ppdname, 0))
1223 {
1224 p = p->printers[i];
1225 break;
1226 }
1227 }
1228 }
1229
1230 if (i >= p->num_printers)
1231 p = NULL;
1232 }
1233 }
1234
1235 if (p)
1236 snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
1237 else
1238 {
1239 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1240 {
1241 cupsdCloseClient(con);
1242 return;
1243 }
1244
1245 break;
1246 }
1247 }
1248 else if (!WebInterface)
1249 {
1250 /*
1251 * Web interface is disabled. Show an appropriate message...
1252 */
1253
1254 if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
1255 {
1256 cupsdCloseClient(con);
1257 return;
1258 }
1259
1260 break;
1261 }
1262
1263 if ((!strncmp(con->uri, "/admin", 6) &&
1264 strncmp(con->uri, "/admin/conf/", 12) &&
1265 strncmp(con->uri, "/admin/log/", 11)) ||
1266 !strncmp(con->uri, "/printers", 9) ||
1267 !strncmp(con->uri, "/classes", 8) ||
1268 !strncmp(con->uri, "/help", 5) ||
1269 !strncmp(con->uri, "/jobs", 5))
1270 {
1271 /*
1272 * Send CGI output...
1273 */
1274
1275 if (!strncmp(con->uri, "/admin", 6))
1276 {
1277 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1278 ServerBin);
1279
1280 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
1281 }
1282 else if (!strncmp(con->uri, "/printers", 9))
1283 {
1284 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1285 ServerBin);
1286
1287 if (con->uri[9] && con->uri[10])
1288 cupsdSetString(&con->options, con->uri + 9);
1289 else
1290 cupsdSetString(&con->options, NULL);
1291 }
1292 else if (!strncmp(con->uri, "/classes", 8))
1293 {
1294 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1295 ServerBin);
1296
1297 if (con->uri[8] && con->uri[9])
1298 cupsdSetString(&con->options, con->uri + 8);
1299 else
1300 cupsdSetString(&con->options, NULL);
1301 }
1302 else if (!strncmp(con->uri, "/jobs", 5))
1303 {
1304 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1305 ServerBin);
1306
1307 if (con->uri[5] && con->uri[6])
1308 cupsdSetString(&con->options, con->uri + 5);
1309 else
1310 cupsdSetString(&con->options, NULL);
1311 }
1312 else
1313 {
1314 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1315 ServerBin);
1316
1317 if (con->uri[5] && con->uri[6])
1318 cupsdSetString(&con->options, con->uri + 5);
1319 else
1320 cupsdSetString(&con->options, NULL);
1321 }
1322
1323 if (!cupsdSendCommand(con, con->command, con->options, 0))
1324 {
1325 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1326 {
1327 cupsdCloseClient(con);
1328 return;
1329 }
1330 }
1331 else
1332 cupsdLogRequest(con, HTTP_STATUS_OK);
1333
1334 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1335 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1336 }
1337 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1338 (strchr(con->uri + 12, '/') ||
1339 strlen(con->uri) == 12)) ||
1340 (!strncmp(con->uri, "/admin/log/", 11) &&
1341 (strchr(con->uri + 11, '/') ||
1342 strlen(con->uri) == 11)))
1343 {
1344 /*
1345 * GET can only be done to configuration files directly under
1346 * /admin/conf...
1347 */
1348
1349 cupsdLogClient(con, CUPSD_LOG_ERROR,
1350 "Request for subdirectory \"%s\"!", con->uri);
1351
1352 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1353 {
1354 cupsdCloseClient(con);
1355 return;
1356 }
1357
1358 break;
1359 }
1360 else
1361 {
1362 /*
1363 * Serve a file...
1364 */
1365
1366 if ((filename = get_file(con, &filestats, buf,
1367 sizeof(buf))) == NULL)
1368 {
1369 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1370 {
1371 cupsdCloseClient(con);
1372 return;
1373 }
1374
1375 break;
1376 }
1377
1378 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1379
1380 if (is_cgi(con, filename, &filestats, type))
1381 {
1382 /*
1383 * Note: con->command and con->options were set by
1384 * is_cgi()...
1385 */
1386
1387 if (!cupsdSendCommand(con, con->command, con->options, 0))
1388 {
1389 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1390 {
1391 cupsdCloseClient(con);
1392 return;
1393 }
1394 }
1395 else
1396 cupsdLogRequest(con, HTTP_STATUS_OK);
1397
1398 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1399 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1400 break;
1401 }
1402
1403 if (!check_if_modified(con, &filestats))
1404 {
1405 if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
1406 {
1407 cupsdCloseClient(con);
1408 return;
1409 }
1410 }
1411 else
1412 {
1413 if (type == NULL)
1414 strlcpy(line, "text/plain", sizeof(line));
1415 else
1416 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1417
1418 if (!write_file(con, HTTP_STATUS_OK, filename, line, &filestats))
1419 {
1420 cupsdCloseClient(con);
1421 return;
1422 }
1423 }
1424 }
1425 break;
1426
1427 case HTTP_STATE_POST_RECV :
1428 /*
1429 * See if the POST request includes a Content-Length field, and if
1430 * so check the length against any limits that are set...
1431 */
1432
1433 if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
1434 MaxRequestSize > 0 &&
1435 httpGetLength2(con->http) > MaxRequestSize)
1436 {
1437 /*
1438 * Request too large...
1439 */
1440
1441 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1442 {
1443 cupsdCloseClient(con);
1444 return;
1445 }
1446
1447 break;
1448 }
1449 else if (httpGetLength2(con->http) < 0)
1450 {
1451 /*
1452 * Negative content lengths are invalid!
1453 */
1454
1455 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
1456 {
1457 cupsdCloseClient(con);
1458 return;
1459 }
1460
1461 break;
1462 }
1463
1464 /*
1465 * See what kind of POST request this is; for IPP requests the
1466 * content-type field will be "application/ipp"...
1467 */
1468
1469 if (!strcmp(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
1470 "application/ipp"))
1471 con->request = ippNew();
1472 else if (!WebInterface)
1473 {
1474 /*
1475 * Web interface is disabled. Show an appropriate message...
1476 */
1477
1478 if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
1479 {
1480 cupsdCloseClient(con);
1481 return;
1482 }
1483
1484 break;
1485 }
1486 else if ((!strncmp(con->uri, "/admin", 6) &&
1487 strncmp(con->uri, "/admin/conf/", 12) &&
1488 strncmp(con->uri, "/admin/log/", 11)) ||
1489 !strncmp(con->uri, "/printers", 9) ||
1490 !strncmp(con->uri, "/classes", 8) ||
1491 !strncmp(con->uri, "/help", 5) ||
1492 !strncmp(con->uri, "/jobs", 5))
1493 {
1494 /*
1495 * CGI request...
1496 */
1497
1498 if (!strncmp(con->uri, "/admin", 6))
1499 {
1500 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1501 ServerBin);
1502
1503 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
1504 }
1505 else if (!strncmp(con->uri, "/printers", 9))
1506 {
1507 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1508 ServerBin);
1509
1510 if (con->uri[9] && con->uri[10])
1511 cupsdSetString(&con->options, con->uri + 9);
1512 else
1513 cupsdSetString(&con->options, NULL);
1514 }
1515 else if (!strncmp(con->uri, "/classes", 8))
1516 {
1517 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1518 ServerBin);
1519
1520 if (con->uri[8] && con->uri[9])
1521 cupsdSetString(&con->options, con->uri + 8);
1522 else
1523 cupsdSetString(&con->options, NULL);
1524 }
1525 else if (!strncmp(con->uri, "/jobs", 5))
1526 {
1527 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1528 ServerBin);
1529
1530 if (con->uri[5] && con->uri[6])
1531 cupsdSetString(&con->options, con->uri + 5);
1532 else
1533 cupsdSetString(&con->options, NULL);
1534 }
1535 else
1536 {
1537 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1538 ServerBin);
1539
1540 if (con->uri[5] && con->uri[6])
1541 cupsdSetString(&con->options, con->uri + 5);
1542 else
1543 cupsdSetString(&con->options, NULL);
1544 }
1545
1546 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1547 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1548 }
1549 else
1550 {
1551 /*
1552 * POST to a file...
1553 */
1554
1555 if ((filename = get_file(con, &filestats, buf,
1556 sizeof(buf))) == NULL)
1557 {
1558 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1559 {
1560 cupsdCloseClient(con);
1561 return;
1562 }
1563
1564 break;
1565 }
1566
1567 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1568
1569 if (!is_cgi(con, filename, &filestats, type))
1570 {
1571 /*
1572 * Only POST to CGI's...
1573 */
1574
1575 if (!cupsdSendError(con, HTTP_STATUS_UNAUTHORIZED, CUPSD_AUTH_NONE))
1576 {
1577 cupsdCloseClient(con);
1578 return;
1579 }
1580 }
1581 }
1582 break;
1583
1584 case HTTP_STATE_PUT_RECV :
1585 /*
1586 * Validate the resource name...
1587 */
1588
1589 if (strcmp(con->uri, "/admin/conf/cupsd.conf"))
1590 {
1591 /*
1592 * PUT can only be done to the cupsd.conf file...
1593 */
1594
1595 cupsdLogClient(con, CUPSD_LOG_ERROR,
1596 "Disallowed PUT request for \"%s\".", con->uri);
1597
1598 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1599 {
1600 cupsdCloseClient(con);
1601 return;
1602 }
1603
1604 break;
1605 }
1606
1607 /*
1608 * See if the PUT request includes a Content-Length field, and if
1609 * so check the length against any limits that are set...
1610 */
1611
1612 if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
1613 MaxRequestSize > 0 &&
1614 httpGetLength2(con->http) > MaxRequestSize)
1615 {
1616 /*
1617 * Request too large...
1618 */
1619
1620 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1621 {
1622 cupsdCloseClient(con);
1623 return;
1624 }
1625
1626 break;
1627 }
1628 else if (httpGetLength2(con->http) < 0)
1629 {
1630 /*
1631 * Negative content lengths are invalid!
1632 */
1633
1634 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
1635 {
1636 cupsdCloseClient(con);
1637 return;
1638 }
1639
1640 break;
1641 }
1642
1643 /*
1644 * Open a temporary file to hold the request...
1645 */
1646
1647 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1648 request_id ++);
1649 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1650
1651 if (con->file < 0)
1652 {
1653 cupsdLogClient(con, CUPSD_LOG_ERROR,
1654 "Unable to create request file \"%s\": %s",
1655 con->filename, strerror(errno));
1656
1657 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1658 {
1659 cupsdCloseClient(con);
1660 return;
1661 }
1662 }
1663
1664 fchmod(con->file, 0640);
1665 fchown(con->file, RunUser, Group);
1666 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1667 break;
1668
1669 case HTTP_STATE_DELETE :
1670 case HTTP_STATE_TRACE :
1671 cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);
1672 cupsdCloseClient(con);
1673 return;
1674
1675 case HTTP_STATE_HEAD :
1676 if (!strncmp(con->uri, "/printers/", 10) &&
1677 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1678 {
1679 /*
1680 * Send PPD file - get the real printer name since printer
1681 * names are not case sensitive but filenames can be...
1682 */
1683
1684 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1685
1686 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1687 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1688 else
1689 {
1690 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1691 {
1692 cupsdCloseClient(con);
1693 return;
1694 }
1695
1696 cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
1697 break;
1698 }
1699 }
1700 else if (!strncmp(con->uri, "/printers/", 10) &&
1701 !strcmp(con->uri + strlen(con->uri) - 4, ".png"))
1702 {
1703 /*
1704 * Send PNG file - get the real printer name since printer
1705 * names are not case sensitive but filenames can be...
1706 */
1707
1708 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1709
1710 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1711 snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
1712 else
1713 {
1714 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1715 {
1716 cupsdCloseClient(con);
1717 return;
1718 }
1719
1720 cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
1721 break;
1722 }
1723 }
1724 else if (!WebInterface)
1725 {
1726 if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
1727 {
1728 cupsdCloseClient(con);
1729 return;
1730 }
1731
1732 cupsdLogRequest(con, HTTP_STATUS_OK);
1733 break;
1734 }
1735
1736 if ((!strncmp(con->uri, "/admin", 6) &&
1737 strncmp(con->uri, "/admin/conf/", 12) &&
1738 strncmp(con->uri, "/admin/log/", 11)) ||
1739 !strncmp(con->uri, "/printers", 9) ||
1740 !strncmp(con->uri, "/classes", 8) ||
1741 !strncmp(con->uri, "/help", 5) ||
1742 !strncmp(con->uri, "/jobs", 5))
1743 {
1744 /*
1745 * CGI output...
1746 */
1747
1748 if (!cupsdSendHeader(con, HTTP_STATUS_OK, "text/html", CUPSD_AUTH_NONE))
1749 {
1750 cupsdCloseClient(con);
1751 return;
1752 }
1753
1754 cupsdLogRequest(con, HTTP_STATUS_OK);
1755 }
1756 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1757 (strchr(con->uri + 12, '/') ||
1758 strlen(con->uri) == 12)) ||
1759 (!strncmp(con->uri, "/admin/log/", 11) &&
1760 (strchr(con->uri + 11, '/') ||
1761 strlen(con->uri) == 11)))
1762 {
1763 /*
1764 * HEAD can only be done to configuration files under
1765 * /admin/conf...
1766 */
1767
1768 cupsdLogClient(con, CUPSD_LOG_ERROR,
1769 "Request for subdirectory \"%s\".", con->uri);
1770
1771 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1772 {
1773 cupsdCloseClient(con);
1774 return;
1775 }
1776
1777 cupsdLogRequest(con, HTTP_STATUS_FORBIDDEN);
1778 break;
1779 }
1780 else if ((filename = get_file(con, &filestats, buf,
1781 sizeof(buf))) == NULL)
1782 {
1783 if (!cupsdSendHeader(con, HTTP_STATUS_NOT_FOUND, "text/html",
1784 CUPSD_AUTH_NONE))
1785 {
1786 cupsdCloseClient(con);
1787 return;
1788 }
1789
1790 cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
1791 }
1792 else if (!check_if_modified(con, &filestats))
1793 {
1794 if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
1795 {
1796 cupsdCloseClient(con);
1797 return;
1798 }
1799
1800 cupsdLogRequest(con, HTTP_STATUS_NOT_MODIFIED);
1801 }
1802 else
1803 {
1804 /*
1805 * Serve a file...
1806 */
1807
1808 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1809 if (type == NULL)
1810 strlcpy(line, "text/plain", sizeof(line));
1811 else
1812 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1813
1814 httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
1815 httpGetDateString(filestats.st_mtime));
1816 httpSetLength(con->http, filestats.st_size);
1817
1818 if (!cupsdSendHeader(con, HTTP_STATUS_OK, line, CUPSD_AUTH_NONE))
1819 {
1820 cupsdCloseClient(con);
1821 return;
1822 }
1823
1824 cupsdLogRequest(con, HTTP_STATUS_OK);
1825 }
1826 break;
1827
1828 default :
1829 break; /* Anti-compiler-warning-code */
1830 }
1831 }
1832 }
1833
1834 /*
1835 * Handle any incoming data...
1836 */
1837
1838 switch (httpGetState(con->http))
1839 {
1840 case HTTP_STATE_PUT_RECV :
1841 do
1842 {
1843 if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
1844 {
1845 if (httpError(con->http) && httpError(con->http) != EPIPE)
1846 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1847 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1848 httpError(con->http), strerror(httpError(con->http)));
1849 else
1850 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1851 "HTTP_STATE_PUT_RECV Closing on EOF.");
1852
1853 cupsdCloseClient(con);
1854 return;
1855 }
1856 else if (bytes > 0)
1857 {
1858 con->bytes += bytes;
1859
1860 if (write(con->file, line, bytes) < bytes)
1861 {
1862 cupsdLogClient(con, CUPSD_LOG_ERROR,
1863 "Unable to write %d bytes to \"%s\": %s", bytes,
1864 con->filename, strerror(errno));
1865
1866 close(con->file);
1867 con->file = -1;
1868 unlink(con->filename);
1869 cupsdClearString(&con->filename);
1870
1871 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1872 {
1873 cupsdCloseClient(con);
1874 return;
1875 }
1876 }
1877 }
1878 }
1879 while (httpGetState(con->http) == HTTP_STATE_PUT_RECV && httpGetReady(con->http));
1880
1881 if (httpGetState(con->http) == HTTP_STATE_STATUS)
1882 {
1883 /*
1884 * End of file, see how big it is...
1885 */
1886
1887 fstat(con->file, &filestats);
1888
1889 close(con->file);
1890 con->file = -1;
1891
1892 if (filestats.st_size > MaxRequestSize &&
1893 MaxRequestSize > 0)
1894 {
1895 /*
1896 * Request is too big; remove it and send an error...
1897 */
1898
1899 unlink(con->filename);
1900 cupsdClearString(&con->filename);
1901
1902 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1903 {
1904 cupsdCloseClient(con);
1905 return;
1906 }
1907 }
1908
1909 /*
1910 * Install the configuration file...
1911 */
1912
1913 status = install_cupsd_conf(con);
1914
1915 /*
1916 * Return the status to the client...
1917 */
1918
1919 if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))
1920 {
1921 cupsdCloseClient(con);
1922 return;
1923 }
1924 }
1925 break;
1926
1927 case HTTP_STATE_POST_RECV :
1928 do
1929 {
1930 if (con->request && con->file < 0)
1931 {
1932 /*
1933 * Grab any request data from the connection...
1934 */
1935
1936 if ((ipp_state = ippRead(con->http, con->request)) == IPP_STATE_ERROR)
1937 {
1938 cupsdLogClient(con, CUPSD_LOG_ERROR, "IPP read error: %s",
1939 cupsLastErrorString());
1940
1941 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
1942 cupsdCloseClient(con);
1943 return;
1944 }
1945 else if (ipp_state != IPP_STATE_DATA)
1946 {
1947 if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
1948 {
1949 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
1950 cupsdCloseClient(con);
1951 return;
1952 }
1953
1954 if (httpGetReady(con->http))
1955 continue;
1956 break;
1957 }
1958 else
1959 {
1960 cupsdLogClient(con, CUPSD_LOG_DEBUG, "%d.%d %s %d",
1961 con->request->request.op.version[0],
1962 con->request->request.op.version[1],
1963 ippOpString(con->request->request.op.operation_id),
1964 con->request->request.op.request_id);
1965 con->bytes += ippLength(con->request);
1966 }
1967 }
1968
1969 if (con->file < 0 && httpGetState(con->http) != HTTP_STATE_POST_SEND)
1970 {
1971 /*
1972 * Create a file as needed for the request data...
1973 */
1974
1975 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1976 request_id ++);
1977 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1978
1979 if (con->file < 0)
1980 {
1981 cupsdLogClient(con, CUPSD_LOG_ERROR,
1982 "Unable to create request file \"%s\": %s",
1983 con->filename, strerror(errno));
1984
1985 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1986 {
1987 cupsdCloseClient(con);
1988 return;
1989 }
1990 }
1991
1992 fchmod(con->file, 0640);
1993 fchown(con->file, RunUser, Group);
1994 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1995 }
1996
1997 if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
1998 {
1999 if (!httpWait(con->http, 0))
2000 return;
2001 else if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
2002 {
2003 if (httpError(con->http) && httpError(con->http) != EPIPE)
2004 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2005 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
2006 httpError(con->http), strerror(httpError(con->http)));
2007 else
2008 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2009 "HTTP_STATE_POST_SEND Closing on EOF.");
2010
2011 cupsdCloseClient(con);
2012 return;
2013 }
2014 else if (bytes > 0)
2015 {
2016 con->bytes += bytes;
2017
2018 if (write(con->file, line, bytes) < bytes)
2019 {
2020 cupsdLogClient(con, CUPSD_LOG_ERROR,
2021 "Unable to write %d bytes to \"%s\": %s",
2022 bytes, con->filename, strerror(errno));
2023
2024 close(con->file);
2025 con->file = -1;
2026 unlink(con->filename);
2027 cupsdClearString(&con->filename);
2028
2029 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE,
2030 CUPSD_AUTH_NONE))
2031 {
2032 cupsdCloseClient(con);
2033 return;
2034 }
2035 }
2036 }
2037 else if (httpGetState(con->http) == HTTP_STATE_POST_RECV)
2038 return;
2039 else if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
2040 {
2041 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2042 "Closing on unexpected state %s.",
2043 httpStateString(httpGetState(con->http)));
2044 cupsdCloseClient(con);
2045 return;
2046 }
2047 }
2048 }
2049 while (httpGetState(con->http) == HTTP_STATE_POST_RECV && httpGetReady(con->http));
2050
2051 if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
2052 {
2053 if (con->file >= 0)
2054 {
2055 fstat(con->file, &filestats);
2056
2057 close(con->file);
2058 con->file = -1;
2059
2060 if (filestats.st_size > MaxRequestSize &&
2061 MaxRequestSize > 0)
2062 {
2063 /*
2064 * Request is too big; remove it and send an error...
2065 */
2066
2067 unlink(con->filename);
2068 cupsdClearString(&con->filename);
2069
2070 if (con->request)
2071 {
2072 /*
2073 * Delete any IPP request data...
2074 */
2075
2076 ippDelete(con->request);
2077 con->request = NULL;
2078 }
2079
2080 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
2081 {
2082 cupsdCloseClient(con);
2083 return;
2084 }
2085 }
2086 else if (filestats.st_size == 0)
2087 {
2088 /*
2089 * Don't allow empty file...
2090 */
2091
2092 unlink(con->filename);
2093 cupsdClearString(&con->filename);
2094 }
2095
2096 if (con->command)
2097 {
2098 if (!cupsdSendCommand(con, con->command, con->options, 0))
2099 {
2100 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
2101 {
2102 cupsdCloseClient(con);
2103 return;
2104 }
2105 }
2106 else
2107 cupsdLogRequest(con, HTTP_STATUS_OK);
2108 }
2109 }
2110
2111 if (con->request)
2112 {
2113 cupsdProcessIPPRequest(con);
2114
2115 if (con->filename)
2116 {
2117 unlink(con->filename);
2118 cupsdClearString(&con->filename);
2119 }
2120
2121 return;
2122 }
2123 }
2124 break;
2125
2126 default :
2127 break; /* Anti-compiler-warning-code */
2128 }
2129
2130 if (httpGetState(con->http) == HTTP_STATE_WAITING)
2131 {
2132 if (!httpGetKeepAlive(con->http))
2133 {
2134 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2135 "Closing because Keep-Alive is disabled.");
2136 cupsdCloseClient(con);
2137 }
2138 else
2139 {
2140 cupsArrayRemove(ActiveClients, con);
2141 cupsdSetBusyState();
2142 }
2143 }
2144 }
2145
2146
2147 /*
2148 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2149 */
2150
2151 int /* O - 1 on success, 0 on failure */
2152 cupsdSendCommand(
2153 cupsd_client_t *con, /* I - Client connection */
2154 char *command, /* I - Command to run */
2155 char *options, /* I - Command-line options */
2156 int root) /* I - Run as root? */
2157 {
2158 int fd; /* Standard input file descriptor */
2159
2160
2161 if (con->filename)
2162 {
2163 fd = open(con->filename, O_RDONLY);
2164
2165 if (fd < 0)
2166 {
2167 cupsdLogClient(con, CUPSD_LOG_ERROR,
2168 "Unable to open \"%s\" for reading: %s",
2169 con->filename ? con->filename : "/dev/null",
2170 strerror(errno));
2171 return (0);
2172 }
2173
2174 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
2175 }
2176 else
2177 fd = -1;
2178
2179 con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
2180 con->pipe_status = HTTP_STATUS_OK;
2181
2182 if (fd >= 0)
2183 close(fd);
2184
2185 cupsdLogClient(con, CUPSD_LOG_INFO, "Started \"%s\" (pid=%d, file=%d)",
2186 command, con->pipe_pid, con->file);
2187
2188 if (con->pipe_pid == 0)
2189 return (0);
2190
2191 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2192
2193 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2194
2195 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
2196
2197 con->sent_header = 0;
2198 con->file_ready = 0;
2199 con->got_fields = 0;
2200 con->header_used = 0;
2201
2202 return (1);
2203 }
2204
2205
2206 /*
2207 * 'cupsdSendError()' - Send an error message via HTTP.
2208 */
2209
2210 int /* O - 1 if successful, 0 otherwise */
2211 cupsdSendError(cupsd_client_t *con, /* I - Connection */
2212 http_status_t code, /* I - Error code */
2213 int auth_type)/* I - Authentication type */
2214 {
2215 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdSendError code=%d, auth_type=%d",
2216 code, auth_type);
2217
2218 #ifdef HAVE_SSL
2219 /*
2220 * Force client to upgrade for authentication if that is how the
2221 * server is configured...
2222 */
2223
2224 if (code == HTTP_STATUS_UNAUTHORIZED &&
2225 DefaultEncryption == HTTP_ENCRYPTION_REQUIRED &&
2226 _cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost") &&
2227 !httpIsEncrypted(con->http))
2228 {
2229 code = HTTP_STATUS_UPGRADE_REQUIRED;
2230 }
2231 #endif /* HAVE_SSL */
2232
2233 /*
2234 * Put the request in the access_log file...
2235 */
2236
2237 cupsdLogRequest(con, code);
2238
2239 /*
2240 * To work around bugs in some proxies, don't use Keep-Alive for some
2241 * error messages...
2242 *
2243 * Kerberos authentication doesn't work without Keep-Alive, so
2244 * never disable it in that case.
2245 */
2246
2247 if (code >= HTTP_STATUS_BAD_REQUEST && con->type != CUPSD_AUTH_NEGOTIATE)
2248 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
2249
2250 if (httpGetVersion(con->http) >= HTTP_VERSION_1_1 &&
2251 httpGetKeepAlive(con->http) == HTTP_KEEPALIVE_OFF)
2252 httpSetField(con->http, HTTP_FIELD_CONNECTION, "close");
2253
2254 if (code >= HTTP_STATUS_BAD_REQUEST)
2255 {
2256 /*
2257 * Send a human-readable error message.
2258 */
2259
2260 char message[4096], /* Message for user */
2261 urltext[1024], /* URL redirection text */
2262 redirect[1024]; /* Redirection link */
2263 const char *text; /* Status-specific text */
2264
2265
2266 redirect[0] = '\0';
2267
2268 if (code == HTTP_STATUS_UNAUTHORIZED)
2269 text = _cupsLangString(con->language,
2270 _("Enter your username and password or the "
2271 "root username and password to access this "
2272 "page. If you are using Kerberos authentication, "
2273 "make sure you have a valid Kerberos ticket."));
2274 else if (code == HTTP_STATUS_UPGRADE_REQUIRED)
2275 {
2276 text = urltext;
2277
2278 snprintf(urltext, sizeof(urltext),
2279 _cupsLangString(con->language,
2280 _("You must access this page using the URL "
2281 "<A HREF=\"https://%s:%d%s\">"
2282 "https://%s:%d%s</A>.")),
2283 con->servername, con->serverport, con->uri,
2284 con->servername, con->serverport, con->uri);
2285
2286 snprintf(redirect, sizeof(redirect),
2287 "<META HTTP-EQUIV=\"Refresh\" "
2288 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2289 con->servername, con->serverport, con->uri);
2290 }
2291 else if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
2292 text = _cupsLangString(con->language,
2293 _("The web interface is currently disabled. Run "
2294 "\"cupsctl WebInterface=yes\" to enable it."));
2295 else
2296 text = "";
2297
2298 snprintf(message, sizeof(message),
2299 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2300 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2301 "<HTML>\n"
2302 "<HEAD>\n"
2303 "\t<META HTTP-EQUIV=\"Content-Type\" "
2304 "CONTENT=\"text/html; charset=utf-8\">\n"
2305 "\t<TITLE>%s - " CUPS_SVERSION "</TITLE>\n"
2306 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2307 "HREF=\"/cups.css\">\n"
2308 "%s"
2309 "</HEAD>\n"
2310 "<BODY>\n"
2311 "<H1>%s</H1>\n"
2312 "<P>%s</P>\n"
2313 "</BODY>\n"
2314 "</HTML>\n",
2315 _httpStatus(con->language, code), redirect,
2316 _httpStatus(con->language, code), text);
2317
2318 /*
2319 * Send an error message back to the client. If the error code is a
2320 * 400 or 500 series, make sure the message contains some text, too!
2321 */
2322
2323 httpSetLength(con->http, strlen(message));
2324
2325 if (!cupsdSendHeader(con, code, "text/html", auth_type))
2326 return (0);
2327
2328 if (httpPrintf(con->http, "%s", message) < 0)
2329 return (0);
2330 }
2331 else
2332 {
2333 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
2334
2335 if (!cupsdSendHeader(con, code, NULL, auth_type))
2336 return (0);
2337 }
2338
2339 return (1);
2340 }
2341
2342
2343 /*
2344 * 'cupsdSendHeader()' - Send an HTTP request.
2345 */
2346
2347 int /* O - 1 on success, 0 on failure */
2348 cupsdSendHeader(
2349 cupsd_client_t *con, /* I - Client to send to */
2350 http_status_t code, /* I - HTTP status code */
2351 char *type, /* I - MIME type of document */
2352 int auth_type) /* I - Type of authentication */
2353 {
2354 char auth_str[1024]; /* Authorization string */
2355
2356
2357 /*
2358 * Send the HTTP status header...
2359 */
2360
2361 if (code == HTTP_STATUS_CONTINUE)
2362 {
2363 /*
2364 * 100-continue doesn't send any headers...
2365 */
2366
2367 return (!httpWriteResponse(con->http, HTTP_STATUS_CONTINUE));
2368 }
2369 else if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
2370 {
2371 /*
2372 * Treat our special "web interface is disabled" status as "200 OK" for web
2373 * browsers.
2374 */
2375
2376 code = HTTP_STATUS_OK;
2377 }
2378
2379 if (ServerHeader)
2380 httpSetField(con->http, HTTP_FIELD_SERVER, ServerHeader);
2381
2382 if (code == HTTP_STATUS_METHOD_NOT_ALLOWED)
2383 httpSetField(con->http, HTTP_FIELD_ALLOW, "GET, HEAD, OPTIONS, POST, PUT");
2384
2385 if (code == HTTP_STATUS_UNAUTHORIZED)
2386 {
2387 if (auth_type == CUPSD_AUTH_NONE)
2388 {
2389 if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
2390 auth_type = cupsdDefaultAuthType();
2391 else
2392 auth_type = con->best->type;
2393 }
2394
2395 auth_str[0] = '\0';
2396
2397 if (auth_type == CUPSD_AUTH_BASIC || auth_type == CUPSD_AUTH_BASICDIGEST)
2398 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2399 else if (auth_type == CUPSD_AUTH_DIGEST)
2400 snprintf(auth_str, sizeof(auth_str), "Digest realm=\"CUPS\", nonce=\"%s\"",
2401 httpGetHostname(con->http, NULL, 0));
2402 #ifdef HAVE_GSSAPI
2403 else if (auth_type == CUPSD_AUTH_NEGOTIATE)
2404 {
2405 # ifdef AF_LOCAL
2406 if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
2407 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2408 else
2409 # endif /* AF_LOCAL */
2410 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2411 }
2412 #endif /* HAVE_GSSAPI */
2413
2414 if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
2415 !_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost"))
2416 {
2417 /*
2418 * Add a "trc" (try root certification) parameter for local non-Kerberos
2419 * requests when the request requires system group membership - then the
2420 * client knows the root certificate can/should be used.
2421 *
2422 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2423 * parameter as needed...
2424 */
2425
2426 char *name, /* Current user name */
2427 *auth_key; /* Auth key buffer */
2428 size_t auth_size; /* Size of remaining buffer */
2429
2430 auth_key = auth_str + strlen(auth_str);
2431 auth_size = sizeof(auth_str) - (auth_key - auth_str);
2432
2433 for (name = (char *)cupsArrayFirst(con->best->names);
2434 name;
2435 name = (char *)cupsArrayNext(con->best->names))
2436 {
2437 #ifdef HAVE_AUTHORIZATION_H
2438 if (!_cups_strncasecmp(name, "@AUTHKEY(", 9))
2439 {
2440 snprintf(auth_key, auth_size, ", authkey=\"%s\"", name + 9);
2441 /* end parenthesis is stripped in conf.c */
2442 break;
2443 }
2444 else
2445 #endif /* HAVE_AUTHORIZATION_H */
2446 if (!_cups_strcasecmp(name, "@SYSTEM"))
2447 {
2448 #ifdef HAVE_AUTHORIZATION_H
2449 if (SystemGroupAuthKey)
2450 snprintf(auth_key, auth_size,
2451 ", authkey=\"%s\"",
2452 SystemGroupAuthKey);
2453 else
2454 #else
2455 strlcpy(auth_key, ", trc=\"y\"", auth_size);
2456 #endif /* HAVE_AUTHORIZATION_H */
2457 break;
2458 }
2459 }
2460 }
2461
2462 if (auth_str[0])
2463 {
2464 cupsdLogClient(con, CUPSD_LOG_DEBUG, "WWW-Authenticate: %s", auth_str);
2465
2466 httpSetField(con->http, HTTP_FIELD_WWW_AUTHENTICATE, auth_str);
2467 }
2468 }
2469
2470 if (con->language && strcmp(con->language->language, "C"))
2471 httpSetField(con->http, HTTP_FIELD_CONTENT_LANGUAGE, con->language->language);
2472
2473 if (type)
2474 {
2475 if (!strcmp(type, "text/html"))
2476 httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, "text/html; charset=utf-8");
2477 else
2478 httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, type);
2479 }
2480
2481 return (!httpWriteResponse(con->http, code));
2482 }
2483
2484
2485 /*
2486 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2487 */
2488
2489 void
2490 cupsdUpdateCGI(void)
2491 {
2492 char *ptr, /* Pointer to end of line in buffer */
2493 message[1024]; /* Pointer to message text */
2494 int loglevel; /* Log level for message */
2495
2496
2497 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2498 message, sizeof(message))) != NULL)
2499 {
2500 if (loglevel == CUPSD_LOG_INFO)
2501 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
2502
2503 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2504 break;
2505 }
2506
2507 if (ptr == NULL && !CGIStatusBuffer->bufused)
2508 {
2509 /*
2510 * Fatal error on pipe - should never happen!
2511 */
2512
2513 cupsdLogMessage(CUPSD_LOG_CRIT,
2514 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2515 strerror(errno));
2516 }
2517 }
2518
2519
2520 /*
2521 * 'cupsdWriteClient()' - Write data to a client as needed.
2522 */
2523
2524 void
2525 cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2526 {
2527 int bytes, /* Number of bytes written */
2528 field_col; /* Current column */
2529 char *bufptr, /* Pointer into buffer */
2530 *bufend; /* Pointer to end of buffer */
2531 ipp_state_t ipp_state; /* IPP state value */
2532
2533
2534 cupsdLogClient(con, CUPSD_LOG_DEBUG, "con->http=%p", con->http);
2535 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2536 "cupsdWriteClient "
2537 "error=%d, "
2538 "used=%d, "
2539 "state=%s, "
2540 "data_encoding=HTTP_ENCODING_%s, "
2541 "data_remaining=" CUPS_LLFMT ", "
2542 "response=%p(%s), "
2543 "pipe_pid=%d, "
2544 "file=%d",
2545 httpError(con->http), (int)httpGetReady(con->http),
2546 httpStateString(httpGetState(con->http)),
2547 httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
2548 CUPS_LLCAST httpGetLength2(con->http),
2549 con->response,
2550 con->response ? ipp_states[con->response->state] : "",
2551 con->pipe_pid, con->file);
2552
2553 if (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
2554 httpGetState(con->http) != HTTP_STATE_POST_SEND)
2555 {
2556 /*
2557 * If we get called in the wrong state, then something went wrong with the
2558 * connection and we need to shut it down...
2559 */
2560
2561 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP state %s.",
2562 httpStateString(httpGetState(con->http)));
2563 cupsdCloseClient(con);
2564 return;
2565 }
2566
2567 if (con->pipe_pid)
2568 {
2569 /*
2570 * Make sure we select on the CGI output...
2571 */
2572
2573 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2574
2575 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
2576
2577 if (!con->file_ready)
2578 {
2579 /*
2580 * Try again later when there is CGI output available...
2581 */
2582
2583 cupsdRemoveSelect(httpGetFd(con->http));
2584 return;
2585 }
2586
2587 con->file_ready = 0;
2588 }
2589
2590 if (con->response && con->response->state != IPP_STATE_DATA)
2591 {
2592 size_t wused = httpGetPending(con->http); /* Previous write buffer use */
2593
2594 do
2595 {
2596 /*
2597 * Write a single attribute or the IPP message header...
2598 */
2599
2600 ipp_state = ippWrite(con->http, con->response);
2601
2602 /*
2603 * If the write buffer has been flushed, stop buffering up attributes...
2604 */
2605
2606 if (httpGetPending(con->http) <= wused)
2607 break;
2608 }
2609 while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR);
2610
2611 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2612 "Writing IPP response, ipp_state=%s, old "
2613 "wused=" CUPS_LLFMT ", new wused=" CUPS_LLFMT,
2614 ippStateString(ipp_state),
2615 CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http));
2616
2617 if (httpGetPending(con->http) > 0)
2618 httpFlushWrite(con->http);
2619
2620 bytes = ipp_state != IPP_STATE_ERROR &&
2621 (con->file >= 0 || ipp_state != IPP_STATE_DATA);
2622
2623 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2624 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT,
2625 (int)bytes, httpGetState(con->http),
2626 CUPS_LLCAST httpGetLength2(con->http));
2627 }
2628 else if ((bytes = read(con->file, con->header + con->header_used,
2629 sizeof(con->header) - con->header_used)) > 0)
2630 {
2631 con->header_used += bytes;
2632
2633 if (con->pipe_pid && !con->got_fields)
2634 {
2635 /*
2636 * Inspect the data for Content-Type and other fields.
2637 */
2638
2639 for (bufptr = con->header, bufend = con->header + con->header_used,
2640 field_col = 0;
2641 !con->got_fields && bufptr < bufend;
2642 bufptr ++)
2643 {
2644 if (*bufptr == '\n')
2645 {
2646 /*
2647 * Send line to client...
2648 */
2649
2650 if (bufptr > con->header && bufptr[-1] == '\r')
2651 bufptr[-1] = '\0';
2652 *bufptr++ = '\0';
2653
2654 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Script header: %s", con->header);
2655
2656 if (!con->sent_header)
2657 {
2658 /*
2659 * Handle redirection and CGI status codes...
2660 */
2661
2662 http_field_t field; /* HTTP field */
2663 char *value = strchr(con->header, ':');
2664 /* Value of field */
2665
2666 if (value)
2667 {
2668 *value++ = '\0';
2669 while (isspace(*value & 255))
2670 value ++;
2671 }
2672
2673 field = httpFieldValue(con->header);
2674
2675 if (field != HTTP_FIELD_UNKNOWN && value)
2676 {
2677 httpSetField(con->http, field, value);
2678
2679 if (field == HTTP_FIELD_LOCATION)
2680 {
2681 con->pipe_status = HTTP_STATUS_SEE_OTHER;
2682 con->sent_header = 2;
2683 }
2684 else
2685 con->sent_header = 1;
2686 }
2687 else if (!_cups_strcasecmp(con->header, "Status") && value)
2688 {
2689 con->pipe_status = (http_status_t)atoi(value);
2690 con->sent_header = 2;
2691 }
2692 else if (!_cups_strcasecmp(con->header, "Set-Cookie") && value)
2693 {
2694 char *sep = strchr(value, ';');
2695 /* Separator between name=value and the rest */
2696
2697 if (sep)
2698 *sep = '\0';
2699
2700 httpSetCookie(con->http, value);
2701 con->sent_header = 1;
2702 }
2703 }
2704
2705 /*
2706 * Update buffer...
2707 */
2708
2709 con->header_used -= bufptr - con->header;
2710
2711 if (con->header_used > 0)
2712 memmove(con->header, bufptr, con->header_used);
2713
2714 bufptr = con->header - 1;
2715
2716 /*
2717 * See if the line was empty...
2718 */
2719
2720 if (field_col == 0)
2721 {
2722 con->got_fields = 1;
2723
2724 if (httpGetVersion(con->http) == HTTP_VERSION_1_1 &&
2725 !httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0])
2726 httpSetLength(con->http, 0);
2727
2728 if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE))
2729 {
2730 cupsdCloseClient(con);
2731 return;
2732 }
2733 }
2734 else
2735 field_col = 0;
2736 }
2737 else if (*bufptr != '\r')
2738 field_col ++;
2739 }
2740
2741 if (!con->got_fields)
2742 return;
2743 }
2744
2745 if (con->header_used > 0)
2746 {
2747 if (httpWrite2(con->http, con->header, con->header_used) < 0)
2748 {
2749 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
2750 httpError(con->http), strerror(httpError(con->http)));
2751 cupsdCloseClient(con);
2752 return;
2753 }
2754
2755 if (httpIsChunked(con->http))
2756 httpFlushWrite(con->http);
2757
2758 con->bytes += con->header_used;
2759
2760 if (httpGetState(con->http) == HTTP_STATE_WAITING)
2761 bytes = 0;
2762 else
2763 bytes = con->header_used;
2764
2765 con->header_used = 0;
2766 }
2767 }
2768
2769 if (bytes <= 0 ||
2770 (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
2771 httpGetState(con->http) != HTTP_STATE_POST_SEND))
2772 {
2773 if (!con->sent_header && con->pipe_pid)
2774 cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE);
2775 else
2776 {
2777 cupsdLogRequest(con, HTTP_STATUS_OK);
2778
2779 httpFlushWrite(con->http);
2780
2781 if (httpIsChunked(con->http) && con->sent_header == 1)
2782 {
2783 if (httpWrite2(con->http, "", 0) < 0)
2784 {
2785 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
2786 httpError(con->http), strerror(httpError(con->http)));
2787 cupsdCloseClient(con);
2788 return;
2789 }
2790 }
2791 }
2792
2793 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con);
2794
2795 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
2796
2797 if (con->file >= 0)
2798 {
2799 cupsdRemoveSelect(con->file);
2800
2801 if (con->pipe_pid)
2802 cupsdEndProcess(con->pipe_pid, 0);
2803
2804 close(con->file);
2805 con->file = -1;
2806 con->pipe_pid = 0;
2807 }
2808
2809 if (con->filename)
2810 {
2811 unlink(con->filename);
2812 cupsdClearString(&con->filename);
2813 }
2814
2815 if (con->request)
2816 {
2817 ippDelete(con->request);
2818 con->request = NULL;
2819 }
2820
2821 if (con->response)
2822 {
2823 ippDelete(con->response);
2824 con->response = NULL;
2825 }
2826
2827 cupsdClearString(&con->command);
2828 cupsdClearString(&con->options);
2829 cupsdClearString(&con->query_string);
2830
2831 if (!httpGetKeepAlive(con->http))
2832 {
2833 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2834 "Closing because Keep-Alive is disabled.");
2835 cupsdCloseClient(con);
2836 return;
2837 }
2838 else
2839 {
2840 cupsArrayRemove(ActiveClients, con);
2841 cupsdSetBusyState();
2842 }
2843 }
2844 }
2845
2846
2847 /*
2848 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2849 */
2850
2851 static int /* O - 1 if modified since */
2852 check_if_modified(
2853 cupsd_client_t *con, /* I - Client connection */
2854 struct stat *filestats) /* I - File information */
2855 {
2856 const char *ptr; /* Pointer into field */
2857 time_t date; /* Time/date value */
2858 off_t size; /* Size/length value */
2859
2860
2861 size = 0;
2862 date = 0;
2863 ptr = httpGetField(con->http, HTTP_FIELD_IF_MODIFIED_SINCE);
2864
2865 if (*ptr == '\0')
2866 return (1);
2867
2868 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
2869 "check_if_modified "
2870 "filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"",
2871 filestats, CUPS_LLCAST filestats->st_size,
2872 (int)filestats->st_mtime, ptr);
2873
2874 while (*ptr != '\0')
2875 {
2876 while (isspace(*ptr) || *ptr == ';')
2877 ptr ++;
2878
2879 if (_cups_strncasecmp(ptr, "length=", 7) == 0)
2880 {
2881 ptr += 7;
2882 size = strtoll(ptr, NULL, 10);
2883
2884 while (isdigit(*ptr))
2885 ptr ++;
2886 }
2887 else if (isalpha(*ptr))
2888 {
2889 date = httpGetDateTime(ptr);
2890 while (*ptr != '\0' && *ptr != ';')
2891 ptr ++;
2892 }
2893 else
2894 ptr ++;
2895 }
2896
2897 return ((size != filestats->st_size && size != 0) ||
2898 (date < filestats->st_mtime && date != 0) ||
2899 (size == 0 && date == 0));
2900 }
2901
2902
2903 /*
2904 * 'compare_clients()' - Compare two client connections.
2905 */
2906
2907 static int /* O - Result of comparison */
2908 compare_clients(cupsd_client_t *a, /* I - First client */
2909 cupsd_client_t *b, /* I - Second client */
2910 void *data) /* I - User data (not used) */
2911 {
2912 (void)data;
2913
2914 if (a == b)
2915 return (0);
2916 else if (a < b)
2917 return (-1);
2918 else
2919 return (1);
2920 }
2921
2922
2923 /*
2924 * 'get_file()' - Get a filename and state info.
2925 */
2926
2927 static char * /* O - Real filename */
2928 get_file(cupsd_client_t *con, /* I - Client connection */
2929 struct stat *filestats, /* O - File information */
2930 char *filename, /* IO - Filename buffer */
2931 int len) /* I - Buffer length */
2932 {
2933 int status; /* Status of filesystem calls */
2934 char *ptr; /* Pointer info filename */
2935 int plen; /* Remaining length after pointer */
2936 char language[7]; /* Language subdirectory, if any */
2937
2938
2939 /*
2940 * Figure out the real filename...
2941 */
2942
2943 language[0] = '\0';
2944
2945 if (!strncmp(con->uri, "/ppd/", 5) && !strchr(con->uri + 5, '/'))
2946 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
2947 else if (!strncmp(con->uri, "/icons/", 7) && !strchr(con->uri + 7, '/'))
2948 {
2949 snprintf(filename, len, "%s/%s", CacheDir, con->uri + 7);
2950 if (access(filename, F_OK) < 0)
2951 snprintf(filename, len, "%s/images/generic.png", DocumentRoot);
2952 }
2953 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
2954 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
2955 else if (!strncmp(con->uri, "/admin/conf/", 12))
2956 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
2957 else if (!strncmp(con->uri, "/admin/log/", 11))
2958 {
2959 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
2960 strlcpy(filename, AccessLog, len);
2961 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
2962 strlcpy(filename, ErrorLog, len);
2963 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
2964 strlcpy(filename, PageLog, len);
2965 else
2966 return (NULL);
2967 }
2968 else if (con->language)
2969 {
2970 snprintf(language, sizeof(language), "/%s", con->language->language);
2971 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
2972 }
2973 else
2974 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
2975
2976 if ((ptr = strchr(filename, '?')) != NULL)
2977 *ptr = '\0';
2978
2979 /*
2980 * Grab the status for this language; if there isn't a language-specific file
2981 * then fallback to the default one...
2982 */
2983
2984 if ((status = stat(filename, filestats)) != 0 && language[0] &&
2985 strncmp(con->uri, "/icons/", 7) &&
2986 strncmp(con->uri, "/ppd/", 5) &&
2987 strncmp(con->uri, "/rss/", 5) &&
2988 strncmp(con->uri, "/admin/conf/", 12) &&
2989 strncmp(con->uri, "/admin/log/", 11))
2990 {
2991 /*
2992 * Drop the country code...
2993 */
2994
2995 language[3] = '\0';
2996 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
2997
2998 if ((ptr = strchr(filename, '?')) != NULL)
2999 *ptr = '\0';
3000
3001 if ((status = stat(filename, filestats)) != 0)
3002 {
3003 /*
3004 * Drop the language prefix and try the root directory...
3005 */
3006
3007 language[0] = '\0';
3008 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3009
3010 if ((ptr = strchr(filename, '?')) != NULL)
3011 *ptr = '\0';
3012
3013 status = stat(filename, filestats);
3014 }
3015 }
3016
3017 /*
3018 * If we're found a directory, get the index.html file instead...
3019 */
3020
3021 if (!status && S_ISDIR(filestats->st_mode))
3022 {
3023 /*
3024 * Make sure the URI ends with a slash...
3025 */
3026
3027 if (con->uri[strlen(con->uri) - 1] != '/')
3028 strlcat(con->uri, "/", sizeof(con->uri));
3029
3030 /*
3031 * Find the directory index file, trying every language...
3032 */
3033
3034 do
3035 {
3036 if (status && language[0])
3037 {
3038 /*
3039 * Try a different language subset...
3040 */
3041
3042 if (language[3])
3043 language[0] = '\0'; /* Strip country code */
3044 else
3045 language[0] = '\0'; /* Strip language */
3046 }
3047
3048 /*
3049 * Look for the index file...
3050 */
3051
3052 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3053
3054 if ((ptr = strchr(filename, '?')) != NULL)
3055 *ptr = '\0';
3056
3057 ptr = filename + strlen(filename);
3058 plen = len - (ptr - filename);
3059
3060 strlcpy(ptr, "index.html", plen);
3061 status = stat(filename, filestats);
3062
3063 #ifdef HAVE_JAVA
3064 if (status)
3065 {
3066 strlcpy(ptr, "index.class", plen);
3067 status = stat(filename, filestats);
3068 }
3069 #endif /* HAVE_JAVA */
3070
3071 #ifdef HAVE_PERL
3072 if (status)
3073 {
3074 strlcpy(ptr, "index.pl", plen);
3075 status = stat(filename, filestats);
3076 }
3077 #endif /* HAVE_PERL */
3078
3079 #ifdef HAVE_PHP
3080 if (status)
3081 {
3082 strlcpy(ptr, "index.php", plen);
3083 status = stat(filename, filestats);
3084 }
3085 #endif /* HAVE_PHP */
3086
3087 #ifdef HAVE_PYTHON
3088 if (status)
3089 {
3090 strlcpy(ptr, "index.pyc", plen);
3091 status = stat(filename, filestats);
3092 }
3093
3094 if (status)
3095 {
3096 strlcpy(ptr, "index.py", plen);
3097 status = stat(filename, filestats);
3098 }
3099 #endif /* HAVE_PYTHON */
3100
3101 }
3102 while (status && language[0]);
3103 }
3104
3105 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3106 "get_file filestats=%p, filename=%p, len=%d, "
3107 "returning \"%s\".", filestats, filename, len,
3108 status ? "(null)" : filename);
3109
3110 if (status)
3111 return (NULL);
3112 else
3113 return (filename);
3114 }
3115
3116
3117 /*
3118 * 'install_cupsd_conf()' - Install a configuration file.
3119 */
3120
3121 static http_status_t /* O - Status */
3122 install_cupsd_conf(cupsd_client_t *con) /* I - Connection */
3123 {
3124 char filename[1024]; /* Configuration filename */
3125 cups_file_t *in, /* Input file */
3126 *out; /* Output file */
3127 char buffer[16384]; /* Copy buffer */
3128 ssize_t bytes; /* Number of bytes */
3129
3130
3131 /*
3132 * Open the request file...
3133 */
3134
3135 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3136 {
3137 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to open request file \"%s\": %s",
3138 con->filename, strerror(errno));
3139 return (HTTP_STATUS_SERVER_ERROR);
3140 }
3141
3142 /*
3143 * Open the new config file...
3144 */
3145
3146 if ((out = cupsdCreateConfFile(ConfigurationFile, ConfigFilePerm)) == NULL)
3147 {
3148 cupsFileClose(in);
3149 return (HTTP_STATUS_SERVER_ERROR);
3150 }
3151
3152 cupsdLogClient(con, CUPSD_LOG_INFO, "Installing config file \"%s\"...",
3153 ConfigurationFile);
3154
3155 /*
3156 * Copy from the request to the new config file...
3157 */
3158
3159 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3160 if (cupsFileWrite(out, buffer, bytes) < bytes)
3161 {
3162 cupsdLogClient(con, CUPSD_LOG_ERROR,
3163 "Unable to copy to config file \"%s\": %s",
3164 ConfigurationFile, strerror(errno));
3165
3166 cupsFileClose(in);
3167 cupsFileClose(out);
3168
3169 snprintf(filename, sizeof(filename), "%s.N", ConfigurationFile);
3170 cupsdUnlinkOrRemoveFile(filename);
3171
3172 return (HTTP_STATUS_SERVER_ERROR);
3173 }
3174
3175 /*
3176 * Close the files...
3177 */
3178
3179 cupsFileClose(in);
3180
3181 if (cupsdCloseCreatedConfFile(out, ConfigurationFile))
3182 return (HTTP_STATUS_SERVER_ERROR);
3183
3184 /*
3185 * Remove the request file...
3186 */
3187
3188 cupsdUnlinkOrRemoveFile(con->filename);
3189 cupsdClearString(&con->filename);
3190
3191 /*
3192 * Set the NeedReload flag...
3193 */
3194
3195 NeedReload = RELOAD_CUPSD;
3196 ReloadTime = time(NULL);
3197
3198 /*
3199 * Return that the file was created successfully...
3200 */
3201
3202 return (HTTP_STATUS_CREATED);
3203 }
3204
3205
3206 /*
3207 * 'is_cgi()' - Is the resource a CGI script/program?
3208 */
3209
3210 static int /* O - 1 = CGI, 0 = file */
3211 is_cgi(cupsd_client_t *con, /* I - Client connection */
3212 const char *filename, /* I - Real filename */
3213 struct stat *filestats, /* I - File information */
3214 mime_type_t *type) /* I - MIME type */
3215 {
3216 const char *options; /* Options on URL */
3217
3218
3219 /*
3220 * Get the options, if any...
3221 */
3222
3223 if ((options = strchr(con->uri, '?')) != NULL)
3224 {
3225 options ++;
3226 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3227 }
3228
3229 /*
3230 * Check for known types...
3231 */
3232
3233 if (!type || _cups_strcasecmp(type->super, "application"))
3234 {
3235 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3236 "is_cgi filename=\"%s\", filestats=%p, "
3237 "type=%s/%s, returning 0", filename,
3238 filestats, type ? type->super : "unknown",
3239 type ? type->type : "unknown");
3240 return (0);
3241 }
3242
3243 if (!_cups_strcasecmp(type->type, "x-httpd-cgi") &&
3244 (filestats->st_mode & 0111))
3245 {
3246 /*
3247 * "application/x-httpd-cgi" is a CGI script.
3248 */
3249
3250 cupsdSetString(&con->command, filename);
3251
3252 if (options)
3253 cupsdSetStringf(&con->options, " %s", options);
3254
3255 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3256 "is_cgi filename=\"%s\", filestats=%p, "
3257 "type=%s/%s, returning 1", filename,
3258 filestats, type->super, type->type);
3259 return (1);
3260 }
3261 #ifdef HAVE_JAVA
3262 else if (!_cups_strcasecmp(type->type, "x-httpd-java"))
3263 {
3264 /*
3265 * "application/x-httpd-java" is a Java servlet.
3266 */
3267
3268 cupsdSetString(&con->command, CUPS_JAVA);
3269
3270 if (options)
3271 cupsdSetStringf(&con->options, " %s %s", filename, options);
3272 else
3273 cupsdSetStringf(&con->options, " %s", filename);
3274
3275 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3276 "is_cgi filename=\"%s\", filestats=%p, "
3277 "type=%s/%s, returning 1", filename,
3278 filestats, type->super, type->type);
3279 return (1);
3280 }
3281 #endif /* HAVE_JAVA */
3282 #ifdef HAVE_PERL
3283 else if (!_cups_strcasecmp(type->type, "x-httpd-perl"))
3284 {
3285 /*
3286 * "application/x-httpd-perl" is a Perl page.
3287 */
3288
3289 cupsdSetString(&con->command, CUPS_PERL);
3290
3291 if (options)
3292 cupsdSetStringf(&con->options, " %s %s", filename, options);
3293 else
3294 cupsdSetStringf(&con->options, " %s", filename);
3295
3296 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3297 "is_cgi filename=\"%s\", filestats=%p, "
3298 "type=%s/%s, returning 1", filename,
3299 filestats, type->super, type->type);
3300 return (1);
3301 }
3302 #endif /* HAVE_PERL */
3303 #ifdef HAVE_PHP
3304 else if (!_cups_strcasecmp(type->type, "x-httpd-php"))
3305 {
3306 /*
3307 * "application/x-httpd-php" is a PHP page.
3308 */
3309
3310 cupsdSetString(&con->command, CUPS_PHP);
3311
3312 if (options)
3313 cupsdSetStringf(&con->options, " %s %s", filename, options);
3314 else
3315 cupsdSetStringf(&con->options, " %s", filename);
3316
3317 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3318 "is_cgi filename=\"%s\", filestats=%p, "
3319 "type=%s/%s, returning 1", filename,
3320 filestats, type->super, type->type);
3321 return (1);
3322 }
3323 #endif /* HAVE_PHP */
3324 #ifdef HAVE_PYTHON
3325 else if (!_cups_strcasecmp(type->type, "x-httpd-python"))
3326 {
3327 /*
3328 * "application/x-httpd-python" is a Python page.
3329 */
3330
3331 cupsdSetString(&con->command, CUPS_PYTHON);
3332
3333 if (options)
3334 cupsdSetStringf(&con->options, " %s %s", filename, options);
3335 else
3336 cupsdSetStringf(&con->options, " %s", filename);
3337
3338 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3339 "is_cgi filename=\"%s\", filestats=%p, "
3340 "type=%s/%s, returning 1", filename,
3341 filestats, type->super, type->type);
3342 return (1);
3343 }
3344 #endif /* HAVE_PYTHON */
3345
3346 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3347 "is_cgi filename=\"%s\", filestats=%p, "
3348 "type=%s/%s, returning 0", filename,
3349 filestats, type->super, type->type);
3350 return (0);
3351 }
3352
3353
3354 /*
3355 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3356 */
3357
3358 static int /* O - 0 if relative, 1 if absolute */
3359 is_path_absolute(const char *path) /* I - Input path */
3360 {
3361 /*
3362 * Check for a leading slash...
3363 */
3364
3365 if (path[0] != '/')
3366 return (0);
3367
3368 /*
3369 * Check for "/.." in the path...
3370 */
3371
3372 while ((path = strstr(path, "/..")) != NULL)
3373 {
3374 if (!path[3] || path[3] == '/')
3375 return (0);
3376
3377 path ++;
3378 }
3379
3380 /*
3381 * If we haven't found any relative paths, return 1 indicating an
3382 * absolute path...
3383 */
3384
3385 return (1);
3386 }
3387
3388
3389 /*
3390 * 'pipe_command()' - Pipe the output of a command to the remote client.
3391 */
3392
3393 static int /* O - Process ID */
3394 pipe_command(cupsd_client_t *con, /* I - Client connection */
3395 int infile, /* I - Standard input for command */
3396 int *outfile, /* O - Standard output for command */
3397 char *command, /* I - Command to run */
3398 char *options, /* I - Options for command */
3399 int root) /* I - Run as root? */
3400 {
3401 int i; /* Looping var */
3402 int pid; /* Process ID */
3403 char *commptr, /* Command string pointer */
3404 commch; /* Command string character */
3405 char *uriptr; /* URI string pointer */
3406 int fds[2]; /* Pipe FDs */
3407 int argc; /* Number of arguments */
3408 int envc; /* Number of environment variables */
3409 char argbuf[10240], /* Argument buffer */
3410 *argv[100], /* Argument strings */
3411 *envp[MAX_ENV + 20]; /* Environment variables */
3412 char auth_type[256], /* AUTH_TYPE environment variable */
3413 content_length[1024], /* CONTENT_LENGTH environment variable */
3414 content_type[1024], /* CONTENT_TYPE environment variable */
3415 http_cookie[32768], /* HTTP_COOKIE environment variable */
3416 http_referer[1024], /* HTTP_REFERER environment variable */
3417 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
3418 lang[1024], /* LANG environment variable */
3419 path_info[1024], /* PATH_INFO environment variable */
3420 remote_addr[1024], /* REMOTE_ADDR environment variable */
3421 remote_host[1024], /* REMOTE_HOST environment variable */
3422 remote_user[1024], /* REMOTE_USER environment variable */
3423 script_filename[1024], /* SCRIPT_FILENAME environment variable */
3424 script_name[1024], /* SCRIPT_NAME environment variable */
3425 server_name[1024], /* SERVER_NAME environment variable */
3426 server_port[1024]; /* SERVER_PORT environment variable */
3427 ipp_attribute_t *attr; /* attributes-natural-language attribute */
3428
3429
3430 /*
3431 * Parse a copy of the options string, which is of the form:
3432 *
3433 * argument+argument+argument
3434 * ?argument+argument+argument
3435 * param=value&param=value
3436 * ?param=value&param=value
3437 * /name?argument+argument+argument
3438 * /name?param=value&param=value
3439 *
3440 * If the string contains an "=" character after the initial name,
3441 * then we treat it as a HTTP GET form request and make a copy of
3442 * the remaining string for the environment variable.
3443 *
3444 * The string is always parsed out as command-line arguments, to
3445 * be consistent with Apache...
3446 */
3447
3448 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3449 "pipe_command infile=%d, outfile=%p, "
3450 "command=\"%s\", options=\"%s\", root=%d",
3451 infile, outfile, command,
3452 options ? options : "(null)", root);
3453
3454 argv[0] = command;
3455
3456 if (options)
3457 {
3458 commptr = options;
3459 if (*commptr == ' ')
3460 commptr ++;
3461 strlcpy(argbuf, commptr, sizeof(argbuf));
3462 }
3463 else
3464 argbuf[0] = '\0';
3465
3466 if (argbuf[0] == '/')
3467 {
3468 /*
3469 * Found some trailing path information, set PATH_INFO...
3470 */
3471
3472 if ((commptr = strchr(argbuf, '?')) == NULL)
3473 commptr = argbuf + strlen(argbuf);
3474
3475 commch = *commptr;
3476 *commptr = '\0';
3477 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
3478 *commptr = commch;
3479 }
3480 else
3481 {
3482 commptr = argbuf;
3483 path_info[0] = '\0';
3484
3485 if (*commptr == ' ')
3486 commptr ++;
3487 }
3488
3489 if (*commptr == '?' && con->operation == HTTP_STATE_GET && !con->query_string)
3490 {
3491 commptr ++;
3492 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
3493 }
3494
3495 argc = 1;
3496
3497 if (*commptr)
3498 {
3499 argv[argc ++] = commptr;
3500
3501 for (; *commptr && argc < 99; commptr ++)
3502 {
3503 /*
3504 * Break arguments whenever we see a + or space...
3505 */
3506
3507 if (*commptr == ' ' || *commptr == '+')
3508 {
3509 while (*commptr == ' ' || *commptr == '+')
3510 *commptr++ = '\0';
3511
3512 /*
3513 * If we don't have a blank string, save it as another argument...
3514 */
3515
3516 if (*commptr)
3517 {
3518 argv[argc] = commptr;
3519 argc ++;
3520 }
3521 else
3522 break;
3523 }
3524 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
3525 isxdigit(commptr[2] & 255))
3526 {
3527 /*
3528 * Convert the %xx notation to the individual character.
3529 */
3530
3531 if (commptr[1] >= '0' && commptr[1] <= '9')
3532 *commptr = (commptr[1] - '0') << 4;
3533 else
3534 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
3535
3536 if (commptr[2] >= '0' && commptr[2] <= '9')
3537 *commptr |= commptr[2] - '0';
3538 else
3539 *commptr |= tolower(commptr[2]) - 'a' + 10;
3540
3541 _cups_strcpy(commptr + 1, commptr + 3);
3542
3543 /*
3544 * Check for a %00 and break if that is the case...
3545 */
3546
3547 if (!*commptr)
3548 break;
3549 }
3550 }
3551 }
3552
3553 argv[argc] = NULL;
3554
3555 /*
3556 * Setup the environment variables as needed...
3557 */
3558
3559 if (con->username[0])
3560 {
3561 snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
3562 httpGetField(con->http, HTTP_FIELD_AUTHORIZATION));
3563
3564 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
3565 *uriptr = '\0';
3566 }
3567 else
3568 auth_type[0] = '\0';
3569
3570 if (con->request &&
3571 (attr = ippFindAttribute(con->request, "attributes-natural-language",
3572 IPP_TAG_LANGUAGE)) != NULL)
3573 {
3574 switch (strlen(attr->values[0].string.text))
3575 {
3576 default :
3577 /*
3578 * This is an unknown or badly formatted language code; use
3579 * the POSIX locale...
3580 */
3581
3582 strlcpy(lang, "LANG=C", sizeof(lang));
3583 break;
3584
3585 case 2 :
3586 /*
3587 * Just the language code (ll)...
3588 */
3589
3590 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
3591 attr->values[0].string.text);
3592 break;
3593
3594 case 5 :
3595 /*
3596 * Language and country code (ll-cc)...
3597 */
3598
3599 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
3600 attr->values[0].string.text[0],
3601 attr->values[0].string.text[1],
3602 toupper(attr->values[0].string.text[3] & 255),
3603 toupper(attr->values[0].string.text[4] & 255));
3604 break;
3605 }
3606 }
3607 else if (con->language)
3608 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
3609 else
3610 strlcpy(lang, "LANG=C", sizeof(lang));
3611
3612 strlcpy(remote_addr, "REMOTE_ADDR=", sizeof(remote_addr));
3613 httpAddrString(httpGetAddress(con->http), remote_addr + 12,
3614 sizeof(remote_addr) - 12);
3615
3616 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
3617 httpGetHostname(con->http, NULL, 0));
3618
3619 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
3620 if ((uriptr = strchr(script_name, '?')) != NULL)
3621 *uriptr = '\0';
3622
3623 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
3624 DocumentRoot, script_name + 12);
3625
3626 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
3627
3628 if (httpGetField(con->http, HTTP_FIELD_HOST)[0])
3629 {
3630 char *nameptr; /* Pointer to ":port" */
3631
3632 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3633 httpGetField(con->http, HTTP_FIELD_HOST));
3634 if ((nameptr = strrchr(server_name, ':')) != NULL && !strchr(nameptr, ']'))
3635 *nameptr = '\0'; /* Strip trailing ":port" */
3636 }
3637 else
3638 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3639 con->servername);
3640
3641 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
3642
3643 if (auth_type[0])
3644 envp[envc ++] = auth_type;
3645
3646 envp[envc ++] = lang;
3647 envp[envc ++] = "REDIRECT_STATUS=1";
3648 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
3649 envp[envc ++] = server_name;
3650 envp[envc ++] = server_port;
3651 envp[envc ++] = remote_addr;
3652 envp[envc ++] = remote_host;
3653 envp[envc ++] = script_name;
3654 envp[envc ++] = script_filename;
3655
3656 if (path_info[0])
3657 envp[envc ++] = path_info;
3658
3659 if (con->username[0])
3660 {
3661 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
3662
3663 envp[envc ++] = remote_user;
3664 }
3665
3666 if (httpGetVersion(con->http) == HTTP_VERSION_1_1)
3667 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
3668 else if (httpGetVersion(con->http) == HTTP_VERSION_1_0)
3669 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
3670 else
3671 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
3672
3673 if (httpGetCookie(con->http))
3674 {
3675 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
3676 httpGetCookie(con->http));
3677 envp[envc ++] = http_cookie;
3678 }
3679
3680 if (httpGetField(con->http, HTTP_FIELD_USER_AGENT)[0])
3681 {
3682 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
3683 httpGetField(con->http, HTTP_FIELD_USER_AGENT));
3684 envp[envc ++] = http_user_agent;
3685 }
3686
3687 if (httpGetField(con->http, HTTP_FIELD_REFERER)[0])
3688 {
3689 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
3690 httpGetField(con->http, HTTP_FIELD_REFERER));
3691 envp[envc ++] = http_referer;
3692 }
3693
3694 if (con->operation == HTTP_STATE_GET)
3695 {
3696 envp[envc ++] = "REQUEST_METHOD=GET";
3697
3698 if (con->query_string)
3699 {
3700 /*
3701 * Add GET form variables after ?...
3702 */
3703
3704 envp[envc ++] = con->query_string;
3705 }
3706 else
3707 envp[envc ++] = "QUERY_STRING=";
3708 }
3709 else
3710 {
3711 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
3712 CUPS_LLCAST con->bytes);
3713 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
3714 httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE));
3715
3716 envp[envc ++] = "REQUEST_METHOD=POST";
3717 envp[envc ++] = content_length;
3718 envp[envc ++] = content_type;
3719 }
3720
3721 /*
3722 * Tell the CGI if we are using encryption...
3723 */
3724
3725 if (httpIsEncrypted(con->http))
3726 envp[envc ++] = "HTTPS=ON";
3727
3728 /*
3729 * Terminate the environment array...
3730 */
3731
3732 envp[envc] = NULL;
3733
3734 if (LogLevel >= CUPSD_LOG_DEBUG)
3735 {
3736 for (i = 0; i < argc; i ++)
3737 cupsdLogMessage(CUPSD_LOG_DEBUG,
3738 "[CGI] argv[%d] = \"%s\"", i, argv[i]);
3739 for (i = 0; i < envc; i ++)
3740 cupsdLogMessage(CUPSD_LOG_DEBUG,
3741 "[CGI] envp[%d] = \"%s\"", i, envp[i]);
3742 }
3743
3744 /*
3745 * Create a pipe for the output...
3746 */
3747
3748 if (cupsdOpenPipe(fds))
3749 {
3750 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
3751 argv[0], strerror(errno));
3752 return (0);
3753 }
3754
3755 /*
3756 * Then execute the command...
3757 */
3758
3759 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
3760 -1, -1, root, DefaultProfile, NULL, &pid) < 0)
3761 {
3762 /*
3763 * Error - can't fork!
3764 */
3765
3766 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
3767 strerror(errno));
3768
3769 cupsdClosePipe(fds);
3770 pid = 0;
3771 }
3772 else
3773 {
3774 /*
3775 * Fork successful - return the PID...
3776 */
3777
3778 if (con->username[0])
3779 cupsdAddCert(pid, con->username, con->type);
3780
3781 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
3782
3783 *outfile = fds[0];
3784 close(fds[1]);
3785 }
3786
3787 return (pid);
3788 }
3789
3790
3791 /*
3792 * 'valid_host()' - Is the Host: field valid?
3793 */
3794
3795 static int /* O - 1 if valid, 0 if not */
3796 valid_host(cupsd_client_t *con) /* I - Client connection */
3797 {
3798 cupsd_alias_t *a; /* Current alias */
3799 cupsd_netif_t *netif; /* Current network interface */
3800 const char *end; /* End character */
3801 char *ptr; /* Pointer into host value */
3802
3803
3804 /*
3805 * Copy the Host: header for later use...
3806 */
3807
3808 strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
3809 sizeof(con->clientname));
3810 if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
3811 {
3812 *ptr++ = '\0';
3813 con->clientport = atoi(ptr);
3814 }
3815 else
3816 con->clientport = con->serverport;
3817
3818 /*
3819 * Then validate...
3820 */
3821
3822 if (httpAddrLocalhost(httpGetAddress(con->http)))
3823 {
3824 /*
3825 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3826 * addresses when accessing CUPS via the loopback interface...
3827 */
3828
3829 return (!_cups_strcasecmp(con->clientname, "localhost") ||
3830 !_cups_strcasecmp(con->clientname, "localhost.") ||
3831 #ifdef __linux
3832 !_cups_strcasecmp(con->clientname, "localhost.localdomain") ||
3833 #endif /* __linux */
3834 !strcmp(con->clientname, "127.0.0.1") ||
3835 !strcmp(con->clientname, "[::1]"));
3836 }
3837
3838 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3839 /*
3840 * Check if the hostname is something.local (Bonjour); if so, allow it.
3841 */
3842
3843 if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
3844 !end[1])
3845 {
3846 /*
3847 * "." on end, work back to second-to-last "."...
3848 */
3849
3850 for (end --; end > con->clientname && *end != '.'; end --);
3851 }
3852
3853 if (end && (!_cups_strcasecmp(end, ".local") ||
3854 !_cups_strcasecmp(end, ".local.")))
3855 return (1);
3856 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3857
3858 /*
3859 * Check if the hostname is an IP address...
3860 */
3861
3862 if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
3863 {
3864 /*
3865 * Possible IPv4/IPv6 address...
3866 */
3867
3868 http_addrlist_t *addrlist; /* List of addresses */
3869
3870
3871 if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
3872 {
3873 /*
3874 * Good IPv4/IPv6 address...
3875 */
3876
3877 httpAddrFreeList(addrlist);
3878 return (1);
3879 }
3880 }
3881
3882 /*
3883 * Check for (alias) name matches...
3884 */
3885
3886 for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
3887 a;
3888 a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
3889 {
3890 /*
3891 * "ServerAlias *" allows all host values through...
3892 */
3893
3894 if (!strcmp(a->name, "*"))
3895 return (1);
3896
3897 if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
3898 {
3899 /*
3900 * Prefix matches; check the character at the end - it must be "." or nul.
3901 */
3902
3903 end = con->clientname + a->namelen;
3904
3905 if (!*end || (*end == '.' && !end[1]))
3906 return (1);
3907 }
3908 }
3909
3910 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3911 for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
3912 a;
3913 a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
3914 {
3915 /*
3916 * "ServerAlias *" allows all host values through...
3917 */
3918
3919 if (!strcmp(a->name, "*"))
3920 return (1);
3921
3922 if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
3923 {
3924 /*
3925 * Prefix matches; check the character at the end - it must be "." or nul.
3926 */
3927
3928 end = con->clientname + a->namelen;
3929
3930 if (!*end || (*end == '.' && !end[1]))
3931 return (1);
3932 }
3933 }
3934 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3935
3936 /*
3937 * Check for interface hostname matches...
3938 */
3939
3940 for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
3941 netif;
3942 netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
3943 {
3944 if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
3945 {
3946 /*
3947 * Prefix matches; check the character at the end - it must be "." or nul.
3948 */
3949
3950 end = con->clientname + netif->hostlen;
3951
3952 if (!*end || (*end == '.' && !end[1]))
3953 return (1);
3954 }
3955 }
3956
3957 return (0);
3958 }
3959
3960
3961 /*
3962 * 'write_file()' - Send a file via HTTP.
3963 */
3964
3965 static int /* O - 0 on failure, 1 on success */
3966 write_file(cupsd_client_t *con, /* I - Client connection */
3967 http_status_t code, /* I - HTTP status */
3968 char *filename, /* I - Filename */
3969 char *type, /* I - File type */
3970 struct stat *filestats) /* O - File information */
3971 {
3972 con->file = open(filename, O_RDONLY);
3973
3974 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3975 "write_file code=%d, filename=\"%s\" (%d), "
3976 "type=\"%s\", filestats=%p",
3977 code, filename, con->file, type ? type : "(null)", filestats);
3978
3979 if (con->file < 0)
3980 return (0);
3981
3982 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
3983
3984 con->pipe_pid = 0;
3985
3986 httpSetLength(con->http, filestats->st_size);
3987
3988 httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
3989 httpGetDateString(filestats->st_mtime));
3990
3991 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
3992 return (0);
3993
3994 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
3995 (cupsd_selfunc_t)cupsdWriteClient, con);
3996
3997 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending file.");
3998
3999 return (1);
4000 }
4001
4002
4003 /*
4004 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4005 */
4006
4007 static void
4008 write_pipe(cupsd_client_t *con) /* I - Client connection */
4009 {
4010 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_pipe CGI output on fd %d",
4011 con->file);
4012
4013 con->file_ready = 1;
4014
4015 cupsdRemoveSelect(con->file);
4016 cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4017
4018 cupsdLogClient(con, CUPSD_LOG_DEBUG, "CGI data ready to be sent.");
4019 }
4020
4021
4022 /*
4023 * End of "$Id$".
4024 */