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