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