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