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