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