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