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