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