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