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