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