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