]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/client.c
Get builds working again (still need to fill in the server-side stuff for TLS)
[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 #ifdef HAVE_LIBSSL
422 #elif defined(HAVE_GNUTLS)
423 # elif defined(HAVE_CDSASSL)
424 #endif /* HAVE_LIBSSL */
425
426
427 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing connection.");
428
429 /*
430 * Flush pending writes before closing...
431 */
432
433 httpFlushWrite(con->http);
434
435 partial = 0;
436
437 if (con->pipe_pid != 0)
438 {
439 /*
440 * Stop any CGI process...
441 */
442
443 cupsdEndProcess(con->pipe_pid, 1);
444 con->pipe_pid = 0;
445 }
446
447 if (con->file >= 0)
448 {
449 cupsdRemoveSelect(con->file);
450
451 close(con->file);
452 con->file = -1;
453 }
454
455 /*
456 * Close the socket and clear the file from the input set for select()...
457 */
458
459 if (httpGetFd(con->http) >= 0)
460 {
461 cupsArrayRemove(ActiveClients, con);
462 cupsdSetBusyState();
463
464 #ifdef HAVE_SSL
465 /*
466 * Shutdown encryption as needed...
467 */
468
469 if (httpIsEncrypted(con->http))
470 partial = 1;
471 #endif /* HAVE_SSL */
472
473 if (partial)
474 {
475 /*
476 * Only do a partial close so that the encrypted client gets everything.
477 */
478
479 httpShutdown(con->http);
480 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
481 NULL, con);
482
483 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for socket close.");
484 }
485 else
486 {
487 /*
488 * Shut the socket down fully...
489 */
490
491 cupsdRemoveSelect(httpGetFd(con->http));
492 httpClose(con->http);
493 con->http = NULL;
494 }
495 }
496
497 if (!partial)
498 {
499 /*
500 * Free memory...
501 */
502
503 cupsdRemoveSelect(httpGetFd(con->http));
504
505 httpClose(con->http);
506
507 cupsdClearString(&con->filename);
508 cupsdClearString(&con->command);
509 cupsdClearString(&con->options);
510 cupsdClearString(&con->query_string);
511
512 if (con->request)
513 {
514 ippDelete(con->request);
515 con->request = NULL;
516 }
517
518 if (con->response)
519 {
520 ippDelete(con->response);
521 con->response = NULL;
522 }
523
524 if (con->language)
525 {
526 cupsLangFree(con->language);
527 con->language = NULL;
528 }
529
530 #ifdef HAVE_AUTHORIZATION_H
531 if (con->authref)
532 {
533 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
534 con->authref = NULL;
535 }
536 #endif /* HAVE_AUTHORIZATION_H */
537
538 /*
539 * Re-enable new client connections if we are going back under the
540 * limit...
541 */
542
543 if (cupsArrayCount(Clients) == MaxClients)
544 cupsdResumeListening();
545
546 /*
547 * Compact the list of clients as necessary...
548 */
549
550 cupsArrayRemove(Clients, con);
551
552 free(con);
553 }
554
555 return (partial);
556 }
557
558
559 #if 0
560 /*
561 * 'cupsdFlushHeader()' - Flush the header fields to the client.
562 */
563
564 int /* I - Bytes written or -1 on error */
565 cupsdFlushHeader(cupsd_client_t *con) /* I - Client to flush to */
566 {
567 int bytes = httpFlushWrite(con->http);
568
569 // TODO: Need to use httpSendResponse
570 con->http->data_encoding = HTTP_ENCODING_LENGTH;
571
572 return (bytes);
573 }
574 #endif /* 0 */
575
576
577 /*
578 * 'cupsdReadClient()' - Read data from a client.
579 */
580
581 void
582 cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
583 {
584 char line[32768], /* Line from client... */
585 locale[64], /* Locale */
586 *ptr; /* Pointer into strings */
587 http_status_t status; /* Transfer status */
588 ipp_state_t ipp_state; /* State of IPP transfer */
589 int bytes; /* Number of bytes to POST */
590 char *filename; /* Name of file for GET/HEAD */
591 char buf[1024]; /* Buffer for real filename */
592 struct stat filestats; /* File information */
593 mime_type_t *type; /* MIME type of file */
594 cupsd_printer_t *p; /* Printer */
595 static unsigned request_id = 0; /* Request ID for temp files */
596
597
598 status = HTTP_STATUS_CONTINUE;
599
600 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
601 "cupsdReadClient "
602 "error=%d, "
603 "used=%d, "
604 "state=%s, "
605 "data_encoding=HTTP_ENCODING_%s, "
606 "data_remaining=" CUPS_LLFMT ", "
607 "request=%p(%s), "
608 "file=%d",
609 httpError(con->http), (int)httpGetReady(con->http),
610 httpStateString(httpGetState(con->http)),
611 httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
612 CUPS_LLCAST httpGetRemaining(con->http),
613 con->request,
614 con->request ? ippStateString(ippGetState(con->request)) : "",
615 con->file);
616
617 #ifdef HAVE_SSL
618 if (con->auto_ssl)
619 {
620 /*
621 * Automatically check for a SSL/TLS handshake...
622 */
623
624 con->auto_ssl = 0;
625
626 if (recv(httpGetFd(con->http), buf, 1, MSG_PEEK) == 1 &&
627 (!buf[0] || !strchr("DGHOPT", buf[0])))
628 {
629 /*
630 * Encrypt this connection...
631 */
632
633 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
634 "Saw first byte %02X, auto-negotiating "
635 "SSL/TLS session.", buf[0] & 255);
636
637 if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
638 cupsdCloseClient(con);
639
640 return;
641 }
642 }
643 #endif /* HAVE_SSL */
644
645 switch (httpGetState(con->http))
646 {
647 case HTTP_STATE_WAITING :
648 /*
649 * See if we've received a request line...
650 */
651
652 con->operation = httpReadRequest(con->http, con->uri, sizeof(con->uri));
653 if (con->operation == HTTP_STATE_ERROR ||
654 con->operation == HTTP_STATE_UNKNOWN_METHOD ||
655 con->operation == HTTP_STATE_UNKNOWN_VERSION)
656 {
657 if (httpError(con->http))
658 cupsdLogClient(con, CUPSD_LOG_DEBUG,
659 "HTTP_STATE_WAITING Closing for error %d (%s)",
660 httpError(con->http), strerror(httpError(con->http)));
661 else
662 cupsdLogClient(con, CUPSD_LOG_DEBUG,
663 "HTTP_STATE_WAITING Closing on error: %s",
664 cupsLastErrorString());
665
666 cupsdCloseClient(con);
667 return;
668 }
669
670 /*
671 * Ignore blank request lines...
672 */
673
674 if (con->operation == HTTP_STATE_WAITING)
675 break;
676
677 /*
678 * Clear other state variables...
679 */
680
681 con->bytes = 0;
682 con->file = -1;
683 con->file_ready = 0;
684 con->pipe_pid = 0;
685 con->username[0] = '\0';
686 con->password[0] = '\0';
687
688 cupsdClearString(&con->command);
689 cupsdClearString(&con->options);
690 cupsdClearString(&con->query_string);
691
692 if (con->request)
693 {
694 ippDelete(con->request);
695 con->request = NULL;
696 }
697
698 if (con->response)
699 {
700 ippDelete(con->response);
701 con->response = NULL;
702 }
703
704 if (con->language)
705 {
706 cupsLangFree(con->language);
707 con->language = NULL;
708 }
709
710 #ifdef HAVE_GSSAPI
711 con->have_gss = 0;
712 con->gss_uid = 0;
713 #endif /* HAVE_GSSAPI */
714
715 /*
716 * Handle full URLs in the request line...
717 */
718
719 if (strcmp(con->uri, "*"))
720 {
721 char scheme[HTTP_MAX_URI], /* Method/scheme */
722 userpass[HTTP_MAX_URI], /* Username:password */
723 hostname[HTTP_MAX_URI], /* Hostname */
724 resource[HTTP_MAX_URI]; /* Resource path */
725 int port; /* Port number */
726
727 /*
728 * Separate the URI into its components...
729 */
730
731 if (httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
732 scheme, sizeof(scheme),
733 userpass, sizeof(userpass),
734 hostname, sizeof(hostname), &port,
735 resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
736 {
737 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
738 con->uri);
739 cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
740 cupsdCloseClient(con);
741 return;
742 }
743
744 /*
745 * Only allow URIs with the servername, localhost, or an IP
746 * address...
747 */
748
749 if (strcmp(scheme, "file") &&
750 _cups_strcasecmp(hostname, ServerName) &&
751 _cups_strcasecmp(hostname, "localhost") &&
752 !cupsArrayFind(ServerAlias, hostname) &&
753 !isdigit(hostname[0]) && hostname[0] != '[')
754 {
755 /*
756 * Nope, we don't do proxies...
757 */
758
759 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
760 con->uri);
761 cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
762 cupsdCloseClient(con);
763 return;
764 }
765
766 /*
767 * Copy the resource portion back into the URI; both resource and
768 * con->uri are HTTP_MAX_URI bytes in size...
769 */
770
771 strlcpy(con->uri, resource, sizeof(con->uri));
772 }
773
774 /*
775 * Process the request...
776 */
777
778 gettimeofday(&(con->start), NULL);
779
780 cupsdLogClient(con, CUPSD_LOG_DEBUG, "%s %s HTTP/%d.%d",
781 httpStateString(con->operation) + 11, con->uri,
782 httpGetVersion(con->http) / 100,
783 httpGetVersion(con->http) % 100);
784
785 if (!cupsArrayFind(ActiveClients, con))
786 {
787 cupsArrayAdd(ActiveClients, con);
788 cupsdSetBusyState();
789 }
790
791 case HTTP_STATE_OPTIONS :
792 case HTTP_STATE_DELETE :
793 case HTTP_STATE_GET :
794 case HTTP_STATE_HEAD :
795 case HTTP_STATE_POST :
796 case HTTP_STATE_PUT :
797 case HTTP_STATE_TRACE :
798 /*
799 * Parse incoming parameters until the status changes...
800 */
801
802 while ((status = httpUpdate(con->http)) == HTTP_STATUS_CONTINUE)
803 if (!httpGetReady(con->http))
804 break;
805
806 if (status != HTTP_STATUS_OK && status != HTTP_STATUS_CONTINUE)
807 {
808 if (httpError(con->http) && httpError(con->http) != EPIPE)
809 cupsdLogClient(con, CUPSD_LOG_DEBUG,
810 "Closing for error %d (%s) while reading headers.",
811 httpError(con->http), strerror(httpError(con->http)));
812 else
813 cupsdLogClient(con, CUPSD_LOG_DEBUG,
814 "Closing on EOF while reading headers.");
815
816 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
817 cupsdCloseClient(con);
818 return;
819 }
820 break;
821
822 default :
823 if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
824 {
825 /*
826 * Connection closed...
827 */
828
829 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
830 cupsdCloseClient(con);
831 return;
832 }
833 break; /* Anti-compiler-warning-code */
834 }
835
836 /*
837 * Handle new transfers...
838 */
839
840 if (status == HTTP_STATUS_OK)
841 {
842 if (httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE)[0])
843 {
844 /*
845 * Figure out the locale from the Accept-Language and Content-Type
846 * fields...
847 */
848
849 if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
850 ',')) != NULL)
851 *ptr = '\0';
852
853 if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
854 ';')) != NULL)
855 *ptr = '\0';
856
857 if ((ptr = strstr(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
858 "charset=")) != NULL)
859 {
860 /*
861 * Combine language and charset, and trim any extra params in the
862 * content-type.
863 */
864
865 snprintf(locale, sizeof(locale), "%s.%s",
866 httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE), ptr + 8);
867
868 if ((ptr = strchr(locale, ',')) != NULL)
869 *ptr = '\0';
870 }
871 else
872 snprintf(locale, sizeof(locale), "%s.UTF-8",
873 httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE));
874
875 con->language = cupsLangGet(locale);
876 }
877 else
878 con->language = cupsLangGet(DefaultLocale);
879
880 cupsdAuthorize(con);
881
882 if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
883 "Keep-Alive", 10) && KeepAlive)
884 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_ON);
885 else if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
886 "close", 5))
887 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
888
889 if (!httpGetField(con->http, HTTP_FIELD_HOST)[0] &&
890 httpGetVersion(con->http) >= HTTP_VERSION_1_1)
891 {
892 /*
893 * HTTP/1.1 and higher require the "Host:" field...
894 */
895
896 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
897 {
898 cupsdLogClient(con, CUPSD_LOG_ERROR, "Missing Host: field in request.");
899 cupsdCloseClient(con);
900 return;
901 }
902 }
903 else if (!valid_host(con))
904 {
905 /*
906 * Access to localhost must use "localhost" or the corresponding IPv4
907 * or IPv6 values in the Host: field.
908 */
909
910 cupsdLogClient(con, CUPSD_LOG_ERROR,
911 "Request from \"%s\" using invalid Host: field \"%s\".",
912 httpGetHostname(con->http, NULL, 0), httpGetField(con->http, HTTP_FIELD_HOST));
913
914 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
915 {
916 cupsdCloseClient(con);
917 return;
918 }
919 }
920 else if (con->operation == HTTP_STATE_OPTIONS)
921 {
922 /*
923 * Do OPTIONS command...
924 */
925
926 if (con->best && con->best->type != CUPSD_AUTH_NONE)
927 {
928 httpClearFields(con->http);
929
930 if (!cupsdSendHeader(con, HTTP_STATUS_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
931 {
932 cupsdCloseClient(con);
933 return;
934 }
935 }
936
937 if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION), "Upgrade") &&
938 !httpIsEncrypted(con->http))
939 {
940 #ifdef HAVE_SSL
941 /*
942 * Do encryption stuff...
943 */
944
945 httpClearFields(con->http);
946
947 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
948 {
949 cupsdCloseClient(con);
950 return;
951 }
952
953 if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
954 {
955 cupsdCloseClient(con);
956 return;
957 }
958 #else
959 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
960 {
961 cupsdCloseClient(con);
962 return;
963 }
964 #endif /* HAVE_SSL */
965 }
966
967 httpClearFields(con->http);
968 httpSetField(con->http, HTTP_FIELD_ALLOW,
969 "GET, HEAD, OPTIONS, POST, PUT");
970 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
971
972 if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
973 {
974 cupsdCloseClient(con);
975 return;
976 }
977 }
978 else if (!is_path_absolute(con->uri))
979 {
980 /*
981 * Protect against malicious users!
982 */
983
984 cupsdLogClient(con, CUPSD_LOG_ERROR,
985 "Request for non-absolute resource \"%s\".", con->uri);
986
987 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
988 {
989 cupsdCloseClient(con);
990 return;
991 }
992 }
993 else
994 {
995 if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
996 "Upgrade") && !httpIsEncrypted(con->http))
997 {
998 #ifdef HAVE_SSL
999 /*
1000 * Do encryption stuff...
1001 */
1002
1003 httpClearFields(con->http);
1004
1005 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,
1006 CUPSD_AUTH_NONE))
1007 {
1008 cupsdCloseClient(con);
1009 return;
1010 }
1011
1012 if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
1013 {
1014 cupsdCloseClient(con);
1015 return;
1016 }
1017 #else
1018 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
1019 {
1020 cupsdCloseClient(con);
1021 return;
1022 }
1023 #endif /* HAVE_SSL */
1024 }
1025
1026 if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_STATUS_OK)
1027 {
1028 cupsdSendError(con, status, CUPSD_AUTH_NONE);
1029 cupsdCloseClient(con);
1030 return;
1031 }
1032
1033 if (httpGetExpect(con->http) &&
1034 (con->operation == HTTP_STATE_POST || con->operation == HTTP_STATE_PUT))
1035 {
1036 if (httpGetExpect(con->http) == HTTP_STATUS_CONTINUE)
1037 {
1038 /*
1039 * Send 100-continue header...
1040 */
1041
1042 if (httpWriteResponse(con->http, HTTP_STATUS_CONTINUE))
1043 {
1044 cupsdCloseClient(con);
1045 return;
1046 }
1047 }
1048 else
1049 {
1050 /*
1051 * Send 417-expectation-failed header...
1052 */
1053
1054 httpClearFields(con->http);
1055 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
1056
1057 cupsdSendError(con, HTTP_STATUS_EXPECTATION_FAILED, CUPSD_AUTH_NONE);
1058 cupsdCloseClient(con);
1059 return;
1060 }
1061 }
1062
1063 switch (httpGetState(con->http))
1064 {
1065 case HTTP_STATE_GET_SEND :
1066 if ((!strncmp(con->uri, "/ppd/", 5) ||
1067 !strncmp(con->uri, "/printers/", 10) ||
1068 !strncmp(con->uri, "/classes/", 9)) &&
1069 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1070 {
1071 /*
1072 * Send PPD file - get the real printer name since printer
1073 * names are not case sensitive but filenames can be...
1074 */
1075
1076 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1077
1078 if (!strncmp(con->uri, "/ppd/", 5))
1079 p = cupsdFindPrinter(con->uri + 5);
1080 else if (!strncmp(con->uri, "/printers/", 10))
1081 p = cupsdFindPrinter(con->uri + 10);
1082 else
1083 {
1084 p = cupsdFindClass(con->uri + 9);
1085
1086 if (p)
1087 {
1088 int i; /* Looping var */
1089
1090 for (i = 0; i < p->num_printers; i ++)
1091 {
1092 if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
1093 {
1094 char ppdname[1024];/* PPD filename */
1095
1096 snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
1097 ServerRoot, p->printers[i]->name);
1098 if (!access(ppdname, 0))
1099 {
1100 p = p->printers[i];
1101 break;
1102 }
1103 }
1104 }
1105
1106 if (i >= p->num_printers)
1107 p = NULL;
1108 }
1109 }
1110
1111 if (p)
1112 {
1113 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1114 }
1115 else
1116 {
1117 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1118 {
1119 cupsdCloseClient(con);
1120 return;
1121 }
1122
1123 break;
1124 }
1125 }
1126 else if ((!strncmp(con->uri, "/icons/", 7) ||
1127 !strncmp(con->uri, "/printers/", 10) ||
1128 !strncmp(con->uri, "/classes/", 9)) &&
1129 !strcmp(con->uri + strlen(con->uri) - 4, ".png"))
1130 {
1131 /*
1132 * Send icon file - get the real queue name since queue names are
1133 * not case sensitive but filenames can be...
1134 */
1135
1136 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".png" */
1137
1138 if (!strncmp(con->uri, "/icons/", 7))
1139 p = cupsdFindPrinter(con->uri + 7);
1140 else if (!strncmp(con->uri, "/printers/", 10))
1141 p = cupsdFindPrinter(con->uri + 10);
1142 else
1143 {
1144 p = cupsdFindClass(con->uri + 9);
1145
1146 if (p)
1147 {
1148 int i; /* Looping var */
1149
1150 for (i = 0; i < p->num_printers; i ++)
1151 {
1152 if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
1153 {
1154 char ppdname[1024];/* PPD filename */
1155
1156 snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
1157 ServerRoot, p->printers[i]->name);
1158 if (!access(ppdname, 0))
1159 {
1160 p = p->printers[i];
1161 break;
1162 }
1163 }
1164 }
1165
1166 if (i >= p->num_printers)
1167 p = NULL;
1168 }
1169 }
1170
1171 if (p)
1172 snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
1173 else
1174 {
1175 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1176 {
1177 cupsdCloseClient(con);
1178 return;
1179 }
1180
1181 break;
1182 }
1183 }
1184 else if (!WebInterface)
1185 {
1186 /*
1187 * Web interface is disabled. Show an appropriate message...
1188 */
1189
1190 if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
1191 {
1192 cupsdCloseClient(con);
1193 return;
1194 }
1195
1196 break;
1197 }
1198
1199 if ((!strncmp(con->uri, "/admin", 6) &&
1200 strncmp(con->uri, "/admin/conf/", 12) &&
1201 strncmp(con->uri, "/admin/log/", 11)) ||
1202 !strncmp(con->uri, "/printers", 9) ||
1203 !strncmp(con->uri, "/classes", 8) ||
1204 !strncmp(con->uri, "/help", 5) ||
1205 !strncmp(con->uri, "/jobs", 5))
1206 {
1207 /*
1208 * Send CGI output...
1209 */
1210
1211 if (!strncmp(con->uri, "/admin", 6))
1212 {
1213 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1214 ServerBin);
1215
1216 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
1217 }
1218 else if (!strncmp(con->uri, "/printers", 9))
1219 {
1220 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1221 ServerBin);
1222
1223 if (con->uri[9] && con->uri[10])
1224 cupsdSetString(&con->options, con->uri + 9);
1225 else
1226 cupsdSetString(&con->options, NULL);
1227 }
1228 else if (!strncmp(con->uri, "/classes", 8))
1229 {
1230 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1231 ServerBin);
1232
1233 if (con->uri[8] && con->uri[9])
1234 cupsdSetString(&con->options, con->uri + 8);
1235 else
1236 cupsdSetString(&con->options, NULL);
1237 }
1238 else if (!strncmp(con->uri, "/jobs", 5))
1239 {
1240 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1241 ServerBin);
1242
1243 if (con->uri[5] && con->uri[6])
1244 cupsdSetString(&con->options, con->uri + 5);
1245 else
1246 cupsdSetString(&con->options, NULL);
1247 }
1248 else
1249 {
1250 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1251 ServerBin);
1252
1253 if (con->uri[5] && con->uri[6])
1254 cupsdSetString(&con->options, con->uri + 5);
1255 else
1256 cupsdSetString(&con->options, NULL);
1257 }
1258
1259 if (!cupsdSendCommand(con, con->command, con->options, 0))
1260 {
1261 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1262 {
1263 cupsdCloseClient(con);
1264 return;
1265 }
1266 }
1267 else
1268 cupsdLogRequest(con, HTTP_STATUS_OK);
1269
1270 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1271 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1272 }
1273 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1274 (strchr(con->uri + 12, '/') ||
1275 strlen(con->uri) == 12)) ||
1276 (!strncmp(con->uri, "/admin/log/", 11) &&
1277 (strchr(con->uri + 11, '/') ||
1278 strlen(con->uri) == 11)))
1279 {
1280 /*
1281 * GET can only be done to configuration files directly under
1282 * /admin/conf...
1283 */
1284
1285 cupsdLogClient(con, CUPSD_LOG_ERROR,
1286 "Request for subdirectory \"%s\"!", con->uri);
1287
1288 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1289 {
1290 cupsdCloseClient(con);
1291 return;
1292 }
1293
1294 break;
1295 }
1296 else
1297 {
1298 /*
1299 * Serve a file...
1300 */
1301
1302 if ((filename = get_file(con, &filestats, buf,
1303 sizeof(buf))) == NULL)
1304 {
1305 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1306 {
1307 cupsdCloseClient(con);
1308 return;
1309 }
1310
1311 break;
1312 }
1313
1314 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
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 httpSetLength(con->http, strlen(message));
2272
2273 if (!cupsdSendHeader(con, code, "text/html", auth_type))
2274 return (0);
2275
2276 if (httpPrintf(con->http, "%s", message) < 0)
2277 return (0);
2278 }
2279 else
2280 {
2281 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
2282
2283 if (!cupsdSendHeader(con, code, NULL, auth_type))
2284 return (0);
2285 }
2286
2287 return (1);
2288 }
2289
2290
2291 /*
2292 * 'cupsdSendHeader()' - Send an HTTP request.
2293 */
2294
2295 int /* O - 1 on success, 0 on failure */
2296 cupsdSendHeader(
2297 cupsd_client_t *con, /* I - Client to send to */
2298 http_status_t code, /* I - HTTP status code */
2299 char *type, /* I - MIME type of document */
2300 int auth_type) /* I - Type of authentication */
2301 {
2302 char auth_str[1024]; /* Authorization string */
2303
2304
2305 /*
2306 * Send the HTTP status header...
2307 */
2308
2309 if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
2310 {
2311 /*
2312 * Treat our special "web interface is disabled" status as "200 OK" for web
2313 * browsers.
2314 */
2315
2316 code = HTTP_STATUS_OK;
2317 }
2318
2319 if (ServerHeader)
2320 httpSetField(con->http, HTTP_FIELD_SERVER, ServerHeader);
2321
2322 if (code == HTTP_STATUS_METHOD_NOT_ALLOWED)
2323 httpSetField(con->http, HTTP_FIELD_ALLOW, "GET, HEAD, OPTIONS, POST, PUT");
2324
2325 if (code == HTTP_STATUS_UNAUTHORIZED)
2326 {
2327 if (auth_type == CUPSD_AUTH_NONE)
2328 {
2329 if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
2330 auth_type = cupsdDefaultAuthType();
2331 else
2332 auth_type = con->best->type;
2333 }
2334
2335 auth_str[0] = '\0';
2336
2337 if (auth_type == CUPSD_AUTH_BASIC || auth_type == CUPSD_AUTH_BASICDIGEST)
2338 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2339 else if (auth_type == CUPSD_AUTH_DIGEST)
2340 snprintf(auth_str, sizeof(auth_str), "Digest realm=\"CUPS\", nonce=\"%s\"",
2341 httpGetHostname(con->http, NULL, 0));
2342 #ifdef HAVE_GSSAPI
2343 else if (auth_type == CUPSD_AUTH_NEGOTIATE)
2344 {
2345 # ifdef AF_LOCAL
2346 if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
2347 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2348 else
2349 # endif /* AF_LOCAL */
2350 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2351 }
2352 #endif /* HAVE_GSSAPI */
2353
2354 if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
2355 !_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost"))
2356 {
2357 /*
2358 * Add a "trc" (try root certification) parameter for local non-Kerberos
2359 * requests when the request requires system group membership - then the
2360 * client knows the root certificate can/should be used.
2361 *
2362 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2363 * parameter as needed...
2364 */
2365
2366 char *name, /* Current user name */
2367 *auth_key; /* Auth key buffer */
2368 size_t auth_size; /* Size of remaining buffer */
2369
2370 auth_key = auth_str + strlen(auth_str);
2371 auth_size = sizeof(auth_str) - (auth_key - auth_str);
2372
2373 for (name = (char *)cupsArrayFirst(con->best->names);
2374 name;
2375 name = (char *)cupsArrayNext(con->best->names))
2376 {
2377 #ifdef HAVE_AUTHORIZATION_H
2378 if (!_cups_strncasecmp(name, "@AUTHKEY(", 9))
2379 {
2380 snprintf(auth_key, auth_size, ", authkey=\"%s\"", name + 9);
2381 /* end parenthesis is stripped in conf.c */
2382 break;
2383 }
2384 else
2385 #endif /* HAVE_AUTHORIZATION_H */
2386 if (!_cups_strcasecmp(name, "@SYSTEM"))
2387 {
2388 #ifdef HAVE_AUTHORIZATION_H
2389 if (SystemGroupAuthKey)
2390 snprintf(auth_key, auth_size,
2391 ", authkey=\"%s\"",
2392 SystemGroupAuthKey);
2393 else
2394 #else
2395 strlcpy(auth_key, ", trc=\"y\"", auth_size);
2396 #endif /* HAVE_AUTHORIZATION_H */
2397 break;
2398 }
2399 }
2400 }
2401
2402 if (auth_str[0])
2403 {
2404 cupsdLogClient(con, CUPSD_LOG_DEBUG, "WWW-Authenticate: %s", auth_str);
2405
2406 httpSetField(con->http, HTTP_FIELD_WWW_AUTHENTICATE, auth_str);
2407 }
2408 }
2409
2410 if (con->language && strcmp(con->language->language, "C"))
2411 httpSetField(con->http, HTTP_FIELD_CONTENT_LANGUAGE, con->language->language);
2412
2413 if (type)
2414 {
2415 if (!strcmp(type, "text/html"))
2416 httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, "text/html; charset=utf-8");
2417 else
2418 httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, type);
2419 }
2420
2421 return (!httpWriteResponse(con->http, code));
2422 }
2423
2424
2425 /*
2426 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2427 */
2428
2429 void
2430 cupsdUpdateCGI(void)
2431 {
2432 char *ptr, /* Pointer to end of line in buffer */
2433 message[1024]; /* Pointer to message text */
2434 int loglevel; /* Log level for message */
2435
2436
2437 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2438 message, sizeof(message))) != NULL)
2439 {
2440 if (loglevel == CUPSD_LOG_INFO)
2441 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
2442
2443 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2444 break;
2445 }
2446
2447 if (ptr == NULL && !CGIStatusBuffer->bufused)
2448 {
2449 /*
2450 * Fatal error on pipe - should never happen!
2451 */
2452
2453 cupsdLogMessage(CUPSD_LOG_CRIT,
2454 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2455 strerror(errno));
2456 }
2457 }
2458
2459
2460 /*
2461 * 'cupsdWriteClient()' - Write data to a client as needed.
2462 */
2463
2464 void
2465 cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2466 {
2467 int bytes, /* Number of bytes written */
2468 field_col; /* Current column */
2469 char *bufptr, /* Pointer into buffer */
2470 *bufend; /* Pointer to end of buffer */
2471 ipp_state_t ipp_state; /* IPP state value */
2472
2473
2474 cupsdLogClient(con, CUPSD_LOG_DEBUG, "con->http=%p", con->http);
2475 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2476 "cupsdWriteClient "
2477 "error=%d, "
2478 "used=%d, "
2479 "state=%s, "
2480 "data_encoding=HTTP_ENCODING_%s, "
2481 "data_remaining=" CUPS_LLFMT ", "
2482 "response=%p(%s), "
2483 "pipe_pid=%d, "
2484 "file=%d",
2485 httpError(con->http), (int)httpGetReady(con->http),
2486 httpStateString(httpGetState(con->http)),
2487 httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
2488 CUPS_LLCAST httpGetLength2(con->http),
2489 con->response,
2490 con->response ? ippStateString(ippGetState(con->request)) : "",
2491 con->pipe_pid, con->file);
2492
2493 if (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
2494 httpGetState(con->http) != HTTP_STATE_POST_SEND)
2495 {
2496 /*
2497 * If we get called in the wrong state, then something went wrong with the
2498 * connection and we need to shut it down...
2499 */
2500
2501 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP state %s.",
2502 httpStateString(httpGetState(con->http)));
2503 cupsdCloseClient(con);
2504 return;
2505 }
2506
2507 if (con->pipe_pid)
2508 {
2509 /*
2510 * Make sure we select on the CGI output...
2511 */
2512
2513 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2514
2515 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
2516
2517 if (!con->file_ready)
2518 {
2519 /*
2520 * Try again later when there is CGI output available...
2521 */
2522
2523 cupsdRemoveSelect(httpGetFd(con->http));
2524 return;
2525 }
2526
2527 con->file_ready = 0;
2528 }
2529
2530 if (con->response && con->response->state != IPP_STATE_DATA)
2531 {
2532 size_t wused = httpGetPending(con->http); /* Previous write buffer use */
2533
2534 do
2535 {
2536 /*
2537 * Write a single attribute or the IPP message header...
2538 */
2539
2540 ipp_state = ippWrite(con->http, con->response);
2541
2542 /*
2543 * If the write buffer has been flushed, stop buffering up attributes...
2544 */
2545
2546 if (httpGetPending(con->http) <= wused)
2547 break;
2548 }
2549 while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR);
2550
2551 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2552 "Writing IPP response, ipp_state=%s, old "
2553 "wused=" CUPS_LLFMT ", new wused=" CUPS_LLFMT,
2554 ippStateString(ipp_state),
2555 CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http));
2556
2557 if (httpGetPending(con->http) > 0)
2558 httpFlushWrite(con->http);
2559
2560 bytes = ipp_state != IPP_STATE_ERROR &&
2561 (con->file >= 0 || ipp_state != IPP_STATE_DATA);
2562
2563 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2564 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT,
2565 (int)bytes, httpGetState(con->http),
2566 CUPS_LLCAST httpGetLength2(con->http));
2567 }
2568 else if ((bytes = read(con->file, con->header + con->header_used,
2569 sizeof(con->header) - con->header_used)) > 0)
2570 {
2571 con->header_used += bytes;
2572
2573 if (con->pipe_pid && !con->got_fields)
2574 {
2575 /*
2576 * Inspect the data for Content-Type and other fields.
2577 */
2578
2579 for (bufptr = con->header, bufend = con->header + con->header_used,
2580 field_col = 0;
2581 !con->got_fields && bufptr < bufend;
2582 bufptr ++)
2583 {
2584 if (*bufptr == '\n')
2585 {
2586 /*
2587 * Send line to client...
2588 */
2589
2590 if (bufptr > con->header && bufptr[-1] == '\r')
2591 bufptr[-1] = '\0';
2592 *bufptr++ = '\0';
2593
2594 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Script header: %s", con->header);
2595
2596 if (!con->sent_header)
2597 {
2598 /*
2599 * Handle redirection and CGI status codes...
2600 */
2601
2602 http_field_t field; /* HTTP field */
2603 char *value = strchr(con->header, ':');
2604 /* Value of field */
2605
2606 if (value)
2607 {
2608 *value++ = '\0';
2609 while (isspace(*value & 255))
2610 value ++;
2611 }
2612
2613 field = httpFieldValue(con->header);
2614
2615 if (field != HTTP_FIELD_UNKNOWN && value)
2616 {
2617 httpSetField(con->http, field, value);
2618
2619 if (field == HTTP_FIELD_LOCATION)
2620 {
2621 con->pipe_status = HTTP_STATUS_SEE_OTHER;
2622 con->sent_header = 2;
2623 }
2624 else
2625 con->sent_header = 1;
2626 }
2627 else if (!_cups_strcasecmp(con->header, "Status") && value)
2628 {
2629 con->pipe_status = (http_status_t)atoi(value);
2630 con->sent_header = 2;
2631 }
2632 else if (!_cups_strcasecmp(con->header, "Set-Cookie") && value)
2633 {
2634 char *sep = strchr(value, ';');
2635 /* Separator between name=value and the rest */
2636
2637 if (sep)
2638 *sep = '\0';
2639
2640 httpSetCookie(con->http, value);
2641 con->sent_header = 1;
2642 }
2643 }
2644
2645 /*
2646 * Update buffer...
2647 */
2648
2649 con->header_used -= bufptr - con->header;
2650
2651 if (con->header_used > 0)
2652 memmove(con->header, bufptr, con->header_used);
2653
2654 bufptr = con->header - 1;
2655
2656 /*
2657 * See if the line was empty...
2658 */
2659
2660 if (field_col == 0)
2661 {
2662 con->got_fields = 1;
2663
2664 if (httpGetVersion(con->http) == HTTP_VERSION_1_1 &&
2665 !httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0])
2666 httpSetLength(con->http, 0);
2667
2668 if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE))
2669 {
2670 cupsdCloseClient(con);
2671 return;
2672 }
2673 }
2674 else
2675 field_col = 0;
2676 }
2677 else if (*bufptr != '\r')
2678 field_col ++;
2679 }
2680
2681 if (!con->got_fields)
2682 return;
2683 }
2684
2685 if (con->header_used > 0)
2686 {
2687 if (httpWrite2(con->http, con->header, con->header_used) < 0)
2688 {
2689 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
2690 httpError(con->http), strerror(httpError(con->http)));
2691 cupsdCloseClient(con);
2692 return;
2693 }
2694
2695 if (httpIsChunked(con->http))
2696 httpFlushWrite(con->http);
2697
2698 con->bytes += con->header_used;
2699
2700 if (httpGetState(con->http) == HTTP_STATE_WAITING)
2701 bytes = 0;
2702 else
2703 bytes = con->header_used;
2704
2705 con->header_used = 0;
2706 }
2707 }
2708
2709 if (bytes <= 0 ||
2710 (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
2711 httpGetState(con->http) != HTTP_STATE_POST_SEND))
2712 {
2713 if (!con->sent_header && con->pipe_pid)
2714 cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE);
2715 else
2716 {
2717 cupsdLogRequest(con, HTTP_STATUS_OK);
2718
2719 httpFlushWrite(con->http);
2720
2721 if (httpIsChunked(con->http) && con->sent_header == 1)
2722 {
2723 if (httpWrite2(con->http, "", 0) < 0)
2724 {
2725 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
2726 httpError(con->http), strerror(httpError(con->http)));
2727 cupsdCloseClient(con);
2728 return;
2729 }
2730 }
2731 }
2732
2733 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con);
2734
2735 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
2736
2737 if (con->file >= 0)
2738 {
2739 cupsdRemoveSelect(con->file);
2740
2741 if (con->pipe_pid)
2742 cupsdEndProcess(con->pipe_pid, 0);
2743
2744 close(con->file);
2745 con->file = -1;
2746 con->pipe_pid = 0;
2747 }
2748
2749 if (con->filename)
2750 {
2751 unlink(con->filename);
2752 cupsdClearString(&con->filename);
2753 }
2754
2755 if (con->request)
2756 {
2757 ippDelete(con->request);
2758 con->request = NULL;
2759 }
2760
2761 if (con->response)
2762 {
2763 ippDelete(con->response);
2764 con->response = NULL;
2765 }
2766
2767 cupsdClearString(&con->command);
2768 cupsdClearString(&con->options);
2769 cupsdClearString(&con->query_string);
2770
2771 if (!httpGetKeepAlive(con->http))
2772 {
2773 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2774 "Closing because Keep-Alive is disabled.");
2775 cupsdCloseClient(con);
2776 return;
2777 }
2778 else
2779 {
2780 cupsArrayRemove(ActiveClients, con);
2781 cupsdSetBusyState();
2782 }
2783 }
2784 }
2785
2786
2787 /*
2788 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2789 */
2790
2791 static int /* O - 1 if modified since */
2792 check_if_modified(
2793 cupsd_client_t *con, /* I - Client connection */
2794 struct stat *filestats) /* I - File information */
2795 {
2796 const char *ptr; /* Pointer into field */
2797 time_t date; /* Time/date value */
2798 off_t size; /* Size/length value */
2799
2800
2801 size = 0;
2802 date = 0;
2803 ptr = httpGetField(con->http, HTTP_FIELD_IF_MODIFIED_SINCE);
2804
2805 if (*ptr == '\0')
2806 return (1);
2807
2808 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
2809 "check_if_modified "
2810 "filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"",
2811 filestats, CUPS_LLCAST filestats->st_size,
2812 (int)filestats->st_mtime, ptr);
2813
2814 while (*ptr != '\0')
2815 {
2816 while (isspace(*ptr) || *ptr == ';')
2817 ptr ++;
2818
2819 if (_cups_strncasecmp(ptr, "length=", 7) == 0)
2820 {
2821 ptr += 7;
2822 size = strtoll(ptr, NULL, 10);
2823
2824 while (isdigit(*ptr))
2825 ptr ++;
2826 }
2827 else if (isalpha(*ptr))
2828 {
2829 date = httpGetDateTime(ptr);
2830 while (*ptr != '\0' && *ptr != ';')
2831 ptr ++;
2832 }
2833 else
2834 ptr ++;
2835 }
2836
2837 return ((size != filestats->st_size && size != 0) ||
2838 (date < filestats->st_mtime && date != 0) ||
2839 (size == 0 && date == 0));
2840 }
2841
2842
2843 /*
2844 * 'compare_clients()' - Compare two client connections.
2845 */
2846
2847 static int /* O - Result of comparison */
2848 compare_clients(cupsd_client_t *a, /* I - First client */
2849 cupsd_client_t *b, /* I - Second client */
2850 void *data) /* I - User data (not used) */
2851 {
2852 (void)data;
2853
2854 if (a == b)
2855 return (0);
2856 else if (a < b)
2857 return (-1);
2858 else
2859 return (1);
2860 }
2861
2862
2863 #ifdef HAVE_SSL
2864 /*
2865 * 'cupsd_start_tls()' - Start encryption on a connection.
2866 */
2867
2868 static int /* O - 0 on success, -1 on error */
2869 cupsd_start_tls(cupsd_client_t *con, /* I - Client connection */
2870 http_encryption_t e) /* I - Encryption mode */
2871 {
2872 /* TODO: Lookup/load cert + key and set */
2873 if (httpEncryption(con->http, e))
2874 {
2875 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to encrypt connection: %s",
2876 cupsLastErrorString());
2877 return (-1);
2878 }
2879
2880 cupsdLogClient(con, CUPSD_LOG_INFO, "Connection now encrypted.");
2881 return (0);
2882 }
2883 #endif /* HAVE_SSL */
2884
2885
2886 /*
2887 * 'get_file()' - Get a filename and state info.
2888 */
2889
2890 static char * /* O - Real filename */
2891 get_file(cupsd_client_t *con, /* I - Client connection */
2892 struct stat *filestats, /* O - File information */
2893 char *filename, /* IO - Filename buffer */
2894 int len) /* I - Buffer length */
2895 {
2896 int status; /* Status of filesystem calls */
2897 char *ptr; /* Pointer info filename */
2898 int plen; /* Remaining length after pointer */
2899 char language[7]; /* Language subdirectory, if any */
2900
2901
2902 /*
2903 * Figure out the real filename...
2904 */
2905
2906 language[0] = '\0';
2907
2908 if (!strncmp(con->uri, "/ppd/", 5) && !strchr(con->uri + 5, '/'))
2909 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
2910 else if (!strncmp(con->uri, "/icons/", 7) && !strchr(con->uri + 7, '/'))
2911 {
2912 snprintf(filename, len, "%s/%s", CacheDir, con->uri + 7);
2913 if (access(filename, F_OK) < 0)
2914 snprintf(filename, len, "%s/images/generic.png", DocumentRoot);
2915 }
2916 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
2917 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
2918 else if (!strncmp(con->uri, "/admin/conf/", 12))
2919 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
2920 else if (!strncmp(con->uri, "/admin/log/", 11))
2921 {
2922 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
2923 strlcpy(filename, AccessLog, len);
2924 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
2925 strlcpy(filename, ErrorLog, len);
2926 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
2927 strlcpy(filename, PageLog, len);
2928 else
2929 return (NULL);
2930 }
2931 else if (con->language)
2932 {
2933 snprintf(language, sizeof(language), "/%s", con->language->language);
2934 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
2935 }
2936 else
2937 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
2938
2939 if ((ptr = strchr(filename, '?')) != NULL)
2940 *ptr = '\0';
2941
2942 /*
2943 * Grab the status for this language; if there isn't a language-specific file
2944 * then fallback to the default one...
2945 */
2946
2947 if ((status = stat(filename, filestats)) != 0 && language[0] &&
2948 strncmp(con->uri, "/icons/", 7) &&
2949 strncmp(con->uri, "/ppd/", 5) &&
2950 strncmp(con->uri, "/rss/", 5) &&
2951 strncmp(con->uri, "/admin/conf/", 12) &&
2952 strncmp(con->uri, "/admin/log/", 11))
2953 {
2954 /*
2955 * Drop the country code...
2956 */
2957
2958 language[3] = '\0';
2959 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
2960
2961 if ((ptr = strchr(filename, '?')) != NULL)
2962 *ptr = '\0';
2963
2964 if ((status = stat(filename, filestats)) != 0)
2965 {
2966 /*
2967 * Drop the language prefix and try the root directory...
2968 */
2969
2970 language[0] = '\0';
2971 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
2972
2973 if ((ptr = strchr(filename, '?')) != NULL)
2974 *ptr = '\0';
2975
2976 status = stat(filename, filestats);
2977 }
2978 }
2979
2980 /*
2981 * If we're found a directory, get the index.html file instead...
2982 */
2983
2984 if (!status && S_ISDIR(filestats->st_mode))
2985 {
2986 /*
2987 * Make sure the URI ends with a slash...
2988 */
2989
2990 if (con->uri[strlen(con->uri) - 1] != '/')
2991 strlcat(con->uri, "/", sizeof(con->uri));
2992
2993 /*
2994 * Find the directory index file, trying every language...
2995 */
2996
2997 do
2998 {
2999 if (status && language[0])
3000 {
3001 /*
3002 * Try a different language subset...
3003 */
3004
3005 if (language[3])
3006 language[0] = '\0'; /* Strip country code */
3007 else
3008 language[0] = '\0'; /* Strip language */
3009 }
3010
3011 /*
3012 * Look for the index file...
3013 */
3014
3015 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3016
3017 if ((ptr = strchr(filename, '?')) != NULL)
3018 *ptr = '\0';
3019
3020 ptr = filename + strlen(filename);
3021 plen = len - (ptr - filename);
3022
3023 strlcpy(ptr, "index.html", plen);
3024 status = stat(filename, filestats);
3025
3026 #ifdef HAVE_JAVA
3027 if (status)
3028 {
3029 strlcpy(ptr, "index.class", plen);
3030 status = stat(filename, filestats);
3031 }
3032 #endif /* HAVE_JAVA */
3033
3034 #ifdef HAVE_PERL
3035 if (status)
3036 {
3037 strlcpy(ptr, "index.pl", plen);
3038 status = stat(filename, filestats);
3039 }
3040 #endif /* HAVE_PERL */
3041
3042 #ifdef HAVE_PHP
3043 if (status)
3044 {
3045 strlcpy(ptr, "index.php", plen);
3046 status = stat(filename, filestats);
3047 }
3048 #endif /* HAVE_PHP */
3049
3050 #ifdef HAVE_PYTHON
3051 if (status)
3052 {
3053 strlcpy(ptr, "index.pyc", plen);
3054 status = stat(filename, filestats);
3055 }
3056
3057 if (status)
3058 {
3059 strlcpy(ptr, "index.py", plen);
3060 status = stat(filename, filestats);
3061 }
3062 #endif /* HAVE_PYTHON */
3063
3064 }
3065 while (status && language[0]);
3066 }
3067
3068 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3069 "get_file filestats=%p, filename=%p, len=%d, "
3070 "returning \"%s\".", filestats, filename, len,
3071 status ? "(null)" : filename);
3072
3073 if (status)
3074 return (NULL);
3075 else
3076 return (filename);
3077 }
3078
3079
3080 /*
3081 * 'install_cupsd_conf()' - Install a configuration file.
3082 */
3083
3084 static http_status_t /* O - Status */
3085 install_cupsd_conf(cupsd_client_t *con) /* I - Connection */
3086 {
3087 char filename[1024]; /* Configuration filename */
3088 cups_file_t *in, /* Input file */
3089 *out; /* Output file */
3090 char buffer[16384]; /* Copy buffer */
3091 ssize_t bytes; /* Number of bytes */
3092
3093
3094 /*
3095 * Open the request file...
3096 */
3097
3098 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3099 {
3100 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to open request file \"%s\": %s",
3101 con->filename, strerror(errno));
3102 return (HTTP_STATUS_SERVER_ERROR);
3103 }
3104
3105 /*
3106 * Open the new config file...
3107 */
3108
3109 if ((out = cupsdCreateConfFile(ConfigurationFile, ConfigFilePerm)) == NULL)
3110 {
3111 cupsFileClose(in);
3112 return (HTTP_STATUS_SERVER_ERROR);
3113 }
3114
3115 cupsdLogClient(con, CUPSD_LOG_INFO, "Installing config file \"%s\"...",
3116 ConfigurationFile);
3117
3118 /*
3119 * Copy from the request to the new config file...
3120 */
3121
3122 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3123 if (cupsFileWrite(out, buffer, bytes) < bytes)
3124 {
3125 cupsdLogClient(con, CUPSD_LOG_ERROR,
3126 "Unable to copy to config file \"%s\": %s",
3127 ConfigurationFile, strerror(errno));
3128
3129 cupsFileClose(in);
3130 cupsFileClose(out);
3131
3132 snprintf(filename, sizeof(filename), "%s.N", ConfigurationFile);
3133 cupsdUnlinkOrRemoveFile(filename);
3134
3135 return (HTTP_STATUS_SERVER_ERROR);
3136 }
3137
3138 /*
3139 * Close the files...
3140 */
3141
3142 cupsFileClose(in);
3143
3144 if (cupsdCloseCreatedConfFile(out, ConfigurationFile))
3145 return (HTTP_STATUS_SERVER_ERROR);
3146
3147 /*
3148 * Remove the request file...
3149 */
3150
3151 cupsdUnlinkOrRemoveFile(con->filename);
3152 cupsdClearString(&con->filename);
3153
3154 /*
3155 * Set the NeedReload flag...
3156 */
3157
3158 NeedReload = RELOAD_CUPSD;
3159 ReloadTime = time(NULL);
3160
3161 /*
3162 * Return that the file was created successfully...
3163 */
3164
3165 return (HTTP_STATUS_CREATED);
3166 }
3167
3168
3169 /*
3170 * 'is_cgi()' - Is the resource a CGI script/program?
3171 */
3172
3173 static int /* O - 1 = CGI, 0 = file */
3174 is_cgi(cupsd_client_t *con, /* I - Client connection */
3175 const char *filename, /* I - Real filename */
3176 struct stat *filestats, /* I - File information */
3177 mime_type_t *type) /* I - MIME type */
3178 {
3179 const char *options; /* Options on URL */
3180
3181
3182 /*
3183 * Get the options, if any...
3184 */
3185
3186 if ((options = strchr(con->uri, '?')) != NULL)
3187 {
3188 options ++;
3189 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3190 }
3191
3192 /*
3193 * Check for known types...
3194 */
3195
3196 if (!type || _cups_strcasecmp(type->super, "application"))
3197 {
3198 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3199 "is_cgi filename=\"%s\", filestats=%p, "
3200 "type=%s/%s, returning 0", filename,
3201 filestats, type ? type->super : "unknown",
3202 type ? type->type : "unknown");
3203 return (0);
3204 }
3205
3206 if (!_cups_strcasecmp(type->type, "x-httpd-cgi") &&
3207 (filestats->st_mode & 0111))
3208 {
3209 /*
3210 * "application/x-httpd-cgi" is a CGI script.
3211 */
3212
3213 cupsdSetString(&con->command, filename);
3214
3215 if (options)
3216 cupsdSetStringf(&con->options, " %s", options);
3217
3218 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3219 "is_cgi filename=\"%s\", filestats=%p, "
3220 "type=%s/%s, returning 1", filename,
3221 filestats, type->super, type->type);
3222 return (1);
3223 }
3224 #ifdef HAVE_JAVA
3225 else if (!_cups_strcasecmp(type->type, "x-httpd-java"))
3226 {
3227 /*
3228 * "application/x-httpd-java" is a Java servlet.
3229 */
3230
3231 cupsdSetString(&con->command, CUPS_JAVA);
3232
3233 if (options)
3234 cupsdSetStringf(&con->options, " %s %s", filename, options);
3235 else
3236 cupsdSetStringf(&con->options, " %s", filename);
3237
3238 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3239 "is_cgi filename=\"%s\", filestats=%p, "
3240 "type=%s/%s, returning 1", filename,
3241 filestats, type->super, type->type);
3242 return (1);
3243 }
3244 #endif /* HAVE_JAVA */
3245 #ifdef HAVE_PERL
3246 else if (!_cups_strcasecmp(type->type, "x-httpd-perl"))
3247 {
3248 /*
3249 * "application/x-httpd-perl" is a Perl page.
3250 */
3251
3252 cupsdSetString(&con->command, CUPS_PERL);
3253
3254 if (options)
3255 cupsdSetStringf(&con->options, " %s %s", filename, options);
3256 else
3257 cupsdSetStringf(&con->options, " %s", filename);
3258
3259 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3260 "is_cgi filename=\"%s\", filestats=%p, "
3261 "type=%s/%s, returning 1", filename,
3262 filestats, type->super, type->type);
3263 return (1);
3264 }
3265 #endif /* HAVE_PERL */
3266 #ifdef HAVE_PHP
3267 else if (!_cups_strcasecmp(type->type, "x-httpd-php"))
3268 {
3269 /*
3270 * "application/x-httpd-php" is a PHP page.
3271 */
3272
3273 cupsdSetString(&con->command, CUPS_PHP);
3274
3275 if (options)
3276 cupsdSetStringf(&con->options, " %s %s", filename, options);
3277 else
3278 cupsdSetStringf(&con->options, " %s", filename);
3279
3280 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3281 "is_cgi filename=\"%s\", filestats=%p, "
3282 "type=%s/%s, returning 1", filename,
3283 filestats, type->super, type->type);
3284 return (1);
3285 }
3286 #endif /* HAVE_PHP */
3287 #ifdef HAVE_PYTHON
3288 else if (!_cups_strcasecmp(type->type, "x-httpd-python"))
3289 {
3290 /*
3291 * "application/x-httpd-python" is a Python page.
3292 */
3293
3294 cupsdSetString(&con->command, CUPS_PYTHON);
3295
3296 if (options)
3297 cupsdSetStringf(&con->options, " %s %s", filename, options);
3298 else
3299 cupsdSetStringf(&con->options, " %s", filename);
3300
3301 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3302 "is_cgi filename=\"%s\", filestats=%p, "
3303 "type=%s/%s, returning 1", filename,
3304 filestats, type->super, type->type);
3305 return (1);
3306 }
3307 #endif /* HAVE_PYTHON */
3308
3309 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3310 "is_cgi filename=\"%s\", filestats=%p, "
3311 "type=%s/%s, returning 0", filename,
3312 filestats, type->super, type->type);
3313 return (0);
3314 }
3315
3316
3317 /*
3318 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3319 */
3320
3321 static int /* O - 0 if relative, 1 if absolute */
3322 is_path_absolute(const char *path) /* I - Input path */
3323 {
3324 /*
3325 * Check for a leading slash...
3326 */
3327
3328 if (path[0] != '/')
3329 return (0);
3330
3331 /*
3332 * Check for "/.." in the path...
3333 */
3334
3335 while ((path = strstr(path, "/..")) != NULL)
3336 {
3337 if (!path[3] || path[3] == '/')
3338 return (0);
3339
3340 path ++;
3341 }
3342
3343 /*
3344 * If we haven't found any relative paths, return 1 indicating an
3345 * absolute path...
3346 */
3347
3348 return (1);
3349 }
3350
3351
3352 /*
3353 * 'pipe_command()' - Pipe the output of a command to the remote client.
3354 */
3355
3356 static int /* O - Process ID */
3357 pipe_command(cupsd_client_t *con, /* I - Client connection */
3358 int infile, /* I - Standard input for command */
3359 int *outfile, /* O - Standard output for command */
3360 char *command, /* I - Command to run */
3361 char *options, /* I - Options for command */
3362 int root) /* I - Run as root? */
3363 {
3364 int i; /* Looping var */
3365 int pid; /* Process ID */
3366 char *commptr, /* Command string pointer */
3367 commch; /* Command string character */
3368 char *uriptr; /* URI string pointer */
3369 int fds[2]; /* Pipe FDs */
3370 int argc; /* Number of arguments */
3371 int envc; /* Number of environment variables */
3372 char argbuf[10240], /* Argument buffer */
3373 *argv[100], /* Argument strings */
3374 *envp[MAX_ENV + 20]; /* Environment variables */
3375 char auth_type[256], /* AUTH_TYPE environment variable */
3376 content_length[1024], /* CONTENT_LENGTH environment variable */
3377 content_type[1024], /* CONTENT_TYPE environment variable */
3378 http_cookie[32768], /* HTTP_COOKIE environment variable */
3379 http_referer[1024], /* HTTP_REFERER environment variable */
3380 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
3381 lang[1024], /* LANG environment variable */
3382 path_info[1024], /* PATH_INFO environment variable */
3383 remote_addr[1024], /* REMOTE_ADDR environment variable */
3384 remote_host[1024], /* REMOTE_HOST environment variable */
3385 remote_user[1024], /* REMOTE_USER environment variable */
3386 script_filename[1024], /* SCRIPT_FILENAME environment variable */
3387 script_name[1024], /* SCRIPT_NAME environment variable */
3388 server_name[1024], /* SERVER_NAME environment variable */
3389 server_port[1024]; /* SERVER_PORT environment variable */
3390 ipp_attribute_t *attr; /* attributes-natural-language attribute */
3391
3392
3393 /*
3394 * Parse a copy of the options string, which is of the form:
3395 *
3396 * argument+argument+argument
3397 * ?argument+argument+argument
3398 * param=value&param=value
3399 * ?param=value&param=value
3400 * /name?argument+argument+argument
3401 * /name?param=value&param=value
3402 *
3403 * If the string contains an "=" character after the initial name,
3404 * then we treat it as a HTTP GET form request and make a copy of
3405 * the remaining string for the environment variable.
3406 *
3407 * The string is always parsed out as command-line arguments, to
3408 * be consistent with Apache...
3409 */
3410
3411 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3412 "pipe_command infile=%d, outfile=%p, "
3413 "command=\"%s\", options=\"%s\", root=%d",
3414 infile, outfile, command,
3415 options ? options : "(null)", root);
3416
3417 argv[0] = command;
3418
3419 if (options)
3420 {
3421 commptr = options;
3422 if (*commptr == ' ')
3423 commptr ++;
3424 strlcpy(argbuf, commptr, sizeof(argbuf));
3425 }
3426 else
3427 argbuf[0] = '\0';
3428
3429 if (argbuf[0] == '/')
3430 {
3431 /*
3432 * Found some trailing path information, set PATH_INFO...
3433 */
3434
3435 if ((commptr = strchr(argbuf, '?')) == NULL)
3436 commptr = argbuf + strlen(argbuf);
3437
3438 commch = *commptr;
3439 *commptr = '\0';
3440 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
3441 *commptr = commch;
3442 }
3443 else
3444 {
3445 commptr = argbuf;
3446 path_info[0] = '\0';
3447
3448 if (*commptr == ' ')
3449 commptr ++;
3450 }
3451
3452 if (*commptr == '?' && con->operation == HTTP_STATE_GET && !con->query_string)
3453 {
3454 commptr ++;
3455 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
3456 }
3457
3458 argc = 1;
3459
3460 if (*commptr)
3461 {
3462 argv[argc ++] = commptr;
3463
3464 for (; *commptr && argc < 99; commptr ++)
3465 {
3466 /*
3467 * Break arguments whenever we see a + or space...
3468 */
3469
3470 if (*commptr == ' ' || *commptr == '+')
3471 {
3472 while (*commptr == ' ' || *commptr == '+')
3473 *commptr++ = '\0';
3474
3475 /*
3476 * If we don't have a blank string, save it as another argument...
3477 */
3478
3479 if (*commptr)
3480 {
3481 argv[argc] = commptr;
3482 argc ++;
3483 }
3484 else
3485 break;
3486 }
3487 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
3488 isxdigit(commptr[2] & 255))
3489 {
3490 /*
3491 * Convert the %xx notation to the individual character.
3492 */
3493
3494 if (commptr[1] >= '0' && commptr[1] <= '9')
3495 *commptr = (commptr[1] - '0') << 4;
3496 else
3497 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
3498
3499 if (commptr[2] >= '0' && commptr[2] <= '9')
3500 *commptr |= commptr[2] - '0';
3501 else
3502 *commptr |= tolower(commptr[2]) - 'a' + 10;
3503
3504 _cups_strcpy(commptr + 1, commptr + 3);
3505
3506 /*
3507 * Check for a %00 and break if that is the case...
3508 */
3509
3510 if (!*commptr)
3511 break;
3512 }
3513 }
3514 }
3515
3516 argv[argc] = NULL;
3517
3518 /*
3519 * Setup the environment variables as needed...
3520 */
3521
3522 if (con->username[0])
3523 {
3524 snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
3525 httpGetField(con->http, HTTP_FIELD_AUTHORIZATION));
3526
3527 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
3528 *uriptr = '\0';
3529 }
3530 else
3531 auth_type[0] = '\0';
3532
3533 if (con->request &&
3534 (attr = ippFindAttribute(con->request, "attributes-natural-language",
3535 IPP_TAG_LANGUAGE)) != NULL)
3536 {
3537 switch (strlen(attr->values[0].string.text))
3538 {
3539 default :
3540 /*
3541 * This is an unknown or badly formatted language code; use
3542 * the POSIX locale...
3543 */
3544
3545 strlcpy(lang, "LANG=C", sizeof(lang));
3546 break;
3547
3548 case 2 :
3549 /*
3550 * Just the language code (ll)...
3551 */
3552
3553 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
3554 attr->values[0].string.text);
3555 break;
3556
3557 case 5 :
3558 /*
3559 * Language and country code (ll-cc)...
3560 */
3561
3562 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
3563 attr->values[0].string.text[0],
3564 attr->values[0].string.text[1],
3565 toupper(attr->values[0].string.text[3] & 255),
3566 toupper(attr->values[0].string.text[4] & 255));
3567 break;
3568 }
3569 }
3570 else if (con->language)
3571 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
3572 else
3573 strlcpy(lang, "LANG=C", sizeof(lang));
3574
3575 strlcpy(remote_addr, "REMOTE_ADDR=", sizeof(remote_addr));
3576 httpAddrString(httpGetAddress(con->http), remote_addr + 12,
3577 sizeof(remote_addr) - 12);
3578
3579 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
3580 httpGetHostname(con->http, NULL, 0));
3581
3582 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
3583 if ((uriptr = strchr(script_name, '?')) != NULL)
3584 *uriptr = '\0';
3585
3586 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
3587 DocumentRoot, script_name + 12);
3588
3589 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
3590
3591 if (httpGetField(con->http, HTTP_FIELD_HOST)[0])
3592 {
3593 char *nameptr; /* Pointer to ":port" */
3594
3595 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3596 httpGetField(con->http, HTTP_FIELD_HOST));
3597 if ((nameptr = strrchr(server_name, ':')) != NULL && !strchr(nameptr, ']'))
3598 *nameptr = '\0'; /* Strip trailing ":port" */
3599 }
3600 else
3601 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3602 con->servername);
3603
3604 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
3605
3606 if (auth_type[0])
3607 envp[envc ++] = auth_type;
3608
3609 envp[envc ++] = lang;
3610 envp[envc ++] = "REDIRECT_STATUS=1";
3611 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
3612 envp[envc ++] = server_name;
3613 envp[envc ++] = server_port;
3614 envp[envc ++] = remote_addr;
3615 envp[envc ++] = remote_host;
3616 envp[envc ++] = script_name;
3617 envp[envc ++] = script_filename;
3618
3619 if (path_info[0])
3620 envp[envc ++] = path_info;
3621
3622 if (con->username[0])
3623 {
3624 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
3625
3626 envp[envc ++] = remote_user;
3627 }
3628
3629 if (httpGetVersion(con->http) == HTTP_VERSION_1_1)
3630 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
3631 else if (httpGetVersion(con->http) == HTTP_VERSION_1_0)
3632 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
3633 else
3634 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
3635
3636 if (httpGetCookie(con->http))
3637 {
3638 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
3639 httpGetCookie(con->http));
3640 envp[envc ++] = http_cookie;
3641 }
3642
3643 if (httpGetField(con->http, HTTP_FIELD_USER_AGENT)[0])
3644 {
3645 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
3646 httpGetField(con->http, HTTP_FIELD_USER_AGENT));
3647 envp[envc ++] = http_user_agent;
3648 }
3649
3650 if (httpGetField(con->http, HTTP_FIELD_REFERER)[0])
3651 {
3652 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
3653 httpGetField(con->http, HTTP_FIELD_REFERER));
3654 envp[envc ++] = http_referer;
3655 }
3656
3657 if (con->operation == HTTP_STATE_GET)
3658 {
3659 envp[envc ++] = "REQUEST_METHOD=GET";
3660
3661 if (con->query_string)
3662 {
3663 /*
3664 * Add GET form variables after ?...
3665 */
3666
3667 envp[envc ++] = con->query_string;
3668 }
3669 else
3670 envp[envc ++] = "QUERY_STRING=";
3671 }
3672 else
3673 {
3674 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
3675 CUPS_LLCAST con->bytes);
3676 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
3677 httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE));
3678
3679 envp[envc ++] = "REQUEST_METHOD=POST";
3680 envp[envc ++] = content_length;
3681 envp[envc ++] = content_type;
3682 }
3683
3684 /*
3685 * Tell the CGI if we are using encryption...
3686 */
3687
3688 if (httpIsEncrypted(con->http))
3689 envp[envc ++] = "HTTPS=ON";
3690
3691 /*
3692 * Terminate the environment array...
3693 */
3694
3695 envp[envc] = NULL;
3696
3697 if (LogLevel >= CUPSD_LOG_DEBUG)
3698 {
3699 for (i = 0; i < argc; i ++)
3700 cupsdLogMessage(CUPSD_LOG_DEBUG,
3701 "[CGI] argv[%d] = \"%s\"", i, argv[i]);
3702 for (i = 0; i < envc; i ++)
3703 cupsdLogMessage(CUPSD_LOG_DEBUG,
3704 "[CGI] envp[%d] = \"%s\"", i, envp[i]);
3705 }
3706
3707 /*
3708 * Create a pipe for the output...
3709 */
3710
3711 if (cupsdOpenPipe(fds))
3712 {
3713 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
3714 argv[0], strerror(errno));
3715 return (0);
3716 }
3717
3718 /*
3719 * Then execute the command...
3720 */
3721
3722 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
3723 -1, -1, root, DefaultProfile, NULL, &pid) < 0)
3724 {
3725 /*
3726 * Error - can't fork!
3727 */
3728
3729 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
3730 strerror(errno));
3731
3732 cupsdClosePipe(fds);
3733 pid = 0;
3734 }
3735 else
3736 {
3737 /*
3738 * Fork successful - return the PID...
3739 */
3740
3741 if (con->username[0])
3742 cupsdAddCert(pid, con->username, con->type);
3743
3744 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
3745
3746 *outfile = fds[0];
3747 close(fds[1]);
3748 }
3749
3750 return (pid);
3751 }
3752
3753
3754 /*
3755 * 'valid_host()' - Is the Host: field valid?
3756 */
3757
3758 static int /* O - 1 if valid, 0 if not */
3759 valid_host(cupsd_client_t *con) /* I - Client connection */
3760 {
3761 cupsd_alias_t *a; /* Current alias */
3762 cupsd_netif_t *netif; /* Current network interface */
3763 const char *end; /* End character */
3764 char *ptr; /* Pointer into host value */
3765
3766
3767 /*
3768 * Copy the Host: header for later use...
3769 */
3770
3771 strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
3772 sizeof(con->clientname));
3773 if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
3774 {
3775 *ptr++ = '\0';
3776 con->clientport = atoi(ptr);
3777 }
3778 else
3779 con->clientport = con->serverport;
3780
3781 /*
3782 * Then validate...
3783 */
3784
3785 if (httpAddrLocalhost(httpGetAddress(con->http)))
3786 {
3787 /*
3788 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3789 * addresses when accessing CUPS via the loopback interface...
3790 */
3791
3792 return (!_cups_strcasecmp(con->clientname, "localhost") ||
3793 !_cups_strcasecmp(con->clientname, "localhost.") ||
3794 #ifdef __linux
3795 !_cups_strcasecmp(con->clientname, "localhost.localdomain") ||
3796 #endif /* __linux */
3797 !strcmp(con->clientname, "127.0.0.1") ||
3798 !strcmp(con->clientname, "[::1]"));
3799 }
3800
3801 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3802 /*
3803 * Check if the hostname is something.local (Bonjour); if so, allow it.
3804 */
3805
3806 if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
3807 !end[1])
3808 {
3809 /*
3810 * "." on end, work back to second-to-last "."...
3811 */
3812
3813 for (end --; end > con->clientname && *end != '.'; end --);
3814 }
3815
3816 if (end && (!_cups_strcasecmp(end, ".local") ||
3817 !_cups_strcasecmp(end, ".local.")))
3818 return (1);
3819 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3820
3821 /*
3822 * Check if the hostname is an IP address...
3823 */
3824
3825 if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
3826 {
3827 /*
3828 * Possible IPv4/IPv6 address...
3829 */
3830
3831 http_addrlist_t *addrlist; /* List of addresses */
3832
3833
3834 if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
3835 {
3836 /*
3837 * Good IPv4/IPv6 address...
3838 */
3839
3840 httpAddrFreeList(addrlist);
3841 return (1);
3842 }
3843 }
3844
3845 /*
3846 * Check for (alias) name matches...
3847 */
3848
3849 for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
3850 a;
3851 a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
3852 {
3853 /*
3854 * "ServerAlias *" allows all host values through...
3855 */
3856
3857 if (!strcmp(a->name, "*"))
3858 return (1);
3859
3860 if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
3861 {
3862 /*
3863 * Prefix matches; check the character at the end - it must be "." or nul.
3864 */
3865
3866 end = con->clientname + a->namelen;
3867
3868 if (!*end || (*end == '.' && !end[1]))
3869 return (1);
3870 }
3871 }
3872
3873 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3874 for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
3875 a;
3876 a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
3877 {
3878 /*
3879 * "ServerAlias *" allows all host values through...
3880 */
3881
3882 if (!strcmp(a->name, "*"))
3883 return (1);
3884
3885 if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
3886 {
3887 /*
3888 * Prefix matches; check the character at the end - it must be "." or nul.
3889 */
3890
3891 end = con->clientname + a->namelen;
3892
3893 if (!*end || (*end == '.' && !end[1]))
3894 return (1);
3895 }
3896 }
3897 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3898
3899 /*
3900 * Check for interface hostname matches...
3901 */
3902
3903 for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
3904 netif;
3905 netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
3906 {
3907 if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
3908 {
3909 /*
3910 * Prefix matches; check the character at the end - it must be "." or nul.
3911 */
3912
3913 end = con->clientname + netif->hostlen;
3914
3915 if (!*end || (*end == '.' && !end[1]))
3916 return (1);
3917 }
3918 }
3919
3920 return (0);
3921 }
3922
3923
3924 /*
3925 * 'write_file()' - Send a file via HTTP.
3926 */
3927
3928 static int /* O - 0 on failure, 1 on success */
3929 write_file(cupsd_client_t *con, /* I - Client connection */
3930 http_status_t code, /* I - HTTP status */
3931 char *filename, /* I - Filename */
3932 char *type, /* I - File type */
3933 struct stat *filestats) /* O - File information */
3934 {
3935 con->file = open(filename, O_RDONLY);
3936
3937 cupsdLogClient(con, CUPSD_LOG_DEBUG2,
3938 "write_file code=%d, filename=\"%s\" (%d), "
3939 "type=\"%s\", filestats=%p",
3940 code, filename, con->file, type ? type : "(null)", filestats);
3941
3942 if (con->file < 0)
3943 return (0);
3944
3945 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
3946
3947 con->pipe_pid = 0;
3948
3949 httpClearFields(con->http);
3950
3951 httpSetLength(con->http, filestats->st_size);
3952
3953 httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
3954 httpGetDateString(filestats->st_mtime));
3955
3956 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
3957 return (0);
3958
3959 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
3960 (cupsd_selfunc_t)cupsdWriteClient, con);
3961
3962 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending file.");
3963
3964 return (1);
3965 }
3966
3967
3968 /*
3969 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3970 */
3971
3972 static void
3973 write_pipe(cupsd_client_t *con) /* I - Client connection */
3974 {
3975 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_pipe CGI output on fd %d",
3976 con->file);
3977
3978 con->file_ready = 1;
3979
3980 cupsdRemoveSelect(con->file);
3981 cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
3982
3983 cupsdLogClient(con, CUPSD_LOG_DEBUG, "CGI data ready to be sent.");
3984 }
3985
3986
3987 /*
3988 * End of "$Id$".
3989 */