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