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