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