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