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