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