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