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