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