]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/client.c
Merge changes from CUPS 1.7svn-r10791.
[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 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2584 #endif /* HAVE_GSSAPI */
2585
2586 if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
2587 !_cups_strcasecmp(con->http.hostname, "localhost"))
2588 {
2589 /*
2590 * Add a "trc" (try root certification) parameter for local non-Kerberos
2591 * requests when the request requires system group membership - then the
2592 * client knows the root certificate can/should be used.
2593 *
2594 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2595 * parameter as needed...
2596 */
2597
2598 char *name, /* Current user name */
2599 *auth_key; /* Auth key buffer */
2600 size_t auth_size; /* Size of remaining buffer */
2601
2602 auth_key = auth_str + strlen(auth_str);
2603 auth_size = sizeof(auth_str) - (auth_key - auth_str);
2604
2605 for (name = (char *)cupsArrayFirst(con->best->names);
2606 name;
2607 name = (char *)cupsArrayNext(con->best->names))
2608 {
2609 #ifdef HAVE_AUTHORIZATION_H
2610 if (!_cups_strncasecmp(name, "@AUTHKEY(", 9))
2611 {
2612 snprintf(auth_key, auth_size, ", authkey=\"%s\"", name + 9);
2613 /* end parenthesis is stripped in conf.c */
2614 break;
2615 }
2616 else
2617 #endif /* HAVE_AUTHORIZATION_H */
2618 if (!_cups_strcasecmp(name, "@SYSTEM"))
2619 {
2620 #ifdef HAVE_AUTHORIZATION_H
2621 if (SystemGroupAuthKey)
2622 snprintf(auth_key, auth_size,
2623 ", authkey=\"%s\"",
2624 SystemGroupAuthKey);
2625 else
2626 #else
2627 strlcpy(auth_key, ", trc=\"y\"", auth_size);
2628 #endif /* HAVE_AUTHORIZATION_H */
2629 break;
2630 }
2631 }
2632 }
2633
2634 if (auth_str[0])
2635 {
2636 cupsdLogMessage(CUPSD_LOG_DEBUG,
2637 "[Client %d] WWW-Authenticate: %s", con->http.fd,
2638 auth_str);
2639
2640 if (httpPrintf(HTTP(con), "WWW-Authenticate: %s\r\n", auth_str) < 0)
2641 return (0);
2642 }
2643 }
2644
2645 if (con->language && strcmp(con->language->language, "C"))
2646 {
2647 if (httpPrintf(HTTP(con), "Content-Language: %s\r\n",
2648 con->language->language) < 0)
2649 return (0);
2650 }
2651
2652 if (type)
2653 {
2654 if (!strcmp(type, "text/html"))
2655 {
2656 if (httpPrintf(HTTP(con),
2657 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2658 return (0);
2659 }
2660 else if (httpPrintf(HTTP(con), "Content-Type: %s\r\n", type) < 0)
2661 return (0);
2662 }
2663
2664 return (1);
2665 }
2666
2667
2668 /*
2669 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2670 */
2671
2672 void
2673 cupsdUpdateCGI(void)
2674 {
2675 char *ptr, /* Pointer to end of line in buffer */
2676 message[1024]; /* Pointer to message text */
2677 int loglevel; /* Log level for message */
2678
2679
2680 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2681 message, sizeof(message))) != NULL)
2682 {
2683 if (loglevel == CUPSD_LOG_INFO)
2684 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
2685
2686 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2687 break;
2688 }
2689
2690 if (ptr == NULL && !CGIStatusBuffer->bufused)
2691 {
2692 /*
2693 * Fatal error on pipe - should never happen!
2694 */
2695
2696 cupsdLogMessage(CUPSD_LOG_CRIT,
2697 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2698 strerror(errno));
2699 }
2700 }
2701
2702
2703 /*
2704 * 'cupsdWriteClient()' - Write data to a client as needed.
2705 */
2706
2707 void
2708 cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2709 {
2710 int bytes, /* Number of bytes written */
2711 field_col; /* Current column */
2712 char *bufptr, /* Pointer into buffer */
2713 *bufend; /* Pointer to end of buffer */
2714 ipp_state_t ipp_state; /* IPP state value */
2715
2716
2717 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2718 "[Client %d] cupsdWriteClient "
2719 "error=%d, "
2720 "used=%d, "
2721 "state=%s, "
2722 "data_encoding=HTTP_ENCODE_%s, "
2723 "data_remaining=" CUPS_LLFMT ", "
2724 "response=%p(%s), "
2725 "pipe_pid=%d, "
2726 "file=%d",
2727 con->http.fd, con->http.error, con->http.used,
2728 http_states[con->http.state + 1],
2729 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
2730 "CHUNKED" : "LENGTH",
2731 CUPS_LLCAST con->http.data_remaining,
2732 con->response,
2733 con->response ? ipp_states[con->response->state] : "",
2734 con->pipe_pid, con->file);
2735
2736 if (con->http.state != HTTP_GET_SEND &&
2737 con->http.state != HTTP_POST_SEND)
2738 {
2739 /*
2740 * If we get called in the wrong state, then something went wrong with the
2741 * connection and we need to shut it down...
2742 */
2743
2744 cupsdLogMessage(CUPSD_LOG_DEBUG,
2745 "[Client %d] Closing on unexpected HTTP state %s.",
2746 con->http.fd, http_states[con->http.state + 1]);
2747 cupsdCloseClient(con);
2748 return;
2749 }
2750
2751 if (con->pipe_pid)
2752 {
2753 /*
2754 * Make sure we select on the CGI output...
2755 */
2756
2757 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2758
2759 if (!con->file_ready)
2760 {
2761 /*
2762 * Try again later when there is CGI output available...
2763 */
2764
2765 cupsdRemoveSelect(con->http.fd);
2766 return;
2767 }
2768
2769 con->file_ready = 0;
2770 }
2771
2772 if (con->response && con->response->state != IPP_DATA)
2773 {
2774 ipp_state = ippWrite(HTTP(con), con->response);
2775 bytes = ipp_state != IPP_ERROR &&
2776 (con->file >= 0 || ipp_state != IPP_DATA);
2777 }
2778 else if ((bytes = read(con->file, con->header + con->header_used,
2779 sizeof(con->header) - con->header_used)) > 0)
2780 {
2781 con->header_used += bytes;
2782
2783 if (con->pipe_pid && !con->got_fields)
2784 {
2785 /*
2786 * Inspect the data for Content-Type and other fields.
2787 */
2788
2789 for (bufptr = con->header, bufend = con->header + con->header_used,
2790 field_col = 0;
2791 !con->got_fields && bufptr < bufend;
2792 bufptr ++)
2793 {
2794 if (*bufptr == '\n')
2795 {
2796 /*
2797 * Send line to client...
2798 */
2799
2800 if (bufptr > con->header && bufptr[-1] == '\r')
2801 bufptr[-1] = '\0';
2802 *bufptr++ = '\0';
2803
2804 cupsdLogMessage(CUPSD_LOG_DEBUG, "Script header: %s", con->header);
2805
2806 if (!con->sent_header)
2807 {
2808 /*
2809 * Handle redirection and CGI status codes...
2810 */
2811
2812 if (!_cups_strncasecmp(con->header, "Location:", 9))
2813 {
2814 if (!cupsdSendHeader(con, HTTP_SEE_OTHER, NULL, CUPSD_AUTH_NONE))
2815 {
2816 cupsdCloseClient(con);
2817 return;
2818 }
2819
2820 con->sent_header = 2;
2821
2822 if (httpPrintf(HTTP(con), "Content-Length: 0\r\n") < 0)
2823 return;
2824 }
2825 else if (!_cups_strncasecmp(con->header, "Status:", 7))
2826 {
2827 cupsdSendError(con, (http_status_t)atoi(con->header + 7),
2828 CUPSD_AUTH_NONE);
2829 con->sent_header = 2;
2830 }
2831 else
2832 {
2833 if (!cupsdSendHeader(con, HTTP_OK, NULL, CUPSD_AUTH_NONE))
2834 {
2835 cupsdCloseClient(con);
2836 return;
2837 }
2838
2839 con->sent_header = 1;
2840
2841 if (con->http.version == HTTP_1_1)
2842 {
2843 if (httpPrintf(HTTP(con), "Transfer-Encoding: chunked\r\n") < 0)
2844 return;
2845 }
2846 }
2847 }
2848
2849 if (_cups_strncasecmp(con->header, "Status:", 7))
2850 httpPrintf(HTTP(con), "%s\r\n", con->header);
2851
2852 /*
2853 * Update buffer...
2854 */
2855
2856 con->header_used -= bufptr - con->header;
2857
2858 if (con->header_used > 0)
2859 memmove(con->header, bufptr, con->header_used);
2860
2861 bufptr = con->header - 1;
2862
2863 /*
2864 * See if the line was empty...
2865 */
2866
2867 if (field_col == 0)
2868 {
2869 con->got_fields = 1;
2870
2871 if (cupsdFlushHeader(con) < 0)
2872 {
2873 cupsdCloseClient(con);
2874 return;
2875 }
2876
2877 if (con->http.version == HTTP_1_1)
2878 con->http.data_encoding = HTTP_ENCODE_CHUNKED;
2879 }
2880 else
2881 field_col = 0;
2882 }
2883 else if (*bufptr != '\r')
2884 field_col ++;
2885 }
2886
2887 if (!con->got_fields)
2888 {
2889 con->http.activity = time(NULL);
2890 return;
2891 }
2892 }
2893
2894 if (con->header_used > 0)
2895 {
2896 if (httpWrite2(HTTP(con), con->header, con->header_used) < 0)
2897 {
2898 cupsdLogMessage(CUPSD_LOG_DEBUG,
2899 "[Client %d] Closing for error %d (%s)",
2900 con->http.fd, con->http.error,
2901 strerror(con->http.error));
2902 cupsdCloseClient(con);
2903 return;
2904 }
2905
2906 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED)
2907 httpFlushWrite(HTTP(con));
2908
2909 con->bytes += con->header_used;
2910
2911 if (con->http.state == HTTP_WAITING)
2912 bytes = 0;
2913 else
2914 bytes = con->header_used;
2915
2916 con->header_used = 0;
2917 }
2918 }
2919
2920 if (bytes <= 0 ||
2921 (con->http.state != HTTP_GET_SEND && con->http.state != HTTP_POST_SEND))
2922 {
2923 if (!con->sent_header && con->pipe_pid)
2924 cupsdSendError(con, HTTP_SERVER_ERROR, CUPSD_AUTH_NONE);
2925 else
2926 {
2927 cupsdLogRequest(con, HTTP_OK);
2928
2929 httpFlushWrite(HTTP(con));
2930
2931 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED && con->sent_header == 1)
2932 {
2933 if (httpWrite2(HTTP(con), "", 0) < 0)
2934 {
2935 cupsdLogMessage(CUPSD_LOG_DEBUG,
2936 "[Client %d] Closing for error %d (%s)",
2937 con->http.fd, con->http.error,
2938 strerror(con->http.error));
2939 cupsdCloseClient(con);
2940 return;
2941 }
2942 }
2943 }
2944
2945 con->http.state = HTTP_WAITING;
2946
2947 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
2948
2949 if (con->file >= 0)
2950 {
2951 cupsdRemoveSelect(con->file);
2952
2953 if (con->pipe_pid)
2954 cupsdEndProcess(con->pipe_pid, 0);
2955
2956 close(con->file);
2957 con->file = -1;
2958 con->pipe_pid = 0;
2959 }
2960
2961 if (con->filename)
2962 {
2963 unlink(con->filename);
2964 cupsdClearString(&con->filename);
2965 }
2966
2967 if (con->request)
2968 {
2969 ippDelete(con->request);
2970 con->request = NULL;
2971 }
2972
2973 if (con->response)
2974 {
2975 ippDelete(con->response);
2976 con->response = NULL;
2977 }
2978
2979 cupsdClearString(&con->command);
2980 cupsdClearString(&con->options);
2981 cupsdClearString(&con->query_string);
2982
2983 if (!con->http.keep_alive)
2984 {
2985 cupsdLogMessage(CUPSD_LOG_DEBUG,
2986 "[Client %d] Closing because Keep-Alive disabled.",
2987 con->http.fd);
2988 cupsdCloseClient(con);
2989 return;
2990 }
2991 else
2992 {
2993 cupsArrayRemove(ActiveClients, con);
2994 cupsdSetBusyState();
2995 }
2996 }
2997
2998 con->http.activity = time(NULL);
2999 }
3000
3001
3002 /*
3003 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3004 */
3005
3006 static int /* O - 1 if modified since */
3007 check_if_modified(
3008 cupsd_client_t *con, /* I - Client connection */
3009 struct stat *filestats) /* I - File information */
3010 {
3011 char *ptr; /* Pointer into field */
3012 time_t date; /* Time/date value */
3013 off_t size; /* Size/length value */
3014
3015
3016 size = 0;
3017 date = 0;
3018 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
3019
3020 if (*ptr == '\0')
3021 return (1);
3022
3023 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3024 "[Client %d] check_if_modified "
3025 "filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"",
3026 con->http.fd, filestats, CUPS_LLCAST filestats->st_size,
3027 (int)filestats->st_mtime, ptr);
3028
3029 while (*ptr != '\0')
3030 {
3031 while (isspace(*ptr) || *ptr == ';')
3032 ptr ++;
3033
3034 if (_cups_strncasecmp(ptr, "length=", 7) == 0)
3035 {
3036 ptr += 7;
3037 size = strtoll(ptr, NULL, 10);
3038
3039 while (isdigit(*ptr))
3040 ptr ++;
3041 }
3042 else if (isalpha(*ptr))
3043 {
3044 date = httpGetDateTime(ptr);
3045 while (*ptr != '\0' && *ptr != ';')
3046 ptr ++;
3047 }
3048 else
3049 ptr ++;
3050 }
3051
3052 return ((size != filestats->st_size && size != 0) ||
3053 (date < filestats->st_mtime && date != 0) ||
3054 (size == 0 && date == 0));
3055 }
3056
3057
3058 /*
3059 * 'compare_clients()' - Compare two client connections.
3060 */
3061
3062 static int /* O - Result of comparison */
3063 compare_clients(cupsd_client_t *a, /* I - First client */
3064 cupsd_client_t *b, /* I - Second client */
3065 void *data) /* I - User data (not used) */
3066 {
3067 (void)data;
3068
3069 if (a == b)
3070 return (0);
3071 else if (a < b)
3072 return (-1);
3073 else
3074 return (1);
3075 }
3076
3077
3078 /*
3079 * 'data_ready()' - Check whether data is available from a client.
3080 */
3081
3082 static int /* O - 1 if data is ready, 0 otherwise */
3083 data_ready(cupsd_client_t *con) /* I - Client */
3084 {
3085 if (con->http.used > 0)
3086 return (1);
3087 #ifdef HAVE_SSL
3088 else if (con->http.tls)
3089 {
3090 # ifdef HAVE_LIBSSL
3091 if (SSL_pending((SSL *)(con->http.tls)))
3092 return (1);
3093 # elif defined(HAVE_GNUTLS)
3094 if (gnutls_record_check_pending(con->http.tls))
3095 return (1);
3096 # elif defined(HAVE_CDSASSL)
3097 size_t bytes; /* Bytes that are available */
3098
3099 if (!SSLGetBufferedReadSize(con->http.tls, &bytes) && bytes > 0)
3100 return (1);
3101 # endif /* HAVE_LIBSSL */
3102 }
3103 #endif /* HAVE_SSL */
3104
3105 return (0);
3106 }
3107
3108
3109 /*
3110 * 'get_file()' - Get a filename and state info.
3111 */
3112
3113 static char * /* O - Real filename */
3114 get_file(cupsd_client_t *con, /* I - Client connection */
3115 struct stat *filestats, /* O - File information */
3116 char *filename, /* IO - Filename buffer */
3117 int len) /* I - Buffer length */
3118 {
3119 int status; /* Status of filesystem calls */
3120 char *ptr; /* Pointer info filename */
3121 int plen; /* Remaining length after pointer */
3122 char language[7]; /* Language subdirectory, if any */
3123
3124
3125 /*
3126 * Figure out the real filename...
3127 */
3128
3129 language[0] = '\0';
3130
3131 if (!strncmp(con->uri, "/ppd/", 5) && !strchr(con->uri + 5, '/'))
3132 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
3133 else if (!strncmp(con->uri, "/icons/", 7) && !strchr(con->uri + 7, '/'))
3134 {
3135 snprintf(filename, len, "%s/%s", CacheDir, con->uri + 7);
3136 if (access(filename, F_OK) < 0)
3137 snprintf(filename, len, "%s/images/generic.png", DocumentRoot);
3138 }
3139 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3140 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
3141 else if (!strncmp(con->uri, "/admin/conf/", 12))
3142 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3143 else if (!strncmp(con->uri, "/admin/log/", 11))
3144 {
3145 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
3146 strlcpy(filename, AccessLog, len);
3147 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
3148 strlcpy(filename, ErrorLog, len);
3149 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
3150 strlcpy(filename, PageLog, len);
3151 else
3152 return (NULL);
3153 }
3154 else if (con->language)
3155 {
3156 snprintf(language, sizeof(language), "/%s", con->language->language);
3157 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3158 }
3159 else
3160 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3161
3162 if ((ptr = strchr(filename, '?')) != NULL)
3163 *ptr = '\0';
3164
3165 /*
3166 * Grab the status for this language; if there isn't a language-specific file
3167 * then fallback to the default one...
3168 */
3169
3170 if ((status = stat(filename, filestats)) != 0 && language[0] &&
3171 strncmp(con->uri, "/icons/", 7) &&
3172 strncmp(con->uri, "/ppd/", 5) &&
3173 strncmp(con->uri, "/rss/", 5) &&
3174 strncmp(con->uri, "/admin/conf/", 12) &&
3175 strncmp(con->uri, "/admin/log/", 11))
3176 {
3177 /*
3178 * Drop the country code...
3179 */
3180
3181 language[3] = '\0';
3182 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3183
3184 if ((ptr = strchr(filename, '?')) != NULL)
3185 *ptr = '\0';
3186
3187 if ((status = stat(filename, filestats)) != 0)
3188 {
3189 /*
3190 * Drop the language prefix and try the root directory...
3191 */
3192
3193 language[0] = '\0';
3194 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3195
3196 if ((ptr = strchr(filename, '?')) != NULL)
3197 *ptr = '\0';
3198
3199 status = stat(filename, filestats);
3200 }
3201 }
3202
3203 /*
3204 * If we're found a directory, get the index.html file instead...
3205 */
3206
3207 if (!status && S_ISDIR(filestats->st_mode))
3208 {
3209 /*
3210 * Make sure the URI ends with a slash...
3211 */
3212
3213 if (con->uri[strlen(con->uri) - 1] != '/')
3214 strlcat(con->uri, "/", sizeof(con->uri));
3215
3216 /*
3217 * Find the directory index file, trying every language...
3218 */
3219
3220 do
3221 {
3222 if (status && language[0])
3223 {
3224 /*
3225 * Try a different language subset...
3226 */
3227
3228 if (language[3])
3229 language[0] = '\0'; /* Strip country code */
3230 else
3231 language[0] = '\0'; /* Strip language */
3232 }
3233
3234 /*
3235 * Look for the index file...
3236 */
3237
3238 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3239
3240 if ((ptr = strchr(filename, '?')) != NULL)
3241 *ptr = '\0';
3242
3243 ptr = filename + strlen(filename);
3244 plen = len - (ptr - filename);
3245
3246 strlcpy(ptr, "index.html", plen);
3247 status = stat(filename, filestats);
3248
3249 #ifdef HAVE_JAVA
3250 if (status)
3251 {
3252 strlcpy(ptr, "index.class", plen);
3253 status = stat(filename, filestats);
3254 }
3255 #endif /* HAVE_JAVA */
3256
3257 #ifdef HAVE_PERL
3258 if (status)
3259 {
3260 strlcpy(ptr, "index.pl", plen);
3261 status = stat(filename, filestats);
3262 }
3263 #endif /* HAVE_PERL */
3264
3265 #ifdef HAVE_PHP
3266 if (status)
3267 {
3268 strlcpy(ptr, "index.php", plen);
3269 status = stat(filename, filestats);
3270 }
3271 #endif /* HAVE_PHP */
3272
3273 #ifdef HAVE_PYTHON
3274 if (status)
3275 {
3276 strlcpy(ptr, "index.pyc", plen);
3277 status = stat(filename, filestats);
3278 }
3279
3280 if (status)
3281 {
3282 strlcpy(ptr, "index.py", plen);
3283 status = stat(filename, filestats);
3284 }
3285 #endif /* HAVE_PYTHON */
3286
3287 }
3288 while (status && language[0]);
3289 }
3290
3291 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3292 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3293 "returning \"%s\".", con->http.fd, filestats, filename, len,
3294 status ? "(null)" : filename);
3295
3296 if (status)
3297 return (NULL);
3298 else
3299 return (filename);
3300 }
3301
3302
3303 /*
3304 * 'install_cupsd_conf()' - Install a configuration file.
3305 */
3306
3307 static http_status_t /* O - Status */
3308 install_cupsd_conf(cupsd_client_t *con) /* I - Connection */
3309 {
3310 char filename[1024]; /* Configuration filename */
3311 cups_file_t *in, /* Input file */
3312 *out; /* Output file */
3313 char buffer[16384]; /* Copy buffer */
3314 ssize_t bytes; /* Number of bytes */
3315
3316
3317 /*
3318 * Open the request file...
3319 */
3320
3321 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3322 {
3323 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\": %s",
3324 con->filename, strerror(errno));
3325 return (HTTP_SERVER_ERROR);
3326 }
3327
3328 /*
3329 * Open the new config file...
3330 */
3331
3332 snprintf(filename, sizeof(filename), "%s/cupsd.conf", ServerRoot);
3333 if ((out = cupsdCreateConfFile(filename, ConfigFilePerm)) == NULL)
3334 {
3335 cupsFileClose(in);
3336 return (HTTP_SERVER_ERROR);
3337 }
3338
3339 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", filename);
3340
3341 /*
3342 * Copy from the request to the new config file...
3343 */
3344
3345 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3346 if (cupsFileWrite(out, buffer, bytes) < bytes)
3347 {
3348 cupsdLogMessage(CUPSD_LOG_ERROR,
3349 "Unable to copy to config file \"%s\": %s",
3350 filename, strerror(errno));
3351
3352 cupsFileClose(in);
3353 cupsFileClose(out);
3354
3355 snprintf(filename, sizeof(filename), "%s%s.N", ServerRoot, con->uri + 11);
3356 cupsdRemoveFile(filename);
3357
3358 return (HTTP_SERVER_ERROR);
3359 }
3360
3361 /*
3362 * Close the files...
3363 */
3364
3365 cupsFileClose(in);
3366
3367 if (cupsdCloseCreatedConfFile(out, filename))
3368 return (HTTP_SERVER_ERROR);
3369
3370 /*
3371 * Remove the request file...
3372 */
3373
3374 cupsdRemoveFile(con->filename);
3375 cupsdClearString(&con->filename);
3376
3377 /*
3378 * Set the NeedReload flag...
3379 */
3380
3381 NeedReload = RELOAD_CUPSD;
3382 ReloadTime = time(NULL);
3383
3384 /*
3385 * Return that the file was created successfully...
3386 */
3387
3388 return (HTTP_CREATED);
3389 }
3390
3391
3392 /*
3393 * 'is_cgi()' - Is the resource a CGI script/program?
3394 */
3395
3396 static int /* O - 1 = CGI, 0 = file */
3397 is_cgi(cupsd_client_t *con, /* I - Client connection */
3398 const char *filename, /* I - Real filename */
3399 struct stat *filestats, /* I - File information */
3400 mime_type_t *type) /* I - MIME type */
3401 {
3402 const char *options; /* Options on URL */
3403
3404
3405 /*
3406 * Get the options, if any...
3407 */
3408
3409 if ((options = strchr(con->uri, '?')) != NULL)
3410 {
3411 options ++;
3412 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3413 }
3414
3415 /*
3416 * Check for known types...
3417 */
3418
3419 if (!type || _cups_strcasecmp(type->super, "application"))
3420 {
3421 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3422 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3423 "type=%s/%s, returning 0", con->http.fd, filename,
3424 filestats, type ? type->super : "unknown",
3425 type ? type->type : "unknown");
3426 return (0);
3427 }
3428
3429 if (!_cups_strcasecmp(type->type, "x-httpd-cgi") &&
3430 (filestats->st_mode & 0111))
3431 {
3432 /*
3433 * "application/x-httpd-cgi" is a CGI script.
3434 */
3435
3436 cupsdSetString(&con->command, filename);
3437
3438 if (options)
3439 cupsdSetStringf(&con->options, " %s", options);
3440
3441 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3442 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3443 "type=%s/%s, returning 1", con->http.fd, filename,
3444 filestats, type->super, type->type);
3445 return (1);
3446 }
3447 #ifdef HAVE_JAVA
3448 else if (!_cups_strcasecmp(type->type, "x-httpd-java"))
3449 {
3450 /*
3451 * "application/x-httpd-java" is a Java servlet.
3452 */
3453
3454 cupsdSetString(&con->command, CUPS_JAVA);
3455
3456 if (options)
3457 cupsdSetStringf(&con->options, " %s %s", filename, options);
3458 else
3459 cupsdSetStringf(&con->options, " %s", filename);
3460
3461 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3462 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3463 "type=%s/%s, returning 1", con->http.fd, filename,
3464 filestats, type->super, type->type);
3465 return (1);
3466 }
3467 #endif /* HAVE_JAVA */
3468 #ifdef HAVE_PERL
3469 else if (!_cups_strcasecmp(type->type, "x-httpd-perl"))
3470 {
3471 /*
3472 * "application/x-httpd-perl" is a Perl page.
3473 */
3474
3475 cupsdSetString(&con->command, CUPS_PERL);
3476
3477 if (options)
3478 cupsdSetStringf(&con->options, " %s %s", filename, options);
3479 else
3480 cupsdSetStringf(&con->options, " %s", filename);
3481
3482 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3483 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3484 "type=%s/%s, returning 1", con->http.fd, filename,
3485 filestats, type->super, type->type);
3486 return (1);
3487 }
3488 #endif /* HAVE_PERL */
3489 #ifdef HAVE_PHP
3490 else if (!_cups_strcasecmp(type->type, "x-httpd-php"))
3491 {
3492 /*
3493 * "application/x-httpd-php" is a PHP page.
3494 */
3495
3496 cupsdSetString(&con->command, CUPS_PHP);
3497
3498 if (options)
3499 cupsdSetStringf(&con->options, " %s %s", filename, options);
3500 else
3501 cupsdSetStringf(&con->options, " %s", filename);
3502
3503 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3504 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3505 "type=%s/%s, returning 1", con->http.fd, filename,
3506 filestats, type->super, type->type);
3507 return (1);
3508 }
3509 #endif /* HAVE_PHP */
3510 #ifdef HAVE_PYTHON
3511 else if (!_cups_strcasecmp(type->type, "x-httpd-python"))
3512 {
3513 /*
3514 * "application/x-httpd-python" is a Python page.
3515 */
3516
3517 cupsdSetString(&con->command, CUPS_PYTHON);
3518
3519 if (options)
3520 cupsdSetStringf(&con->options, " %s %s", filename, options);
3521 else
3522 cupsdSetStringf(&con->options, " %s", filename);
3523
3524 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3525 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3526 "type=%s/%s, returning 1", con->http.fd, filename,
3527 filestats, type->super, type->type);
3528 return (1);
3529 }
3530 #endif /* HAVE_PYTHON */
3531
3532 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3533 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3534 "type=%s/%s, returning 0", con->http.fd, filename,
3535 filestats, type->super, type->type);
3536 return (0);
3537 }
3538
3539
3540 /*
3541 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3542 */
3543
3544 static int /* O - 0 if relative, 1 if absolute */
3545 is_path_absolute(const char *path) /* I - Input path */
3546 {
3547 /*
3548 * Check for a leading slash...
3549 */
3550
3551 if (path[0] != '/')
3552 return (0);
3553
3554 /*
3555 * Check for "/.." in the path...
3556 */
3557
3558 while ((path = strstr(path, "/..")) != NULL)
3559 {
3560 if (!path[3] || path[3] == '/')
3561 return (0);
3562
3563 path ++;
3564 }
3565
3566 /*
3567 * If we haven't found any relative paths, return 1 indicating an
3568 * absolute path...
3569 */
3570
3571 return (1);
3572 }
3573
3574
3575 /*
3576 * 'pipe_command()' - Pipe the output of a command to the remote client.
3577 */
3578
3579 static int /* O - Process ID */
3580 pipe_command(cupsd_client_t *con, /* I - Client connection */
3581 int infile, /* I - Standard input for command */
3582 int *outfile, /* O - Standard output for command */
3583 char *command, /* I - Command to run */
3584 char *options, /* I - Options for command */
3585 int root) /* I - Run as root? */
3586 {
3587 int i; /* Looping var */
3588 int pid; /* Process ID */
3589 char *commptr, /* Command string pointer */
3590 commch; /* Command string character */
3591 char *uriptr; /* URI string pointer */
3592 int fds[2]; /* Pipe FDs */
3593 int argc; /* Number of arguments */
3594 int envc; /* Number of environment variables */
3595 char argbuf[10240], /* Argument buffer */
3596 *argv[100], /* Argument strings */
3597 *envp[MAX_ENV + 20]; /* Environment variables */
3598 char auth_type[256], /* AUTH_TYPE environment variable */
3599 content_length[1024], /* CONTENT_LENGTH environment variable */
3600 content_type[1024], /* CONTENT_TYPE environment variable */
3601 http_cookie[32768], /* HTTP_COOKIE environment variable */
3602 http_referer[1024], /* HTTP_REFERER environment variable */
3603 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
3604 lang[1024], /* LANG environment variable */
3605 path_info[1024], /* PATH_INFO environment variable */
3606 remote_addr[1024], /* REMOTE_ADDR environment variable */
3607 remote_host[1024], /* REMOTE_HOST environment variable */
3608 remote_user[1024], /* REMOTE_USER environment variable */
3609 script_filename[1024], /* SCRIPT_FILENAME environment variable */
3610 script_name[1024], /* SCRIPT_NAME environment variable */
3611 server_name[1024], /* SERVER_NAME environment variable */
3612 server_port[1024]; /* SERVER_PORT environment variable */
3613 ipp_attribute_t *attr; /* attributes-natural-language attribute */
3614
3615
3616 /*
3617 * Parse a copy of the options string, which is of the form:
3618 *
3619 * argument+argument+argument
3620 * ?argument+argument+argument
3621 * param=value&param=value
3622 * ?param=value&param=value
3623 * /name?argument+argument+argument
3624 * /name?param=value&param=value
3625 *
3626 * If the string contains an "=" character after the initial name,
3627 * then we treat it as a HTTP GET form request and make a copy of
3628 * the remaining string for the environment variable.
3629 *
3630 * The string is always parsed out as command-line arguments, to
3631 * be consistent with Apache...
3632 */
3633
3634 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3635 "[Client %d] pipe_command infile=%d, outfile=%p, "
3636 "command=\"%s\", options=\"%s\", root=%d",
3637 con->http.fd, infile, outfile, command,
3638 options ? options : "(null)", root);
3639
3640 argv[0] = command;
3641
3642 if (options)
3643 {
3644 commptr = options;
3645 if (*commptr == ' ')
3646 commptr ++;
3647 strlcpy(argbuf, commptr, sizeof(argbuf));
3648 }
3649 else
3650 argbuf[0] = '\0';
3651
3652 if (argbuf[0] == '/')
3653 {
3654 /*
3655 * Found some trailing path information, set PATH_INFO...
3656 */
3657
3658 if ((commptr = strchr(argbuf, '?')) == NULL)
3659 commptr = argbuf + strlen(argbuf);
3660
3661 commch = *commptr;
3662 *commptr = '\0';
3663 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
3664 *commptr = commch;
3665 }
3666 else
3667 {
3668 commptr = argbuf;
3669 path_info[0] = '\0';
3670
3671 if (*commptr == ' ')
3672 commptr ++;
3673 }
3674
3675 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
3676 {
3677 commptr ++;
3678 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
3679 }
3680
3681 argc = 1;
3682
3683 if (*commptr)
3684 {
3685 argv[argc ++] = commptr;
3686
3687 for (; *commptr && argc < 99; commptr ++)
3688 {
3689 /*
3690 * Break arguments whenever we see a + or space...
3691 */
3692
3693 if (*commptr == ' ' || *commptr == '+')
3694 {
3695 while (*commptr == ' ' || *commptr == '+')
3696 *commptr++ = '\0';
3697
3698 /*
3699 * If we don't have a blank string, save it as another argument...
3700 */
3701
3702 if (*commptr)
3703 {
3704 argv[argc] = commptr;
3705 argc ++;
3706 }
3707 else
3708 break;
3709 }
3710 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
3711 isxdigit(commptr[2] & 255))
3712 {
3713 /*
3714 * Convert the %xx notation to the individual character.
3715 */
3716
3717 if (commptr[1] >= '0' && commptr[1] <= '9')
3718 *commptr = (commptr[1] - '0') << 4;
3719 else
3720 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
3721
3722 if (commptr[2] >= '0' && commptr[2] <= '9')
3723 *commptr |= commptr[2] - '0';
3724 else
3725 *commptr |= tolower(commptr[2]) - 'a' + 10;
3726
3727 _cups_strcpy(commptr + 1, commptr + 3);
3728
3729 /*
3730 * Check for a %00 and break if that is the case...
3731 */
3732
3733 if (!*commptr)
3734 break;
3735 }
3736 }
3737 }
3738
3739 argv[argc] = NULL;
3740
3741 /*
3742 * Setup the environment variables as needed...
3743 */
3744
3745 if (con->username[0])
3746 {
3747 snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
3748 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
3749
3750 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
3751 *uriptr = '\0';
3752 }
3753 else
3754 auth_type[0] = '\0';
3755
3756 if (con->request &&
3757 (attr = ippFindAttribute(con->request, "attributes-natural-language",
3758 IPP_TAG_LANGUAGE)) != NULL)
3759 {
3760 switch (strlen(attr->values[0].string.text))
3761 {
3762 default :
3763 /*
3764 * This is an unknown or badly formatted language code; use
3765 * the POSIX locale...
3766 */
3767
3768 strlcpy(lang, "LANG=C", sizeof(lang));
3769 break;
3770
3771 case 2 :
3772 /*
3773 * Just the language code (ll)...
3774 */
3775
3776 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
3777 attr->values[0].string.text);
3778 break;
3779
3780 case 5 :
3781 /*
3782 * Language and country code (ll-cc)...
3783 */
3784
3785 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
3786 attr->values[0].string.text[0],
3787 attr->values[0].string.text[1],
3788 toupper(attr->values[0].string.text[3] & 255),
3789 toupper(attr->values[0].string.text[4] & 255));
3790 break;
3791 }
3792 }
3793 else if (con->language)
3794 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
3795 else
3796 strlcpy(lang, "LANG=C", sizeof(lang));
3797
3798 strlcpy(remote_addr, "REMOTE_ADDR=", sizeof(remote_addr));
3799 httpAddrString(con->http.hostaddr, remote_addr + 12,
3800 sizeof(remote_addr) - 12);
3801
3802 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
3803 con->http.hostname);
3804
3805 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
3806 if ((uriptr = strchr(script_name, '?')) != NULL)
3807 *uriptr = '\0';
3808
3809 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
3810 DocumentRoot, script_name + 12);
3811
3812 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
3813
3814 if (con->http.fields[HTTP_FIELD_HOST][0])
3815 {
3816 char *nameptr; /* Pointer to ":port" */
3817
3818 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3819 con->http.fields[HTTP_FIELD_HOST]);
3820 if ((nameptr = strrchr(server_name, ':')) != NULL && !strchr(nameptr, ']'))
3821 *nameptr = '\0'; /* Strip trailing ":port" */
3822 }
3823 else
3824 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3825 con->servername);
3826
3827 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
3828
3829 if (auth_type[0])
3830 envp[envc ++] = auth_type;
3831
3832 envp[envc ++] = lang;
3833 envp[envc ++] = "REDIRECT_STATUS=1";
3834 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
3835 envp[envc ++] = server_name;
3836 envp[envc ++] = server_port;
3837 envp[envc ++] = remote_addr;
3838 envp[envc ++] = remote_host;
3839 envp[envc ++] = script_name;
3840 envp[envc ++] = script_filename;
3841
3842 if (path_info[0])
3843 envp[envc ++] = path_info;
3844
3845 if (con->username[0])
3846 {
3847 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
3848
3849 envp[envc ++] = remote_user;
3850 }
3851
3852 if (con->http.version == HTTP_1_1)
3853 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
3854 else if (con->http.version == HTTP_1_0)
3855 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
3856 else
3857 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
3858
3859 if (con->http.cookie)
3860 {
3861 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
3862 con->http.cookie);
3863 envp[envc ++] = http_cookie;
3864 }
3865
3866 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
3867 {
3868 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
3869 con->http.fields[HTTP_FIELD_USER_AGENT]);
3870 envp[envc ++] = http_user_agent;
3871 }
3872
3873 if (con->http.fields[HTTP_FIELD_REFERER][0])
3874 {
3875 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
3876 con->http.fields[HTTP_FIELD_REFERER]);
3877 envp[envc ++] = http_referer;
3878 }
3879
3880 if (con->operation == HTTP_GET)
3881 {
3882 envp[envc ++] = "REQUEST_METHOD=GET";
3883
3884 if (con->query_string)
3885 {
3886 /*
3887 * Add GET form variables after ?...
3888 */
3889
3890 envp[envc ++] = con->query_string;
3891 }
3892 else
3893 envp[envc ++] = "QUERY_STRING=";
3894 }
3895 else
3896 {
3897 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
3898 CUPS_LLCAST con->bytes);
3899 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
3900 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
3901
3902 envp[envc ++] = "REQUEST_METHOD=POST";
3903 envp[envc ++] = content_length;
3904 envp[envc ++] = content_type;
3905 }
3906
3907 /*
3908 * Tell the CGI if we are using encryption...
3909 */
3910
3911 if (con->http.tls)
3912 envp[envc ++] = "HTTPS=ON";
3913
3914 /*
3915 * Terminate the environment array...
3916 */
3917
3918 envp[envc] = NULL;
3919
3920 if (LogLevel >= CUPSD_LOG_DEBUG)
3921 {
3922 for (i = 0; i < argc; i ++)
3923 cupsdLogMessage(CUPSD_LOG_DEBUG,
3924 "[CGI] argv[%d] = \"%s\"", i, argv[i]);
3925 for (i = 0; i < envc; i ++)
3926 cupsdLogMessage(CUPSD_LOG_DEBUG,
3927 "[CGI] envp[%d] = \"%s\"", i, envp[i]);
3928 }
3929
3930 /*
3931 * Create a pipe for the output...
3932 */
3933
3934 if (cupsdOpenPipe(fds))
3935 {
3936 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
3937 argv[0], strerror(errno));
3938 return (0);
3939 }
3940
3941 /*
3942 * Then execute the command...
3943 */
3944
3945 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
3946 -1, -1, root, DefaultProfile, NULL, &pid) < 0)
3947 {
3948 /*
3949 * Error - can't fork!
3950 */
3951
3952 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
3953 strerror(errno));
3954
3955 cupsdClosePipe(fds);
3956 pid = 0;
3957 }
3958 else
3959 {
3960 /*
3961 * Fork successful - return the PID...
3962 */
3963
3964 if (con->username[0])
3965 cupsdAddCert(pid, con->username, con->type);
3966
3967 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
3968
3969 *outfile = fds[0];
3970 close(fds[1]);
3971 }
3972
3973 return (pid);
3974 }
3975
3976
3977 /*
3978 * 'valid_host()' - Is the Host: field valid?
3979 */
3980
3981 static int /* O - 1 if valid, 0 if not */
3982 valid_host(cupsd_client_t *con) /* I - Client connection */
3983 {
3984 cupsd_alias_t *a; /* Current alias */
3985 cupsd_netif_t *netif; /* Current network interface */
3986 const char *host, /* Host field */
3987 *end; /* End character */
3988
3989
3990 host = con->http.fields[HTTP_FIELD_HOST];
3991
3992 if (httpAddrLocalhost(con->http.hostaddr))
3993 {
3994 /*
3995 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3996 * addresses when accessing CUPS via the loopback interface...
3997 */
3998
3999 return (!_cups_strcasecmp(host, "localhost") ||
4000 !_cups_strncasecmp(host, "localhost:", 10) ||
4001 !_cups_strcasecmp(host, "localhost.") ||
4002 !_cups_strncasecmp(host, "localhost.:", 11) ||
4003 #ifdef __linux
4004 !_cups_strcasecmp(host, "localhost.localdomain") ||
4005 !_cups_strncasecmp(host, "localhost.localdomain:", 22) ||
4006 #endif /* __linux */
4007 !strcmp(host, "127.0.0.1") ||
4008 !strncmp(host, "127.0.0.1:", 10) ||
4009 !strcmp(host, "[::1]") ||
4010 !strncmp(host, "[::1]:", 6));
4011 }
4012
4013 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4014 /*
4015 * Check if the hostname is something.local (Bonjour); if so, allow it.
4016 */
4017
4018 if ((end = strrchr(host, '.')) != NULL && end > host &&
4019 (!end[1] || end[1] == ':'))
4020 {
4021 /*
4022 * "." on end, work back to second-to-last "."...
4023 */
4024 for (end --; end > host && *end != '.'; end --);
4025 }
4026
4027 if (end && (!_cups_strcasecmp(end, ".local") ||
4028 !_cups_strncasecmp(end, ".local:", 7) ||
4029 !_cups_strcasecmp(end, ".local.") ||
4030 !_cups_strncasecmp(end, ".local.:", 8)))
4031 return (1);
4032 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4033
4034 /*
4035 * Check if the hostname is an IP address...
4036 */
4037
4038 if (isdigit(*host & 255) || *host == '[')
4039 {
4040 /*
4041 * Possible IPv4/IPv6 address...
4042 */
4043
4044 char temp[1024], /* Temporary string */
4045 *ptr; /* Pointer into temporary string */
4046 http_addrlist_t *addrlist; /* List of addresses */
4047
4048
4049 strlcpy(temp, host, sizeof(temp));
4050 if ((ptr = strrchr(temp, ':')) != NULL && !strchr(ptr, ']'))
4051 *ptr = '\0'; /* Strip :port from host value */
4052
4053 if ((addrlist = httpAddrGetList(temp, AF_UNSPEC, NULL)) != NULL)
4054 {
4055 /*
4056 * Good IPv4/IPv6 address...
4057 */
4058
4059 httpAddrFreeList(addrlist);
4060 return (1);
4061 }
4062 }
4063
4064 /*
4065 * Check for (alias) name matches...
4066 */
4067
4068 for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
4069 a;
4070 a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
4071 {
4072 /*
4073 * "ServerAlias *" allows all host values through...
4074 */
4075
4076 if (!strcmp(a->name, "*"))
4077 return (1);
4078
4079 if (!_cups_strncasecmp(host, a->name, a->namelen))
4080 {
4081 /*
4082 * Prefix matches; check the character at the end - it must be ":", ".",
4083 * ".:", or nul...
4084 */
4085
4086 end = host + a->namelen;
4087
4088 if (!*end || *end == ':' || (*end == '.' && (!end[1] || end[1] == ':')))
4089 return (1);
4090 }
4091 }
4092
4093 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4094 for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
4095 a;
4096 a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
4097 {
4098 /*
4099 * "ServerAlias *" allows all host values through...
4100 */
4101
4102 if (!strcmp(a->name, "*"))
4103 return (1);
4104
4105 if (!_cups_strncasecmp(host, a->name, a->namelen))
4106 {
4107 /*
4108 * Prefix matches; check the character at the end - it must be ":", ".",
4109 * ".:", or nul...
4110 */
4111
4112 end = host + a->namelen;
4113
4114 if (!*end || *end == ':' || (*end == '.' && (!end[1] || end[1] == ':')))
4115 return (1);
4116 }
4117 }
4118 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4119
4120 /*
4121 * Check for interface hostname matches...
4122 */
4123
4124 for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
4125 netif;
4126 netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
4127 {
4128 if (!_cups_strncasecmp(host, netif->hostname, netif->hostlen))
4129 {
4130 /*
4131 * Prefix matches; check the character at the end - it must be ":", ".",
4132 * ".:", or nul...
4133 */
4134
4135 end = host + netif->hostlen;
4136
4137 if (!*end || *end == ':' || (*end == '.' && (!end[1] || end[1] == ':')))
4138 return (1);
4139 }
4140 }
4141
4142 return (0);
4143 }
4144
4145
4146 /*
4147 * 'write_file()' - Send a file via HTTP.
4148 */
4149
4150 static int /* O - 0 on failure, 1 on success */
4151 write_file(cupsd_client_t *con, /* I - Client connection */
4152 http_status_t code, /* I - HTTP status */
4153 char *filename, /* I - Filename */
4154 char *type, /* I - File type */
4155 struct stat *filestats) /* O - File information */
4156 {
4157 con->file = open(filename, O_RDONLY);
4158
4159 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4160 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4161 "type=\"%s\", filestats=%p", con->http.fd,
4162 code, filename, con->file, type ? type : "(null)", filestats);
4163
4164 if (con->file < 0)
4165 return (0);
4166
4167 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4168
4169 con->pipe_pid = 0;
4170
4171 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
4172 return (0);
4173
4174 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
4175 httpGetDateString(filestats->st_mtime)) < 0)
4176 return (0);
4177 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
4178 CUPS_LLCAST filestats->st_size) < 0)
4179 return (0);
4180 if (httpPrintf(HTTP(con), "\r\n") < 0)
4181 return (0);
4182
4183 if (cupsdFlushHeader(con) < 0)
4184 return (0);
4185
4186 con->http.data_encoding = HTTP_ENCODE_LENGTH;
4187 con->http.data_remaining = filestats->st_size;
4188
4189 if (con->http.data_remaining <= INT_MAX)
4190 con->http._data_remaining = con->http.data_remaining;
4191 else
4192 con->http._data_remaining = INT_MAX;
4193
4194 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
4195 (cupsd_selfunc_t)cupsdWriteClient, con);
4196
4197 return (1);
4198 }
4199
4200
4201 /*
4202 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4203 */
4204
4205 static void
4206 write_pipe(cupsd_client_t *con) /* I - Client connection */
4207 {
4208 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4209 "[Client %d] write_pipe CGI output on fd %d",
4210 con->http.fd, con->file);
4211
4212 con->file_ready = 1;
4213
4214 cupsdRemoveSelect(con->file);
4215 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4216 }
4217
4218
4219 /*
4220 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".
4221 */