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