]> git.ipfire.org Git - thirdparty/cups.git/blame - scheduler/client.c
Merge changes from CUPS 1.4svn-r8252.
[thirdparty/cups.git] / scheduler / client.c
CommitLineData
ef416fc2 1/*
b19ccc9e 2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
ef416fc2 3 *
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
5 *
91c84a35 6 * Copyright 2007-2008 by Apple Inc.
f7deaa1a 7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
9 * This file contains Kerberos support code, copyright 2006 by
10 * Jelmer Vernooij.
ef416fc2 11 *
12 * These coded instructions, statements, and computer programs are the
bc44d920 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 * Contents:
19 *
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
d09495fa 23 * cupsdFlushHeader() - Flush the header fields to the client.
ef416fc2 24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
ef416fc2 27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
3dfe78b3 31 * compare_clients() - Compare two client connections.
ee571f26 32 * data_ready() - Check whether data is available from a client.
e1d6a774 33 * encrypt_client() - Enable encryption for the client...
b86bc4cf 34 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
ef416fc2 35 * required by SSLSetCertificate.
36 * get_file() - Get a filename and state info.
37 * install_conf_file() - Install a configuration file.
e1d6a774 38 * is_cgi() - Is the resource a CGI script/program?
ef416fc2 39 * is_path_absolute() - Is a path absolute and free of relative elements.
4744bd90 40 * make_certificate() - Make a self-signed SSL/TLS certificate.
ef416fc2 41 * pipe_command() - Pipe the output of a command to the remote client.
a74454a7 42 * write_file() - Send a file via HTTP.
f899b121 43 * write_pipe() - Flag that data is available on the CGI pipe.
ef416fc2 44 */
45
46/*
47 * Include necessary headers...
48 */
49
ef416fc2 50#include "cupsd.h"
51
52#ifdef HAVE_CDSASSL
53# include <Security/Security.h>
b86bc4cf 54# ifdef HAVE_SECIDENTITYSEARCHPRIV_H
55# include <Security/SecIdentitySearchPriv.h>
56# else /* Declare prototype for function in that header... */
57extern OSStatus SecIdentitySearchCreateWithPolicy(SecPolicyRef policy,
58 CFStringRef idString, CSSM_KEYUSE keyUsage,
59 CFTypeRef keychainOrArray,
60 Boolean returnOnlyValidIdentities,
61 SecIdentitySearchRef* searchRef);
62# endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
63# ifdef HAVE_SECPOLICYPRIV_H
64# include <Security/SecPolicyPriv.h>
65# else /* Declare prototype for function in that header... */
66extern OSStatus SecPolicySetValue(SecPolicyRef policyRef,
67 const CSSM_DATA *value);
68# endif /* HAVE_SECPOLICYPRIV_H */
ed486911 69# ifdef HAVE_SECBASEPRIV_H
70# include <Security/SecBasePriv.h>
b86bc4cf 71# else /* Declare prototype for function in that header... */
72extern const char *cssmErrorString(int error);
ed486911 73# endif /* HAVE_SECBASEPRIV_H */
ef416fc2 74#endif /* HAVE_CDSASSL */
b86bc4cf 75
4744bd90 76#ifdef HAVE_GNUTLS
77# include <gnutls/x509.h>
78#endif /* HAVE_GNUTLS */
ef416fc2 79
749b1e90
MS
80#ifdef HAVE_TCPD_H
81# include <tcpd.h>
82#endif /* HAVE_TCPD_H */
83
ef416fc2 84
85/*
86 * Local functions...
87 */
88
89static int check_if_modified(cupsd_client_t *con,
90 struct stat *filestats);
3dfe78b3
MS
91static int compare_clients(cupsd_client_t *a, cupsd_client_t *b,
92 void *data);
ee571f26 93static int data_ready(cupsd_client_t *con);
80ca4592 94#ifdef HAVE_SSL
e1d6a774 95static int encrypt_client(cupsd_client_t *con);
80ca4592 96#endif /* HAVE_SSL */
ef416fc2 97#ifdef HAVE_CDSASSL
b86bc4cf 98static CFArrayRef get_cdsa_certificate(cupsd_client_t *con);
ef416fc2 99#endif /* HAVE_CDSASSL */
f7deaa1a 100static char *get_file(cupsd_client_t *con, struct stat *filestats,
ef416fc2 101 char *filename, int len);
102static http_status_t install_conf_file(cupsd_client_t *con);
e1d6a774 103static int is_cgi(cupsd_client_t *con, const char *filename,
104 struct stat *filestats, mime_type_t *type);
ef416fc2 105static int is_path_absolute(const char *path);
8ca02f3c 106#ifdef HAVE_SSL
b86bc4cf 107static int make_certificate(cupsd_client_t *con);
8ca02f3c 108#endif /* HAVE_SSL */
ef416fc2 109static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
110 char *command, char *options, int root);
a74454a7 111static int write_file(cupsd_client_t *con, http_status_t code,
112 char *filename, char *type,
113 struct stat *filestats);
f899b121 114static void write_pipe(cupsd_client_t *con);
ef416fc2 115
116
117/*
118 * 'cupsdAcceptClient()' - Accept a new client.
119 */
120
121void
122cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
123{
ef416fc2 124 int count; /* Count of connections on a host */
125 int val; /* Parameter value */
bd7854cb 126 cupsd_client_t *con, /* New client pointer */
127 *tempcon; /* Temporary client pointer */
ef416fc2 128 http_addrlist_t *addrlist, /* List of adddresses for host */
129 *addr; /* Current address */
130 socklen_t addrlen; /* Length of address */
131 char *hostname; /* Hostname for address */
132 http_addr_t temp; /* Temporary address variable */
133 static time_t last_dos = 0; /* Time of last DoS attack */
749b1e90
MS
134#ifdef HAVE_TCPD_H
135 struct request_info wrap_req; /* TCP wrappers request information */
136#endif /* HAVE_TCPD_H */
ef416fc2 137
138
139 cupsdLogMessage(CUPSD_LOG_DEBUG2,
bd7854cb 140 "cupsdAcceptClient(lis=%p) %d Clients = %d",
141 lis, lis->fd, cupsArrayCount(Clients));
ef416fc2 142
143 /*
144 * Make sure we don't have a full set of clients already...
145 */
146
bd7854cb 147 if (cupsArrayCount(Clients) == MaxClients)
ef416fc2 148 return;
149
150 /*
151 * Get a pointer to the next available client...
152 */
153
bd7854cb 154 if (!Clients)
155 Clients = cupsArrayNew(NULL, NULL);
156
157 if (!Clients)
91c84a35
MS
158 {
159 cupsdLogMessage(CUPSD_LOG_ERROR,
3dfe78b3
MS
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
162 return;
163 }
164
165 if (!ActiveClients)
166 ActiveClients = cupsArrayNew((cups_array_func_t)compare_clients, NULL);
167
168 if (!ActiveClients)
169 {
170 cupsdLogMessage(CUPSD_LOG_ERROR,
171 "Unable to allocate memory for active clients array!");
91c84a35 172 cupsdPauseListening();
bd7854cb 173 return;
91c84a35 174 }
bd7854cb 175
91c84a35
MS
176 if ((con = calloc(1, sizeof(cupsd_client_t))) == NULL)
177 {
178 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to allocate memory for client!");
179 cupsdPauseListening();
180 return;
181 }
ef416fc2 182
ef416fc2 183 con->http.activity = time(NULL);
184 con->file = -1;
185 con->http.hostaddr = &(con->clientaddr);
186
187 /*
188 * Accept the client and get the remote address...
189 */
190
191 addrlen = sizeof(http_addr_t);
192
193 if ((con->http.fd = accept(lis->fd, (struct sockaddr *)con->http.hostaddr,
194 &addrlen)) < 0)
195 {
76cd9e37
MS
196 if (errno == ENFILE || errno == EMFILE)
197 cupsdPauseListening();
198
ef416fc2 199 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
200 strerror(errno));
bd7854cb 201 free(con);
76cd9e37 202
ef416fc2 203 return;
204 }
205
206#ifdef AF_INET6
207 if (lis->address.addr.sa_family == AF_INET6)
208 {
209 /*
210 * Save the connected port number...
211 */
212
213 con->http.hostaddr->ipv6.sin6_port = lis->address.ipv6.sin6_port;
214
215 /*
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
218 */
219
220 if (con->http.hostaddr->ipv6.sin6_addr.s6_addr32[0] == 0 &&
221 con->http.hostaddr->ipv6.sin6_addr.s6_addr32[1] == 0 &&
222 ntohl(con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2]) == 0xffff)
223 con->http.hostaddr->ipv6.sin6_addr.s6_addr32[2] = 0;
224 }
225 else
226#endif /* AF_INET6 */
227 if (lis->address.addr.sa_family == AF_INET)
228 con->http.hostaddr->ipv4.sin_port = lis->address.ipv4.sin_port;
229
230 /*
231 * Check the number of clients on the same address...
232 */
233
bd7854cb 234 for (count = 0, tempcon = (cupsd_client_t *)cupsArrayFirst(Clients);
235 tempcon;
236 tempcon = (cupsd_client_t *)cupsArrayNext(Clients))
237 if (httpAddrEqual(tempcon->http.hostaddr, con->http.hostaddr))
ef416fc2 238 {
239 count ++;
240 if (count >= MaxClientsPerHost)
241 break;
242 }
243
244 if (count >= MaxClientsPerHost)
245 {
246 if ((time(NULL) - last_dos) >= 60)
247 {
248 last_dos = time(NULL);
249 cupsdLogMessage(CUPSD_LOG_WARN,
bd7854cb 250 "Possible DoS attack - more than %d clients connecting "
251 "from %s!",
749b1e90
MS
252 MaxClientsPerHost,
253 httpAddrString(con->http.hostaddr, con->http.hostname,
254 sizeof(con->http.hostname)));
ef416fc2 255 }
256
257#ifdef WIN32
258 closesocket(con->http.fd);
259#else
260 close(con->http.fd);
261#endif /* WIN32 */
262
bd7854cb 263 free(con);
ef416fc2 264 return;
265 }
266
267 /*
268 * Get the hostname or format the IP address as needed...
269 */
270
271 if (httpAddrLocalhost(con->http.hostaddr))
272 {
273 /*
274 * Map accesses from the loopback interface to "localhost"...
275 */
276
277 strlcpy(con->http.hostname, "localhost", sizeof(con->http.hostname));
278 hostname = con->http.hostname;
279 }
280 else
281 {
282 /*
283 * Map accesses from the same host to the server name.
284 */
285
286 for (addr = ServerAddrs; addr; addr = addr->next)
287 if (httpAddrEqual(con->http.hostaddr, &(addr->addr)))
288 break;
289
290 if (addr)
291 {
292 strlcpy(con->http.hostname, ServerName, sizeof(con->http.hostname));
293 hostname = con->http.hostname;
294 }
295 else if (HostNameLookups)
296 hostname = httpAddrLookup(con->http.hostaddr, con->http.hostname,
297 sizeof(con->http.hostname));
298 else
299 {
300 hostname = NULL;
301 httpAddrString(con->http.hostaddr, con->http.hostname,
302 sizeof(con->http.hostname));
303 }
304 }
305
306 if (hostname == NULL && HostNameLookups == 2)
307 {
308 /*
309 * Can't have an unresolved IP address with double-lookups enabled...
310 */
311
312 cupsdLogMessage(CUPSD_LOG_DEBUG2,
313 "cupsdAcceptClient: Closing connection %d...",
314 con->http.fd);
315
316#ifdef WIN32
317 closesocket(con->http.fd);
318#else
319 close(con->http.fd);
320#endif /* WIN32 */
321
322 cupsdLogMessage(CUPSD_LOG_WARN,
323 "Name lookup failed - connection from %s closed!",
324 con->http.hostname);
bd7854cb 325
326 free(con);
ef416fc2 327 return;
328 }
329
330 if (HostNameLookups == 2)
331 {
332 /*
333 * Do double lookups as needed...
334 */
335
749b1e90
MS
336 if ((addrlist = httpAddrGetList(con->http.hostname, AF_UNSPEC, NULL))
337 != NULL)
ef416fc2 338 {
339 /*
340 * See if the hostname maps to the same IP address...
341 */
342
343 for (addr = addrlist; addr; addr = addr->next)
344 if (httpAddrEqual(con->http.hostaddr, &(addr->addr)))
345 break;
346 }
347 else
348 addr = NULL;
349
350 httpAddrFreeList(addrlist);
351
352 if (!addr)
353 {
354 /*
355 * Can't have a hostname that doesn't resolve to the same IP address
356 * with double-lookups enabled...
357 */
358
359 cupsdLogMessage(CUPSD_LOG_DEBUG2,
360 "cupsdAcceptClient: Closing connection %d...",
361 con->http.fd);
362
363#ifdef WIN32
364 closesocket(con->http.fd);
365#else
366 close(con->http.fd);
367#endif /* WIN32 */
368
369 cupsdLogMessage(CUPSD_LOG_WARN,
370 "IP lookup failed - connection from %s closed!",
371 con->http.hostname);
bd7854cb 372 free(con);
ef416fc2 373 return;
374 }
375 }
376
749b1e90
MS
377#ifdef HAVE_TCPD_H
378 /*
379 * See if the connection is denied by TCP wrappers...
380 */
381
382 request_init(&wrap_req, RQ_DAEMON, "cupsd", RQ_FILE, con->http.fd, NULL);
383 fromhost(&wrap_req);
384
385 if (!hosts_access(&wrap_req))
386 {
387 cupsdLogMessage(CUPSD_LOG_DEBUG2,
388 "cupsdAcceptClient: Closing connection %d...",
389 con->http.fd);
390
391#ifdef WIN32
392 closesocket(con->http.fd);
393#else
394 close(con->http.fd);
395#endif /* WIN32 */
396
397 cupsdLogMessage(CUPSD_LOG_WARN,
398 "Connection from %s refused by /etc/hosts.allow and "
399 "/etc/hosts.deny rules.", con->http.hostname);
400 free(con);
401 return;
402 }
403#endif /* HAVE_TCPD_H */
404
ef416fc2 405#ifdef AF_INET6
406 if (con->http.hostaddr->addr.sa_family == AF_INET6)
407 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s:%d (IPv6)",
408 con->http.fd, con->http.hostname,
409 ntohs(con->http.hostaddr->ipv6.sin6_port));
410 else
411#endif /* AF_INET6 */
412#ifdef AF_LOCAL
413 if (con->http.hostaddr->addr.sa_family == AF_LOCAL)
414 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s (Domain)",
415 con->http.fd, con->http.hostname);
416 else
417#endif /* AF_LOCAL */
418 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdAcceptClient: %d from %s:%d (IPv4)",
419 con->http.fd, con->http.hostname,
420 ntohs(con->http.hostaddr->ipv4.sin_port));
421
422 /*
423 * Get the local address the client connected to...
424 */
425
426 addrlen = sizeof(temp);
427 if (getsockname(con->http.fd, (struct sockaddr *)&temp, &addrlen))
428 {
429 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get local address - %s",
430 strerror(errno));
431
432 strcpy(con->servername, "localhost");
433 con->serverport = LocalPort;
434 }
435 else
436 {
437#ifdef AF_INET6
438 if (temp.addr.sa_family == AF_INET6)
439 {
b19ccc9e
MS
440 if (HostNameLookups)
441 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
0af14961
MS
442 else if (httpAddrLocalhost(&temp))
443 strlcpy(con->servername, "localhost", sizeof(con->servername));
b19ccc9e
MS
444 else
445 httpAddrString(&temp, con->servername, sizeof(con->servername));
446
ef416fc2 447 con->serverport = ntohs(lis->address.ipv6.sin6_port);
448 }
449 else
450#endif /* AF_INET6 */
451 if (temp.addr.sa_family == AF_INET)
452 {
b19ccc9e
MS
453 if (HostNameLookups)
454 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
0af14961
MS
455 else if (httpAddrLocalhost(&temp))
456 strlcpy(con->servername, "localhost", sizeof(con->servername));
b19ccc9e
MS
457 else
458 httpAddrString(&temp, con->servername, sizeof(con->servername));
459
ef416fc2 460 con->serverport = ntohs(lis->address.ipv4.sin_port);
461 }
462 else
463 {
464 strcpy(con->servername, "localhost");
465 con->serverport = LocalPort;
466 }
467 }
468
bd7854cb 469 cupsArrayAdd(Clients, con);
470
ef416fc2 471 cupsdLogMessage(CUPSD_LOG_DEBUG2,
472 "cupsdAcceptClient: %d connected to server on %s:%d",
473 con->http.fd, con->servername, con->serverport);
474
475 /*
476 * Using TCP_NODELAY improves responsiveness, especially on systems
477 * with a slow loopback interface... Since we write large buffers
478 * when sending print files and requests, there shouldn't be any
479 * performance penalty for this...
480 */
481
482 val = 1;
f7deaa1a 483 setsockopt(con->http.fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
ef416fc2 484
485 /*
486 * Close this file on all execs...
487 */
488
489 fcntl(con->http.fd, F_SETFD, fcntl(con->http.fd, F_GETFD) | FD_CLOEXEC);
490
491 /*
492 * Add the socket to the select() input mask.
493 */
494
f7deaa1a 495 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 496
ef416fc2 497 /*
498 * Temporarily suspend accept()'s until we lose a client...
499 */
500
bd7854cb 501 if (cupsArrayCount(Clients) == MaxClients)
ef416fc2 502 cupsdPauseListening();
503
504#ifdef HAVE_SSL
505 /*
506 * See if we are connecting on a secure port...
507 */
508
509 if (lis->encryption == HTTP_ENCRYPT_ALWAYS)
510 {
511 /*
512 * https connection; go secure...
513 */
514
515 con->http.encryption = HTTP_ENCRYPT_ALWAYS;
516
411affcf 517 if (!encrypt_client(con))
518 cupsdCloseClient(con);
ef416fc2 519 }
520 else
521 con->auto_ssl = 1;
522#endif /* HAVE_SSL */
523}
524
525
526/*
527 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
528 */
529
530void
531cupsdCloseAllClients(void)
532{
bd7854cb 533 cupsd_client_t *con; /* Current client */
534
535
536 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
537 con;
538 con = (cupsd_client_t *)cupsArrayNext(Clients))
49d87452
MS
539 if (cupsdCloseClient(con))
540 cupsdCloseClient(con);
ef416fc2 541}
542
543
544/*
545 * 'cupsdCloseClient()' - Close a remote client.
546 */
547
548int /* O - 1 if partial close, 0 if fully closed */
549cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
550{
551 int partial; /* Do partial close for SSL? */
552#ifdef HAVE_LIBSSL
553 SSL_CTX *context; /* Context for encryption */
554 SSL *conn; /* Connection for encryption */
555 unsigned long error; /* Error code */
556#elif defined(HAVE_GNUTLS)
89d46774 557 http_tls_t *conn; /* TLS connection information */
558 int error; /* Error code */
ef416fc2 559 gnutls_certificate_server_credentials *credentials;
560 /* TLS credentials */
89d46774 561# elif defined(HAVE_CDSASSL)
562 http_tls_t *conn; /* CDSA connection information */
ef416fc2 563#endif /* HAVE_LIBSSL */
564
565
566 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdCloseClient: %d", con->http.fd);
567
568 /*
569 * Flush pending writes before closing...
570 */
571
572 httpFlushWrite(HTTP(con));
573
574 partial = 0;
575
576#ifdef HAVE_SSL
577 /*
578 * Shutdown encryption as needed...
579 */
580
581 if (con->http.tls)
582 {
583 partial = 1;
584
585# ifdef HAVE_LIBSSL
586 conn = (SSL *)(con->http.tls);
587 context = SSL_get_SSL_CTX(conn);
588
589 switch (SSL_shutdown(conn))
590 {
591 case 1 :
c934a06c
MS
592 cupsdLogMessage(CUPSD_LOG_DEBUG,
593 "SSL shutdown successful!");
ef416fc2 594 break;
595 case -1 :
596 cupsdLogMessage(CUPSD_LOG_ERROR,
c934a06c 597 "Fatal error during SSL shutdown!");
ef416fc2 598 default :
599 while ((error = ERR_get_error()) != 0)
c934a06c 600 cupsdLogMessage(CUPSD_LOG_ERROR, "SSL shutdown failed: %s",
ef416fc2 601 ERR_error_string(error, NULL));
602 break;
603 }
604
605 SSL_CTX_free(context);
606 SSL_free(conn);
607
608# elif defined(HAVE_GNUTLS)
609 conn = (http_tls_t *)(con->http.tls);
610 credentials = (gnutls_certificate_server_credentials *)(conn->credentials);
611
612 error = gnutls_bye(conn->session, GNUTLS_SHUT_WR);
613 switch (error)
614 {
615 case GNUTLS_E_SUCCESS:
c934a06c
MS
616 cupsdLogMessage(CUPSD_LOG_DEBUG,
617 "SSL shutdown successful!");
ef416fc2 618 break;
619 default:
620 cupsdLogMessage(CUPSD_LOG_ERROR,
c934a06c 621 "SSL shutdown failed: %s", gnutls_strerror(error));
ef416fc2 622 break;
623 }
624
625 gnutls_deinit(conn->session);
626 gnutls_certificate_free_credentials(*credentials);
627 free(credentials);
628 free(conn);
629
630# elif defined(HAVE_CDSASSL)
89d46774 631 conn = (http_tls_t *)(con->http.tls);
632
633 while (SSLClose(conn->session) == errSSLWouldBlock)
b423cd4c 634 usleep(1000);
635
89d46774 636 SSLDisposeContext(conn->session);
637
638 if (conn->certsArray)
639 CFRelease(conn->certsArray);
640
641 free(conn);
ef416fc2 642# endif /* HAVE_LIBSSL */
643
644 con->http.tls = NULL;
645 }
646#endif /* HAVE_SSL */
647
648 if (con->pipe_pid != 0)
649 {
650 /*
651 * Stop any CGI process...
652 */
653
654 cupsdLogMessage(CUPSD_LOG_DEBUG2,
655 "cupsdCloseClient: %d Killing process ID %d...",
656 con->http.fd, con->pipe_pid);
657 cupsdEndProcess(con->pipe_pid, 1);
658 con->pipe_pid = 0;
659 }
660
661 if (con->file >= 0)
662 {
f7deaa1a 663 cupsdRemoveSelect(con->file);
ef416fc2 664
665 cupsdLogMessage(CUPSD_LOG_DEBUG2,
666 "cupsdCloseClient: %d Closing data file %d.",
667 con->http.fd, con->file);
668
669 close(con->file);
670 con->file = -1;
671 }
672
673 /*
674 * Close the socket and clear the file from the input set for select()...
675 */
676
3dfe78b3 677 if (con->http.fd >= 0)
ef416fc2 678 {
3dfe78b3
MS
679 cupsArrayRemove(ActiveClients, con);
680 cupsdSetBusyState();
681
ef416fc2 682 if (partial)
683 {
684 /*
685 * Only do a partial close so that the encrypted client gets everything.
686 */
687
ef416fc2 688 shutdown(con->http.fd, 0);
f7deaa1a 689 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 690 }
691 else
692 {
693 /*
694 * Shut the socket down fully...
695 */
696
f7deaa1a 697 cupsdRemoveSelect(con->http.fd);
ef416fc2 698 close(con->http.fd);
ef416fc2 699 con->http.fd = -1;
700 }
701 }
702
703 if (!partial)
704 {
705 /*
706 * Free memory...
707 */
708
709 if (con->http.input_set)
710 free(con->http.input_set);
711
712 httpClearCookie(HTTP(con));
9f5eb9be 713 httpClearFields(HTTP(con));
ef416fc2 714
715 cupsdClearString(&con->filename);
716 cupsdClearString(&con->command);
717 cupsdClearString(&con->options);
b86bc4cf 718 cupsdClearString(&con->query_string);
ef416fc2 719
720 if (con->request)
721 {
722 ippDelete(con->request);
723 con->request = NULL;
724 }
725
726 if (con->response)
727 {
728 ippDelete(con->response);
729 con->response = NULL;
730 }
731
732 if (con->language)
733 {
734 cupsLangFree(con->language);
735 con->language = NULL;
736 }
737
f7deaa1a 738#ifdef HAVE_AUTHORIZATION_H
739 if (con->authref)
740 {
741 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
742 con->authref = NULL;
743 }
744#endif /* HAVE_AUTHORIZATION_H */
745
ef416fc2 746 /*
747 * Re-enable new client connections if we are going back under the
748 * limit...
749 */
750
bd7854cb 751 if (cupsArrayCount(Clients) == MaxClients)
ef416fc2 752 cupsdResumeListening();
753
754 /*
755 * Compact the list of clients as necessary...
756 */
757
bd7854cb 758 cupsArrayRemove(Clients, con);
ef416fc2 759
bd7854cb 760 free(con);
ef416fc2 761 }
762
763 return (partial);
764}
765
766
d09495fa 767/*
768 * 'cupsdFlushHeader()' - Flush the header fields to the client.
769 */
770
07725fee 771int /* I - Bytes written or -1 on error */
d09495fa 772cupsdFlushHeader(cupsd_client_t *con) /* I - Client to flush to */
773{
07725fee 774 int bytes = httpFlushWrite(HTTP(con));
d09495fa 775
776 con->http.data_encoding = HTTP_ENCODE_LENGTH;
07725fee 777
778 return (bytes);
d09495fa 779}
780
781
ef416fc2 782/*
783 * 'cupsdReadClient()' - Read data from a client.
784 */
785
f7deaa1a 786void
ef416fc2 787cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
788{
789 char line[32768], /* Line from client... */
790 operation[64], /* Operation code from socket */
791 version[64], /* HTTP version number string */
792 locale[64], /* Locale */
793 *ptr; /* Pointer into strings */
794 int major, minor; /* HTTP version numbers */
795 http_status_t status; /* Transfer status */
796 ipp_state_t ipp_state; /* State of IPP transfer */
797 int bytes; /* Number of bytes to POST */
798 char *filename; /* Name of file for GET/HEAD */
799 char buf[1024]; /* Buffer for real filename */
800 struct stat filestats; /* File information */
801 mime_type_t *type; /* MIME type of file */
802 cupsd_printer_t *p; /* Printer */
803 static unsigned request_id = 0; /* Request ID for temp files */
804
805
806 status = HTTP_CONTINUE;
807
808 cupsdLogMessage(CUPSD_LOG_DEBUG2,
809 "cupsdReadClient: %d, used=%d, file=%d state=%d",
810 con->http.fd, con->http.used, con->file, con->http.state);
811
812 if (con->http.error)
813 {
814 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadClient: http error seen...");
f7deaa1a 815 cupsdCloseClient(con);
816 return;
ef416fc2 817 }
818
819#ifdef HAVE_SSL
820 if (con->auto_ssl)
821 {
822 /*
823 * Automatically check for a SSL/TLS handshake...
824 */
825
826 con->auto_ssl = 0;
827
828 if (recv(con->http.fd, buf, 1, MSG_PEEK) == 1 &&
829 (!buf[0] || !strchr("DGHOPT", buf[0])))
830 {
831 /*
832 * Encrypt this connection...
833 */
834
835 cupsdLogMessage(CUPSD_LOG_DEBUG2,
836 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
837 buf[0] & 255);
838
411affcf 839 if (!encrypt_client(con))
f7deaa1a 840 cupsdCloseClient(con);
411affcf 841
f7deaa1a 842 return;
ef416fc2 843 }
844 }
845#endif /* HAVE_SSL */
846
847 switch (con->http.state)
848 {
849 case HTTP_WAITING :
850 /*
851 * See if we've received a request line...
852 */
853
854 if (httpGets(line, sizeof(line) - 1, HTTP(con)) == NULL)
855 {
856 cupsdLogMessage(CUPSD_LOG_DEBUG2,
857 "cupsdReadClient: httpGets returned EOF...");
f7deaa1a 858 cupsdCloseClient(con);
859 return;
ef416fc2 860 }
861
862 /*
863 * Ignore blank request lines...
864 */
865
866 if (line[0] == '\0')
867 break;
868
869 /*
870 * Clear other state variables...
871 */
872
873 httpClearFields(HTTP(con));
874
875 con->http.activity = time(NULL);
876 con->http.version = HTTP_1_0;
877 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
878 con->http.data_encoding = HTTP_ENCODE_LENGTH;
879 con->http.data_remaining = 0;
880 con->http._data_remaining = 0;
881 con->operation = HTTP_WAITING;
882 con->bytes = 0;
883 con->file = -1;
884 con->file_ready = 0;
885 con->pipe_pid = 0;
886 con->username[0] = '\0';
887 con->password[0] = '\0';
888 con->uri[0] = '\0';
889
890 cupsdClearString(&con->command);
891 cupsdClearString(&con->options);
b86bc4cf 892 cupsdClearString(&con->query_string);
ef416fc2 893
2abf387c 894 if (con->request)
895 {
896 ippDelete(con->request);
897 con->request = NULL;
898 }
899
900 if (con->response)
901 {
902 ippDelete(con->response);
903 con->response = NULL;
904 }
905
906 if (con->language)
ef416fc2 907 {
908 cupsLangFree(con->language);
909 con->language = NULL;
910 }
911
09a101d6 912#ifdef HAVE_GSSAPI
913 con->gss_have_creds = 0;
914#endif /* HAVE_GSSAPI */
915
ef416fc2 916 /*
917 * Grab the request line...
918 */
919
920 switch (sscanf(line, "%63s%1023s%63s", operation, con->uri, version))
921 {
922 case 1 :
c934a06c
MS
923 if (line[0])
924 {
925 cupsdLogMessage(CUPSD_LOG_ERROR,
926 "Bad request line \"%s\" from %s!", line,
927 con->http.hostname);
928 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
929 cupsdCloseClient(con);
930 }
f7deaa1a 931 return;
ef416fc2 932 case 2 :
933 con->http.version = HTTP_0_9;
934 break;
935 case 3 :
936 if (sscanf(version, "HTTP/%d.%d", &major, &minor) != 2)
937 {
938 cupsdLogMessage(CUPSD_LOG_ERROR,
939 "Bad request line \"%s\" from %s!", line,
940 con->http.hostname);
5bd77a73 941 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 942 cupsdCloseClient(con);
943 return;
ef416fc2 944 }
945
946 if (major < 2)
947 {
948 con->http.version = (http_version_t)(major * 100 + minor);
949 if (con->http.version == HTTP_1_1 && KeepAlive)
950 con->http.keep_alive = HTTP_KEEPALIVE_ON;
951 else
952 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
953 }
954 else
955 {
5bd77a73 956 cupsdSendError(con, HTTP_NOT_SUPPORTED, CUPSD_AUTH_NONE);
f7deaa1a 957 cupsdCloseClient(con);
958 return;
ef416fc2 959 }
960 break;
961 }
962
963 /*
964 * Handle full URLs in the request line...
965 */
966
967 if (strcmp(con->uri, "*"))
968 {
e6013cfa 969 char scheme[HTTP_MAX_URI], /* Method/scheme */
ef416fc2 970 userpass[HTTP_MAX_URI], /* Username:password */
971 hostname[HTTP_MAX_URI], /* Hostname */
972 resource[HTTP_MAX_URI]; /* Resource path */
973 int port; /* Port number */
974
975
976 /*
977 * Separate the URI into its components...
978 */
979
a4d04587 980 httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
e6013cfa 981 scheme, sizeof(scheme),
ef416fc2 982 userpass, sizeof(userpass),
983 hostname, sizeof(hostname), &port,
984 resource, sizeof(resource));
985
986 /*
987 * Only allow URIs with the servername, localhost, or an IP
988 * address...
989 */
990
e6013cfa 991 if (strcmp(scheme, "file") &&
ef416fc2 992 strcasecmp(hostname, ServerName) &&
993 strcasecmp(hostname, "localhost") &&
e6013cfa 994 !isdigit(hostname[0]) && hostname[0] != '[')
ef416fc2 995 {
996 /*
997 * Nope, we don't do proxies...
998 */
999
1000 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad URI \"%s\" in request!",
1001 con->uri);
5bd77a73 1002 cupsdSendError(con, HTTP_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
f7deaa1a 1003 cupsdCloseClient(con);
1004 return;
ef416fc2 1005 }
1006
1007 /*
1008 * Copy the resource portion back into the URI; both resource and
1009 * con->uri are HTTP_MAX_URI bytes in size...
1010 */
1011
1012 strcpy(con->uri, resource);
1013 }
1014
1015 /*
1016 * Process the request...
1017 */
1018
1019 if (!strcmp(operation, "GET"))
1020 con->http.state = HTTP_GET;
1021 else if (!strcmp(operation, "PUT"))
1022 con->http.state = HTTP_PUT;
1023 else if (!strcmp(operation, "POST"))
1024 con->http.state = HTTP_POST;
1025 else if (!strcmp(operation, "DELETE"))
1026 con->http.state = HTTP_DELETE;
1027 else if (!strcmp(operation, "TRACE"))
1028 con->http.state = HTTP_TRACE;
1029 else if (!strcmp(operation, "OPTIONS"))
1030 con->http.state = HTTP_OPTIONS;
1031 else if (!strcmp(operation, "HEAD"))
1032 con->http.state = HTTP_HEAD;
1033 else
1034 {
1035 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad operation \"%s\"!", operation);
5bd77a73 1036 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 1037 cupsdCloseClient(con);
1038 return;
ef416fc2 1039 }
1040
1041 con->start = time(NULL);
1042 con->operation = con->http.state;
1043
89d46774 1044 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1045 con->http.fd, operation, con->uri,
ef416fc2 1046 con->http.version / 100, con->http.version % 100);
1047
1048 con->http.status = HTTP_OK;
1049
49d87452
MS
1050 if (!cupsArrayFind(ActiveClients, con))
1051 {
1052 cupsArrayAdd(ActiveClients, con);
1053 cupsdSetBusyState();
1054 }
3dfe78b3 1055
ef416fc2 1056 case HTTP_OPTIONS :
1057 case HTTP_DELETE :
1058 case HTTP_GET :
1059 case HTTP_HEAD :
1060 case HTTP_POST :
1061 case HTTP_PUT :
1062 case HTTP_TRACE :
1063 /*
1064 * Parse incoming parameters until the status changes...
1065 */
1066
f7deaa1a 1067 while ((status = httpUpdate(HTTP(con))) == HTTP_CONTINUE)
ee571f26 1068 if (!data_ready(con))
f7deaa1a 1069 break;
ef416fc2 1070
1071 if (status != HTTP_OK && status != HTTP_CONTINUE)
1072 {
5bd77a73 1073 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 1074 cupsdCloseClient(con);
1075 return;
ef416fc2 1076 }
1077 break;
1078
1079 default :
e6013cfa
MS
1080 if (!data_ready(con) && recv(con->http.fd, buf, 1, MSG_PEEK) < 1)
1081 {
1082 /*
1083 * Connection closed...
1084 */
1085
1086 cupsdCloseClient(con);
1087 return;
1088 }
ef416fc2 1089 break; /* Anti-compiler-warning-code */
1090 }
1091
1092 /*
1093 * Handle new transfers...
1094 */
1095
1096 if (status == HTTP_OK)
1097 {
1098 if (con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE][0])
1099 {
1100 /*
1101 * Figure out the locale from the Accept-Language and Content-Type
1102 * fields...
1103 */
1104
1105 if ((ptr = strchr(con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ',')) != NULL)
1106 *ptr = '\0';
1107
1108 if ((ptr = strchr(con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ';')) != NULL)
1109 *ptr = '\0';
1110
1111 if ((ptr = strstr(con->http.fields[HTTP_FIELD_CONTENT_TYPE], "charset=")) != NULL)
1112 {
1113 /*
1114 * Combine language and charset, and trim any extra params in the
1115 * content-type.
1116 */
1117
1118 snprintf(locale, sizeof(locale), "%s.%s",
1119 con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], ptr + 8);
1120
1121 if ((ptr = strchr(locale, ',')) != NULL)
1122 *ptr = '\0';
1123 }
1124 else
1125 snprintf(locale, sizeof(locale), "%s.%s",
1126 con->http.fields[HTTP_FIELD_ACCEPT_LANGUAGE], DefaultCharset);
d6ae789d 1127
355e94dc 1128 cupsdLogMessage(CUPSD_LOG_DEBUG2,
89d46774 1129 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1130 con->http.fd, locale);
1131
ef416fc2 1132 con->language = cupsLangGet(locale);
1133 }
1134 else
1135 con->language = cupsLangGet(DefaultLocale);
1136
1137 cupsdAuthorize(con);
1138
52f6f666 1139 if (!strncasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Keep-Alive", 10) &&
ef416fc2 1140 KeepAlive)
1141 con->http.keep_alive = HTTP_KEEPALIVE_ON;
52f6f666
MS
1142 else if (!strncasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "close", 5))
1143 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
ef416fc2 1144
1145 if (!con->http.fields[HTTP_FIELD_HOST][0] &&
1146 con->http.version >= HTTP_1_1)
1147 {
1148 /*
1149 * HTTP/1.1 and higher require the "Host:" field...
1150 */
1151
5bd77a73 1152 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
f7deaa1a 1153 {
1154 cupsdCloseClient(con);
1155 return;
1156 }
ef416fc2 1157 }
e6013cfa
MS
1158 else if (httpAddrLocalhost(con->http.hostaddr) &&
1159 strcasecmp(con->http.fields[HTTP_FIELD_HOST], "localhost") &&
1160 strncasecmp(con->http.fields[HTTP_FIELD_HOST], "localhost:", 10) &&
1161 strcmp(con->http.fields[HTTP_FIELD_HOST], "127.0.0.1") &&
1162 strncmp(con->http.fields[HTTP_FIELD_HOST], "127.0.0.1:", 10) &&
1163 strcmp(con->http.fields[HTTP_FIELD_HOST], "[::1]") &&
1164 strncmp(con->http.fields[HTTP_FIELD_HOST], "[::1]:", 6))
1165 {
1166 /*
1167 * Access to localhost must use "localhost" or the corresponding IPv4
1168 * or IPv6 values in the Host: field.
1169 */
1170
1171 cupsdLogMessage(CUPSD_LOG_WARN,
1172 "Request from \"%s\" using invalid Host: field \"%s\"",
1173 con->http.hostname, con->http.fields[HTTP_FIELD_HOST]);
1174
1175 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
1176 {
1177 cupsdCloseClient(con);
1178 return;
1179 }
1180 }
ef416fc2 1181 else if (con->operation == HTTP_OPTIONS)
1182 {
1183 /*
1184 * Do OPTIONS command...
1185 */
1186
5bd77a73 1187 if (con->best && con->best->type != CUPSD_AUTH_NONE)
ef416fc2 1188 {
5bd77a73 1189 if (!cupsdSendHeader(con, HTTP_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1190 {
1191 cupsdCloseClient(con);
1192 return;
1193 }
ef416fc2 1194 }
1195
1196 if (!strcasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Upgrade") &&
1197 con->http.tls == NULL)
1198 {
1199#ifdef HAVE_SSL
1200 /*
1201 * Do encryption stuff...
1202 */
1203
5bd77a73 1204 if (!cupsdSendHeader(con, HTTP_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1205 {
1206 cupsdCloseClient(con);
1207 return;
1208 }
ef416fc2 1209
1210 httpPrintf(HTTP(con), "Connection: Upgrade\r\n");
1211 httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1212 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1213 httpPrintf(HTTP(con), "\r\n");
07725fee 1214
1215 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1216 {
1217 cupsdCloseClient(con);
1218 return;
1219 }
ef416fc2 1220
411affcf 1221 if (!encrypt_client(con))
f7deaa1a 1222 {
1223 cupsdCloseClient(con);
1224 return;
1225 }
ef416fc2 1226#else
5bd77a73 1227 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
f7deaa1a 1228 {
1229 cupsdCloseClient(con);
1230 return;
1231 }
ef416fc2 1232#endif /* HAVE_SSL */
1233 }
1234
5bd77a73 1235 if (!cupsdSendHeader(con, HTTP_OK, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1236 {
1237 cupsdCloseClient(con);
1238 return;
1239 }
ef416fc2 1240
1241 httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1242 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1243 httpPrintf(HTTP(con), "\r\n");
07725fee 1244
1245 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1246 {
1247 cupsdCloseClient(con);
1248 return;
1249 }
ef416fc2 1250 }
1251 else if (!is_path_absolute(con->uri))
1252 {
1253 /*
1254 * Protect against malicious users!
1255 */
1256
5bd77a73 1257 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1258 {
1259 cupsdCloseClient(con);
1260 return;
1261 }
ef416fc2 1262 }
1263 else
1264 {
1265 if (!strcasecmp(con->http.fields[HTTP_FIELD_CONNECTION], "Upgrade") &&
1266 con->http.tls == NULL)
1267 {
1268#ifdef HAVE_SSL
1269 /*
1270 * Do encryption stuff...
1271 */
1272
5bd77a73 1273 if (!cupsdSendHeader(con, HTTP_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1274 {
1275 cupsdCloseClient(con);
1276 return;
1277 }
ef416fc2 1278
1279 httpPrintf(HTTP(con), "Connection: Upgrade\r\n");
1280 httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1281 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1282 httpPrintf(HTTP(con), "\r\n");
07725fee 1283
1284 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1285 {
1286 cupsdCloseClient(con);
1287 return;
1288 }
ef416fc2 1289
411affcf 1290 if (!encrypt_client(con))
f7deaa1a 1291 {
1292 cupsdCloseClient(con);
1293 return;
1294 }
ef416fc2 1295#else
5bd77a73 1296 if (!cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
f7deaa1a 1297 {
1298 cupsdCloseClient(con);
1299 return;
1300 }
ef416fc2 1301#endif /* HAVE_SSL */
1302 }
1303
1304 if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_OK)
1305 {
1306 cupsdLogMessage(CUPSD_LOG_DEBUG2,
75bd9771 1307 "cupsdReadClient: Unauthorized request for %s...",
ef416fc2 1308 con->uri);
5bd77a73 1309 cupsdSendError(con, status, CUPSD_AUTH_NONE);
f7deaa1a 1310 cupsdCloseClient(con);
1311 return;
ef416fc2 1312 }
1313
b423cd4c 1314 if (con->http.expect &&
1315 (con->operation == HTTP_POST || con->operation == HTTP_PUT))
ef416fc2 1316 {
b423cd4c 1317 if (con->http.expect == HTTP_CONTINUE)
1318 {
1319 /*
1320 * Send 100-continue header...
1321 */
1322
5bd77a73 1323 if (!cupsdSendHeader(con, HTTP_CONTINUE, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1324 {
1325 cupsdCloseClient(con);
1326 return;
1327 }
b423cd4c 1328 }
1329 else
1330 {
1331 /*
1332 * Send 417-expectation-failed header...
1333 */
1334
5bd77a73 1335 if (!cupsdSendHeader(con, HTTP_EXPECTATION_FAILED, NULL, CUPSD_AUTH_NONE))
f7deaa1a 1336 {
1337 cupsdCloseClient(con);
1338 return;
1339 }
b423cd4c 1340
1341 httpPrintf(HTTP(con), "Content-Length: 0\r\n");
1342 httpPrintf(HTTP(con), "\r\n");
07725fee 1343
1344 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1345 {
1346 cupsdCloseClient(con);
1347 return;
1348 }
b423cd4c 1349 }
ef416fc2 1350 }
1351
1352 switch (con->http.state)
1353 {
1354 case HTTP_GET_SEND :
1355 if (!strncmp(con->uri, "/printers/", 10) &&
1356 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1357 {
1358 /*
1359 * Send PPD file - get the real printer name since printer
1360 * names are not case sensitive but filenames can be...
1361 */
1362
1363 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1364
1365 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1366 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1367 else
1368 {
5bd77a73 1369 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1370 {
1371 cupsdCloseClient(con);
1372 return;
1373 }
ef416fc2 1374
1375 break;
1376 }
1377 }
1378
1379 if ((!strncmp(con->uri, "/admin", 6) &&
1380 strncmp(con->uri, "/admin/conf/", 12) &&
1381 strncmp(con->uri, "/admin/log/", 11)) ||
1382 !strncmp(con->uri, "/printers", 9) ||
1383 !strncmp(con->uri, "/classes", 8) ||
1384 !strncmp(con->uri, "/help", 5) ||
1385 !strncmp(con->uri, "/jobs", 5))
1386 {
1387 /*
1388 * Send CGI output...
1389 */
1390
1391 if (!strncmp(con->uri, "/admin", 6))
1392 {
1393 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1394 ServerBin);
1395
b423cd4c 1396 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
ef416fc2 1397 }
1398 else if (!strncmp(con->uri, "/printers", 9))
1399 {
1400 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1401 ServerBin);
b423cd4c 1402
1403 if (con->uri[9] && con->uri[10])
1404 cupsdSetString(&con->options, con->uri + 9);
1405 else
1406 cupsdSetString(&con->options, NULL);
ef416fc2 1407 }
1408 else if (!strncmp(con->uri, "/classes", 8))
1409 {
1410 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1411 ServerBin);
b423cd4c 1412
1413 if (con->uri[8] && con->uri[9])
1414 cupsdSetString(&con->options, con->uri + 8);
1415 else
1416 cupsdSetString(&con->options, NULL);
ef416fc2 1417 }
1418 else if (!strncmp(con->uri, "/jobs", 5))
1419 {
1420 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1421 ServerBin);
b423cd4c 1422
1423 if (con->uri[5] && con->uri[6])
1424 cupsdSetString(&con->options, con->uri + 5);
1425 else
1426 cupsdSetString(&con->options, NULL);
ef416fc2 1427 }
1428 else
1429 {
1430 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1431 ServerBin);
ef416fc2 1432
b423cd4c 1433 if (con->uri[5] && con->uri[6])
1434 cupsdSetString(&con->options, con->uri + 5);
1435 else
1436 cupsdSetString(&con->options, NULL);
1437 }
ef416fc2 1438
1439 if (!cupsdSendCommand(con, con->command, con->options, 0))
1440 {
5bd77a73 1441 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1442 {
1443 cupsdCloseClient(con);
1444 return;
1445 }
ef416fc2 1446 }
1447 else
1448 cupsdLogRequest(con, HTTP_OK);
1449
1450 if (con->http.version <= HTTP_1_0)
1451 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1452 }
1453 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1454 (strchr(con->uri + 12, '/') ||
1455 strlen(con->uri) == 12)) ||
1456 (!strncmp(con->uri, "/admin/log/", 11) &&
1457 (strchr(con->uri + 11, '/') ||
1458 strlen(con->uri) == 11)))
1459 {
1460 /*
1461 * GET can only be done to configuration files under
1462 * /admin/conf...
1463 */
1464
5bd77a73 1465 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1466 {
1467 cupsdCloseClient(con);
1468 return;
1469 }
ef416fc2 1470
1471 break;
1472 }
1473 else
1474 {
1475 /*
1476 * Serve a file...
1477 */
1478
1479 if ((filename = get_file(con, &filestats, buf,
1480 sizeof(buf))) == NULL)
1481 {
5bd77a73 1482 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1483 {
1484 cupsdCloseClient(con);
1485 return;
1486 }
ef416fc2 1487
1488 break;
1489 }
1490
4400e98d 1491 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
ef416fc2 1492
e1d6a774 1493 if (is_cgi(con, filename, &filestats, type))
ef416fc2 1494 {
1495 /*
1496 * Note: con->command and con->options were set by
e1d6a774 1497 * is_cgi()...
ef416fc2 1498 */
1499
1500 if (!cupsdSendCommand(con, con->command, con->options, 0))
1501 {
5bd77a73 1502 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1503 {
1504 cupsdCloseClient(con);
1505 return;
1506 }
ef416fc2 1507 }
1508 else
1509 cupsdLogRequest(con, HTTP_OK);
1510
1511 if (con->http.version <= HTTP_1_0)
1512 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1513 break;
1514 }
1515
1516 if (!check_if_modified(con, &filestats))
1517 {
5bd77a73 1518 if (!cupsdSendError(con, HTTP_NOT_MODIFIED, CUPSD_AUTH_NONE))
f7deaa1a 1519 {
1520 cupsdCloseClient(con);
1521 return;
1522 }
ef416fc2 1523 }
1524 else
1525 {
1526 if (type == NULL)
1527 strcpy(line, "text/plain");
1528 else
1529 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1530
a74454a7 1531 if (!write_file(con, HTTP_OK, filename, line, &filestats))
f7deaa1a 1532 {
1533 cupsdCloseClient(con);
1534 return;
1535 }
ef416fc2 1536 }
1537 }
1538 break;
1539
1540 case HTTP_POST_RECV :
1541 /*
1542 * See if the POST request includes a Content-Length field, and if
1543 * so check the length against any limits that are set...
1544 */
1545
1546 cupsdLogMessage(CUPSD_LOG_DEBUG2, "POST %s", con->uri);
1547 cupsdLogMessage(CUPSD_LOG_DEBUG2, "CONTENT_TYPE = %s",
1548 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
1549
1550 if (con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1551 MaxRequestSize > 0 &&
1552 con->http.data_remaining > MaxRequestSize)
1553 {
1554 /*
1555 * Request too large...
1556 */
1557
5bd77a73 1558 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1559 {
1560 cupsdCloseClient(con);
1561 return;
1562 }
ef416fc2 1563
1564 break;
1565 }
839a51c8
MS
1566 else if (con->http.data_remaining < 0 ||
1567 (!con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1568 con->http.data_encoding == HTTP_ENCODE_LENGTH))
ef416fc2 1569 {
1570 /*
1571 * Negative content lengths are invalid!
1572 */
1573
5bd77a73 1574 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
f7deaa1a 1575 {
1576 cupsdCloseClient(con);
1577 return;
1578 }
ef416fc2 1579
1580 break;
1581 }
1582
1583 /*
1584 * See what kind of POST request this is; for IPP requests the
1585 * content-type field will be "application/ipp"...
1586 */
1587
1588 if (!strcmp(con->http.fields[HTTP_FIELD_CONTENT_TYPE],
1589 "application/ipp"))
1590 con->request = ippNew();
1591 else if ((!strncmp(con->uri, "/admin", 6) &&
1592 strncmp(con->uri, "/admin/conf/", 12) &&
1593 strncmp(con->uri, "/admin/log/", 11)) ||
1594 !strncmp(con->uri, "/printers", 9) ||
1595 !strncmp(con->uri, "/classes", 8) ||
1596 !strncmp(con->uri, "/help", 5) ||
1597 !strncmp(con->uri, "/jobs", 5))
1598 {
1599 /*
1600 * CGI request...
1601 */
1602
1603 if (!strncmp(con->uri, "/admin", 6))
1604 {
1605 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1606 ServerBin);
1607
b423cd4c 1608 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
ef416fc2 1609 }
1610 else if (!strncmp(con->uri, "/printers", 9))
1611 {
1612 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1613 ServerBin);
b423cd4c 1614
1615 if (con->uri[9] && con->uri[10])
1616 cupsdSetString(&con->options, con->uri + 9);
1617 else
1618 cupsdSetString(&con->options, NULL);
ef416fc2 1619 }
1620 else if (!strncmp(con->uri, "/classes", 8))
1621 {
1622 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1623 ServerBin);
b423cd4c 1624
1625 if (con->uri[8] && con->uri[9])
1626 cupsdSetString(&con->options, con->uri + 8);
1627 else
1628 cupsdSetString(&con->options, NULL);
ef416fc2 1629 }
1630 else if (!strncmp(con->uri, "/jobs", 5))
1631 {
1632 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1633 ServerBin);
b423cd4c 1634
1635 if (con->uri[5] && con->uri[6])
1636 cupsdSetString(&con->options, con->uri + 5);
1637 else
1638 cupsdSetString(&con->options, NULL);
ef416fc2 1639 }
1640 else
1641 {
1642 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1643 ServerBin);
ef416fc2 1644
b423cd4c 1645 if (con->uri[5] && con->uri[6])
1646 cupsdSetString(&con->options, con->uri + 5);
1647 else
1648 cupsdSetString(&con->options, NULL);
1649 }
ef416fc2 1650
1651 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b423cd4c 1652 "cupsdReadClient: %d command=\"%s\", "
1653 "options = \"%s\"",
f301802f 1654 con->http.fd, con->command,
1655 con->options ? con->options : "(null)");
ef416fc2 1656
1657 if (con->http.version <= HTTP_1_0)
1658 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
1659 }
1660 else
1661 {
1662 /*
1663 * POST to a file...
1664 */
1665
1666 if ((filename = get_file(con, &filestats, buf,
1667 sizeof(buf))) == NULL)
1668 {
5bd77a73 1669 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1670 {
1671 cupsdCloseClient(con);
1672 return;
1673 }
ef416fc2 1674
1675 break;
1676 }
1677
4400e98d 1678 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
ef416fc2 1679
e1d6a774 1680 if (!is_cgi(con, filename, &filestats, type))
ef416fc2 1681 {
1682 /*
1683 * Only POST to CGI's...
1684 */
1685
5bd77a73 1686 if (!cupsdSendError(con, HTTP_UNAUTHORIZED, CUPSD_AUTH_NONE))
f7deaa1a 1687 {
1688 cupsdCloseClient(con);
1689 return;
1690 }
ef416fc2 1691 }
1692 }
1693 break;
1694
1695 case HTTP_PUT_RECV :
1696 /*
1697 * Validate the resource name...
1698 */
1699
1700 if (strncmp(con->uri, "/admin/conf/", 12) ||
1701 strchr(con->uri + 12, '/') ||
1702 strlen(con->uri) == 12)
1703 {
1704 /*
1705 * PUT can only be done to configuration files under
1706 * /admin/conf...
1707 */
1708
5bd77a73 1709 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1710 {
1711 cupsdCloseClient(con);
1712 return;
1713 }
ef416fc2 1714
1715 break;
1716 }
1717
1718 /*
1719 * See if the PUT request includes a Content-Length field, and if
1720 * so check the length against any limits that are set...
1721 */
1722
1723 cupsdLogMessage(CUPSD_LOG_DEBUG2, "PUT %s", con->uri);
1724 cupsdLogMessage(CUPSD_LOG_DEBUG2, "CONTENT_TYPE = %s",
1725 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
1726
1727 if (con->http.fields[HTTP_FIELD_CONTENT_LENGTH][0] &&
1728 MaxRequestSize > 0 &&
1729 con->http.data_remaining > MaxRequestSize)
1730 {
1731 /*
1732 * Request too large...
1733 */
1734
5bd77a73 1735 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1736 {
1737 cupsdCloseClient(con);
1738 return;
1739 }
ef416fc2 1740
1741 break;
1742 }
1743 else if (con->http.data_remaining < 0)
1744 {
1745 /*
1746 * Negative content lengths are invalid!
1747 */
1748
5bd77a73 1749 if (!cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE))
f7deaa1a 1750 {
1751 cupsdCloseClient(con);
1752 return;
1753 }
ef416fc2 1754
1755 break;
1756 }
1757
1758 /*
1759 * Open a temporary file to hold the request...
1760 */
1761
1762 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1763 request_id ++);
1764 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1765
ef416fc2 1766 if (con->file < 0)
1767 {
a4924f6c
MS
1768 cupsdLogMessage(CUPSD_LOG_ERROR,
1769 "Unable to create request file %s: %s",
1770 con->filename, strerror(errno));
1771
5bd77a73 1772 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1773 {
1774 cupsdCloseClient(con);
1775 return;
1776 }
ef416fc2 1777 }
1778
a4924f6c
MS
1779 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1780 "cupsdReadClient: %d REQUEST %s=%d", con->http.fd,
1781 con->filename, con->file);
1782
ef416fc2 1783 fchmod(con->file, 0640);
1784 fchown(con->file, RunUser, Group);
1785 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1786 break;
1787
1788 case HTTP_DELETE :
1789 case HTTP_TRACE :
5bd77a73 1790 cupsdSendError(con, HTTP_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);
f7deaa1a 1791 cupsdCloseClient(con);
1792 return;
ef416fc2 1793
1794 case HTTP_HEAD :
1795 if (!strncmp(con->uri, "/printers/", 10) &&
1796 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1797 {
1798 /*
1799 * Send PPD file - get the real printer name since printer
1800 * names are not case sensitive but filenames can be...
1801 */
1802
1803 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1804
1805 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1806 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1807 else
1808 {
5bd77a73 1809 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 1810 {
1811 cupsdCloseClient(con);
1812 return;
1813 }
ef416fc2 1814
1815 break;
1816 }
1817 }
1818
1819 if ((!strncmp(con->uri, "/admin", 6) &&
1820 strncmp(con->uri, "/admin/conf/", 12) &&
1821 strncmp(con->uri, "/admin/log/", 11)) ||
1822 !strncmp(con->uri, "/printers", 9) ||
1823 !strncmp(con->uri, "/classes", 8) ||
1824 !strncmp(con->uri, "/help", 5) ||
1825 !strncmp(con->uri, "/jobs", 5))
1826 {
1827 /*
1828 * CGI output...
1829 */
1830
5bd77a73 1831 if (!cupsdSendHeader(con, HTTP_OK, "text/html", CUPSD_AUTH_NONE))
f7deaa1a 1832 {
1833 cupsdCloseClient(con);
1834 return;
1835 }
ef416fc2 1836
1837 if (httpPrintf(HTTP(con), "\r\n") < 0)
f7deaa1a 1838 {
1839 cupsdCloseClient(con);
1840 return;
1841 }
ef416fc2 1842
07725fee 1843 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1844 {
1845 cupsdCloseClient(con);
1846 return;
1847 }
d09495fa 1848
ef416fc2 1849 cupsdLogRequest(con, HTTP_OK);
1850 }
1851 else if ((!strncmp(con->uri, "/admin/conf/", 12) &&
1852 (strchr(con->uri + 12, '/') ||
1853 strlen(con->uri) == 12)) ||
1854 (!strncmp(con->uri, "/admin/log/", 11) &&
1855 (strchr(con->uri + 11, '/') ||
1856 strlen(con->uri) == 11)))
1857 {
1858 /*
1859 * HEAD can only be done to configuration files under
1860 * /admin/conf...
1861 */
1862
5bd77a73 1863 if (!cupsdSendError(con, HTTP_FORBIDDEN, CUPSD_AUTH_NONE))
f7deaa1a 1864 {
1865 cupsdCloseClient(con);
1866 return;
1867 }
ef416fc2 1868
1869 break;
1870 }
1871 else if ((filename = get_file(con, &filestats, buf,
1872 sizeof(buf))) == NULL)
1873 {
5bd77a73 1874 if (!cupsdSendHeader(con, HTTP_NOT_FOUND, "text/html", CUPSD_AUTH_NONE))
f7deaa1a 1875 {
1876 cupsdCloseClient(con);
1877 return;
1878 }
ef416fc2 1879
1880 cupsdLogRequest(con, HTTP_NOT_FOUND);
1881 }
1882 else if (!check_if_modified(con, &filestats))
1883 {
5bd77a73 1884 if (!cupsdSendError(con, HTTP_NOT_MODIFIED, CUPSD_AUTH_NONE))
f7deaa1a 1885 {
1886 cupsdCloseClient(con);
1887 return;
1888 }
ef416fc2 1889
1890 cupsdLogRequest(con, HTTP_NOT_MODIFIED);
1891 }
1892 else
1893 {
1894 /*
1895 * Serve a file...
1896 */
1897
4400e98d 1898 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
ef416fc2 1899 if (type == NULL)
1900 strcpy(line, "text/plain");
1901 else
1902 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1903
5bd77a73 1904 if (!cupsdSendHeader(con, HTTP_OK, line, CUPSD_AUTH_NONE))
f7deaa1a 1905 {
1906 cupsdCloseClient(con);
1907 return;
1908 }
ef416fc2 1909
1910 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
1911 httpGetDateString(filestats.st_mtime)) < 0)
f7deaa1a 1912 {
1913 cupsdCloseClient(con);
1914 return;
1915 }
ef416fc2 1916
1917 if (httpPrintf(HTTP(con), "Content-Length: %lu\r\n",
1918 (unsigned long)filestats.st_size) < 0)
f7deaa1a 1919 {
1920 cupsdCloseClient(con);
1921 return;
1922 }
ef416fc2 1923
1924 cupsdLogRequest(con, HTTP_OK);
1925 }
1926
1927 if (httpPrintf(HTTP(con), "\r\n") < 0)
f7deaa1a 1928 {
1929 cupsdCloseClient(con);
1930 return;
1931 }
ef416fc2 1932
07725fee 1933 if (cupsdFlushHeader(con) < 0)
f7deaa1a 1934 {
1935 cupsdCloseClient(con);
1936 return;
1937 }
d09495fa 1938
ef416fc2 1939 con->http.state = HTTP_WAITING;
1940 break;
1941
1942 default :
1943 break; /* Anti-compiler-warning-code */
1944 }
1945 }
1946 }
1947
1948 /*
1949 * Handle any incoming data...
1950 */
1951
1952 switch (con->http.state)
1953 {
1954 case HTTP_PUT_RECV :
1955 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1956 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1957 "con->data_remaining=" CUPS_LLFMT ", con->file=%d",
1958 con->http.fd,
1959 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
1960 "CHUNKED" : "LENGTH",
1961 CUPS_LLCAST con->http.data_remaining, con->file);
1962
f7deaa1a 1963 do
ef416fc2 1964 {
f7deaa1a 1965 if ((bytes = httpRead2(HTTP(con), line, sizeof(line))) < 0)
1966 {
1967 cupsdCloseClient(con);
1968 return;
1969 }
1970 else if (bytes > 0)
1971 {
1972 con->bytes += bytes;
ef416fc2 1973
f7deaa1a 1974 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1975 "cupsdReadClient: %d writing %d bytes to %d",
1976 con->http.fd, bytes, con->file);
ef416fc2 1977
f7deaa1a 1978 if (write(con->file, line, bytes) < bytes)
1979 {
1980 cupsdLogMessage(CUPSD_LOG_ERROR,
1981 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1982 bytes, con->filename, strerror(errno));
ef416fc2 1983
f7deaa1a 1984 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1985 "cupsdReadClient: Closing data file %d...",
1986 con->file);
ef416fc2 1987
f7deaa1a 1988 close(con->file);
1989 con->file = -1;
1990 unlink(con->filename);
1991 cupsdClearString(&con->filename);
ef416fc2 1992
5bd77a73 1993 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 1994 {
1995 cupsdCloseClient(con);
1996 return;
1997 }
1998 }
ef416fc2 1999 }
f7deaa1a 2000 }
ee571f26 2001 while (con->http.state == HTTP_PUT_RECV && data_ready(con));
ef416fc2 2002
2003 if (con->http.state == HTTP_WAITING)
2004 {
2005 /*
2006 * End of file, see how big it is...
2007 */
2008
2009 fstat(con->file, &filestats);
2010
2011 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2012 "cupsdReadClient: %d Closing data file %d, size="
2013 CUPS_LLFMT ".",
2014 con->http.fd, con->file,
2015 CUPS_LLCAST filestats.st_size);
2016
2017 close(con->file);
2018 con->file = -1;
2019
2020 if (filestats.st_size > MaxRequestSize &&
2021 MaxRequestSize > 0)
2022 {
2023 /*
2024 * Request is too big; remove it and send an error...
2025 */
2026
2027 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2028 "cupsdReadClient: %d Removing temp file %s",
2029 con->http.fd, con->filename);
2030 unlink(con->filename);
2031 cupsdClearString(&con->filename);
2032
5bd77a73 2033 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2034 {
2035 cupsdCloseClient(con);
2036 return;
2037 }
ef416fc2 2038 }
2039
2040 /*
2041 * Install the configuration file...
2042 */
2043
2044 status = install_conf_file(con);
2045
2046 /*
2047 * Return the status to the client...
2048 */
2049
5bd77a73 2050 if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))
f7deaa1a 2051 {
2052 cupsdCloseClient(con);
2053 return;
2054 }
ef416fc2 2055 }
2056 break;
2057
2058 case HTTP_POST_RECV :
2059 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2060 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2061 "%s, con->data_remaining=" CUPS_LLFMT ", con->file=%d",
2062 con->http.fd,
2063 con->http.data_encoding == HTTP_ENCODE_CHUNKED ?
2064 "CHUNKED" : "LENGTH",
2065 CUPS_LLCAST con->http.data_remaining, con->file);
2066
f7deaa1a 2067 do
ef416fc2 2068 {
f7deaa1a 2069 if (con->request)
ef416fc2 2070 {
f7deaa1a 2071 /*
2072 * Grab any request data from the connection...
2073 */
ef416fc2 2074
f7deaa1a 2075 if ((ipp_state = ippRead(&(con->http), con->request)) == IPP_ERROR)
ef416fc2 2076 {
f7deaa1a 2077 cupsdLogMessage(CUPSD_LOG_ERROR,
2078 "cupsdReadClient: %d IPP Read Error!",
2079 con->http.fd);
2080
5bd77a73 2081 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 2082 cupsdCloseClient(con);
2083 return;
ef416fc2 2084 }
f7deaa1a 2085 else if (ipp_state != IPP_DATA)
2086 {
2087 if (con->http.state == HTTP_POST_SEND)
2088 {
5bd77a73 2089 cupsdSendError(con, HTTP_BAD_REQUEST, CUPSD_AUTH_NONE);
f7deaa1a 2090 cupsdCloseClient(con);
2091 return;
2092 }
ef416fc2 2093
f7deaa1a 2094 break;
2095 }
2096 else
2097 con->bytes += ippLength(con->request);
2098 }
ef416fc2 2099
f7deaa1a 2100 if (con->file < 0 && con->http.state != HTTP_POST_SEND)
2101 {
2102 /*
2103 * Create a file as needed for the request data...
2104 */
ef416fc2 2105
f7deaa1a 2106 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot, request_id ++);
2107 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
ef416fc2 2108
f7deaa1a 2109 if (con->file < 0)
2110 {
a4924f6c
MS
2111 cupsdLogMessage(CUPSD_LOG_ERROR,
2112 "Unable to create request file %s: %s",
2113 con->filename, strerror(errno));
2114
5bd77a73 2115 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2116 {
2117 cupsdCloseClient(con);
2118 return;
2119 }
2120 }
ef416fc2 2121
a4924f6c
MS
2122 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadClient: %d REQUEST %s=%d", con->http.fd,
2123 con->filename, con->file);
2124
f7deaa1a 2125 fchmod(con->file, 0640);
2126 fchown(con->file, RunUser, Group);
2127 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2128 }
ef416fc2 2129
f7deaa1a 2130 if (con->http.state != HTTP_POST_SEND)
ef416fc2 2131 {
f7deaa1a 2132 if ((bytes = httpRead2(HTTP(con), line, sizeof(line))) < 0)
2133 {
2134 cupsdCloseClient(con);
2135 return;
2136 }
2137 else if (bytes > 0)
2138 {
2139 con->bytes += bytes;
ef416fc2 2140
f7deaa1a 2141 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2142 "cupsdReadClient: %d writing %d bytes to %d",
2143 con->http.fd, bytes, con->file);
ef416fc2 2144
f7deaa1a 2145 if (write(con->file, line, bytes) < bytes)
2146 {
2147 cupsdLogMessage(CUPSD_LOG_ERROR,
2148 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2149 bytes, con->filename, strerror(errno));
ef416fc2 2150
f7deaa1a 2151 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2152 "cupsdReadClient: Closing file %d...",
2153 con->file);
ef416fc2 2154
f7deaa1a 2155 close(con->file);
2156 con->file = -1;
2157 unlink(con->filename);
2158 cupsdClearString(&con->filename);
ef416fc2 2159
5bd77a73 2160 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2161 {
2162 cupsdCloseClient(con);
2163 return;
2164 }
2165 }
2166 }
2167 else if (con->http.state == HTTP_POST_RECV)
2168 return;
2169 else if (con->http.state != HTTP_POST_SEND)
2170 {
2171 cupsdCloseClient(con);
2172 return;
ef416fc2 2173 }
2174 }
f7deaa1a 2175 }
ee571f26 2176 while (con->http.state == HTTP_POST_RECV && data_ready(con));
ef416fc2 2177
2178 if (con->http.state == HTTP_POST_SEND)
2179 {
2180 if (con->file >= 0)
2181 {
2182 fstat(con->file, &filestats);
2183
2184 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2185 "cupsdReadClient: %d Closing data file %d, "
2186 "size=" CUPS_LLFMT ".",
2187 con->http.fd, con->file,
2188 CUPS_LLCAST filestats.st_size);
2189
2190 close(con->file);
2191 con->file = -1;
2192
2193 if (filestats.st_size > MaxRequestSize &&
2194 MaxRequestSize > 0)
2195 {
2196 /*
2197 * Request is too big; remove it and send an error...
2198 */
2199
2200 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2201 "cupsdReadClient: %d Removing temp file %s",
2202 con->http.fd, con->filename);
2203 unlink(con->filename);
2204 cupsdClearString(&con->filename);
2205
2206 if (con->request)
2207 {
2208 /*
2209 * Delete any IPP request data...
2210 */
2211
2212 ippDelete(con->request);
2213 con->request = NULL;
2214 }
2215
5bd77a73 2216 if (!cupsdSendError(con, HTTP_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
f7deaa1a 2217 {
2218 cupsdCloseClient(con);
2219 return;
2220 }
ef416fc2 2221 }
2222
2223 if (con->command)
2224 {
2225 if (!cupsdSendCommand(con, con->command, con->options, 0))
2226 {
5bd77a73 2227 if (!cupsdSendError(con, HTTP_NOT_FOUND, CUPSD_AUTH_NONE))
f7deaa1a 2228 {
2229 cupsdCloseClient(con);
2230 return;
2231 }
ef416fc2 2232 }
2233 else
2234 cupsdLogRequest(con, HTTP_OK);
2235 }
2236 }
2237
2238 if (con->request)
f7deaa1a 2239 {
2240 cupsdProcessIPPRequest(con);
bc44d920 2241
2242 if (con->filename)
2243 {
2244 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2245 "cupsdReadClient: %d Removing temp file %s",
2246 con->http.fd, con->filename);
2247 unlink(con->filename);
2248 cupsdClearString(&con->filename);
2249 }
2250
f7deaa1a 2251 return;
2252 }
ef416fc2 2253 }
2254 break;
2255
2256 default :
2257 break; /* Anti-compiler-warning-code */
2258 }
2259
3dfe78b3
MS
2260 if (con->http.state == HTTP_WAITING)
2261 {
2262 if (!con->http.keep_alive)
2263 cupsdCloseClient(con);
2264 else
2265 {
2266 cupsArrayRemove(ActiveClients, con);
2267 cupsdSetBusyState();
2268 }
2269 }
ef416fc2 2270}
2271
2272
2273/*
2274 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2275 */
2276
2277int /* O - 1 on success, 0 on failure */
2278cupsdSendCommand(
2279 cupsd_client_t *con, /* I - Client connection */
2280 char *command, /* I - Command to run */
2281 char *options, /* I - Command-line options */
2282 int root) /* I - Run as root? */
2283{
2284 int fd; /* Standard input file descriptor */
2285
2286
2287 if (con->filename)
ed486911 2288 {
ef416fc2 2289 fd = open(con->filename, O_RDONLY);
ef416fc2 2290
ed486911 2291 if (fd < 0)
2292 {
2293 cupsdLogMessage(CUPSD_LOG_ERROR,
2294 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2295 con->http.fd, con->filename ? con->filename : "/dev/null",
2296 strerror(errno));
2297 return (0);
2298 }
ef416fc2 2299
ed486911 2300 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
2301 }
2302 else
2303 fd = -1;
ef416fc2 2304
2305 con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
2306
ed486911 2307 if (fd >= 0)
2308 close(fd);
ef416fc2 2309
2310 cupsdLogMessage(CUPSD_LOG_INFO, "Started \"%s\" (pid=%d)", command,
2311 con->pipe_pid);
2312
2313 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendCommand: %d file=%d",
2314 con->http.fd, con->file);
2315
2316 if (con->pipe_pid == 0)
2317 return (0);
2318
2319 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2320
f899b121 2321 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
ef416fc2 2322
2323 con->sent_header = 0;
2324 con->file_ready = 0;
2325 con->got_fields = 0;
2326 con->field_col = 0;
2327
2328 return (1);
2329}
2330
2331
2332/*
2333 * 'cupsdSendError()' - Send an error message via HTTP.
2334 */
2335
2336int /* O - 1 if successful, 0 otherwise */
2337cupsdSendError(cupsd_client_t *con, /* I - Connection */
f899b121 2338 http_status_t code, /* I - Error code */
2339 int auth_type)/* I - Authentication type */
ef416fc2 2340{
4744bd90 2341#ifdef HAVE_SSL
2342 /*
2343 * Force client to upgrade for authentication if that is how the
2344 * server is configured...
2345 */
2346
2347 if (code == HTTP_UNAUTHORIZED &&
2348 DefaultEncryption == HTTP_ENCRYPT_REQUIRED &&
2349 strcasecmp(con->http.hostname, "localhost") &&
2350 !con->http.tls)
2351 {
2352 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2353 "cupsdSendError: Encryption before authentication!");
2354 code = HTTP_UPGRADE_REQUIRED;
2355 }
2356#endif /* HAVE_SSL */
2357
ef416fc2 2358 /*
2359 * Put the request in the access_log file...
2360 */
2361
2362 cupsdLogRequest(con, code);
2363
2364 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendError: %d code=%d (%s)",
2365 con->http.fd, code, httpStatus(code));
2366
2367 /*
2368 * To work around bugs in some proxies, don't use Keep-Alive for some
2369 * error messages...
f7deaa1a 2370 *
2371 * Kerberos authentication doesn't work without Keep-Alive, so
2372 * never disable it in that case.
ef416fc2 2373 */
2374
5bd77a73 2375 if (code >= HTTP_BAD_REQUEST && con->http.auth_type != CUPSD_AUTH_NEGOTIATE)
ef416fc2 2376 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
2377
2378 /*
2379 * Send an error message back to the client. If the error code is a
2380 * 400 or 500 series, make sure the message contains some text, too!
2381 */
2382
f899b121 2383 if (!cupsdSendHeader(con, code, NULL, auth_type))
ef416fc2 2384 return (0);
2385
2386#ifdef HAVE_SSL
2387 if (code == HTTP_UPGRADE_REQUIRED)
2388 if (httpPrintf(HTTP(con), "Connection: Upgrade\r\n") < 0)
2389 return (0);
2390
2391 if (httpPrintf(HTTP(con), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2392 return (0);
2393#endif /* HAVE_SSL */
2394
f7deaa1a 2395 if (con->http.version >= HTTP_1_1 &&
2396 con->http.keep_alive == HTTP_KEEPALIVE_OFF)
ef416fc2 2397 {
2398 if (httpPrintf(HTTP(con), "Connection: close\r\n") < 0)
2399 return (0);
2400 }
2401
2402 if (code >= HTTP_BAD_REQUEST)
2403 {
2404 /*
2405 * Send a human-readable error message.
2406 */
2407
80ca4592 2408 char message[4096], /* Message for user */
2409 urltext[1024], /* URL redirection text */
2410 redirect[1024]; /* Redirection link */
ef416fc2 2411 const char *text; /* Status-specific text */
2412
80ca4592 2413
2414 redirect[0] = '\0';
2415
ef416fc2 2416 if (code == HTTP_UNAUTHORIZED)
2417 text = _cupsLangString(con->language,
2418 _("Enter your username and password or the "
2419 "root username and password to access this "
f7deaa1a 2420 "page. If you are using Kerberos authentication, "
2421 "make sure you have a valid Kerberos ticket."));
ef416fc2 2422 else if (code == HTTP_UPGRADE_REQUIRED)
80ca4592 2423 {
2424 text = urltext;
2425
2426 snprintf(urltext, sizeof(urltext),
2427 _cupsLangString(con->language,
2428 _("You must access this page using the URL "
2429 "<A HREF=\"https://%s:%d%s\">"
2430 "https://%s:%d%s</A>.")),
2431 con->servername, con->serverport, con->uri,
2432 con->servername, con->serverport, con->uri);
2433
2434 snprintf(redirect, sizeof(redirect),
b86bc4cf 2435 "<META HTTP-EQUIV=\"Refresh\" "
2436 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
80ca4592 2437 con->servername, con->serverport, con->uri);
2438 }
ef416fc2 2439 else
2440 text = "";
2441
2442 snprintf(message, sizeof(message),
2443 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2444 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2445 "<HTML>\n"
2446 "<HEAD>\n"
2447 "\t<META HTTP-EQUIV=\"Content-Type\" "
2448 "CONTENT=\"text/html; charset=utf-8\">\n"
2449 "\t<TITLE>%d %s</TITLE>\n"
2450 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2451 "HREF=\"/cups.css\">\n"
80ca4592 2452 "%s"
ef416fc2 2453 "</HEAD>\n"
2454 "<BODY>\n"
2455 "<H1>%d %s</H1>\n"
2456 "<P>%s</P>\n"
2457 "</BODY>\n"
2458 "</HTML>\n",
80ca4592 2459 code, httpStatus(code), redirect, code, httpStatus(code), text);
ef416fc2 2460
2461 if (httpPrintf(HTTP(con), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2462 return (0);
2463 if (httpPrintf(HTTP(con), "Content-Length: %d\r\n",
2464 (int)strlen(message)) < 0)
2465 return (0);
2466 if (httpPrintf(HTTP(con), "\r\n") < 0)
2467 return (0);
2468 if (httpPrintf(HTTP(con), "%s", message) < 0)
2469 return (0);
2470 }
2471 else if (httpPrintf(HTTP(con), "\r\n") < 0)
2472 return (0);
2473
07725fee 2474 if (cupsdFlushHeader(con) < 0)
2475 return (0);
d09495fa 2476
ef416fc2 2477 con->http.state = HTTP_WAITING;
2478
2479 return (1);
2480}
2481
2482
ef416fc2 2483/*
2484 * 'cupsdSendHeader()' - Send an HTTP request.
2485 */
2486
2487int /* O - 1 on success, 0 on failure */
f899b121 2488cupsdSendHeader(
2489 cupsd_client_t *con, /* I - Client to send to */
2490 http_status_t code, /* I - HTTP status code */
2491 char *type, /* I - MIME type of document */
2492 int auth_type) /* I - Type of authentication */
ef416fc2 2493{
5a738aea
MS
2494 char auth_str[1024]; /* Authorization string */
2495#ifdef HAVE_GSSAPI
2496 static char *gss_buf = NULL; /* Kerberos auth data buffer */
2497 static int gss_bufsize = 0; /* Size of Kerberos auth data buffer */
2498#endif /* HAVE_GSSAPI */
f7deaa1a 2499
2500
4744bd90 2501 /*
2502 * Send the HTTP status header...
2503 */
2504
b423cd4c 2505 if (code == HTTP_CONTINUE)
2506 {
4744bd90 2507 /*
2508 * 100-continue doesn't send any headers...
2509 */
2510
07725fee 2511 return (httpPrintf(HTTP(con), "HTTP/%d.%d 100 Continue\r\n\r\n",
2512 con->http.version / 100, con->http.version % 100) > 0);
b423cd4c 2513 }
2514
07725fee 2515 httpFlushWrite(HTTP(con));
2516
2517 con->http.data_encoding = HTTP_ENCODE_FIELDS;
2518
2519 if (httpPrintf(HTTP(con), "HTTP/%d.%d %d %s\r\n", con->http.version / 100,
2520 con->http.version % 100, code, httpStatus(code)) < 0)
2521 return (0);
ef416fc2 2522 if (httpPrintf(HTTP(con), "Date: %s\r\n", httpGetDateString(time(NULL))) < 0)
2523 return (0);
2524 if (ServerHeader)
2525 if (httpPrintf(HTTP(con), "Server: %s\r\n", ServerHeader) < 0)
2526 return (0);
2527 if (con->http.keep_alive && con->http.version >= HTTP_1_0)
2528 {
2529 if (httpPrintf(HTTP(con), "Connection: Keep-Alive\r\n") < 0)
2530 return (0);
2531 if (httpPrintf(HTTP(con), "Keep-Alive: timeout=%d\r\n",
2532 KeepAliveTimeout) < 0)
2533 return (0);
2534 }
2535 if (code == HTTP_METHOD_NOT_ALLOWED)
e6013cfa 2536 if (httpPrintf(HTTP(con), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
ef416fc2 2537 return (0);
2538
2539 if (code == HTTP_UNAUTHORIZED)
2540 {
5bd77a73 2541 if (auth_type == CUPSD_AUTH_NONE)
f899b121 2542 {
5bd77a73 2543 if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
f899b121 2544 auth_type = DefaultAuthType;
2545 else
2546 auth_type = con->best->type;
2547 }
f7deaa1a 2548
2549 auth_str[0] = '\0';
2550
5bd77a73 2551 if (auth_type == CUPSD_AUTH_BASIC || auth_type == CUPSD_AUTH_BASICDIGEST)
f7deaa1a 2552 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
5bd77a73 2553 else if (auth_type == CUPSD_AUTH_DIGEST)
f7deaa1a 2554 snprintf(auth_str, sizeof(auth_str), "Digest realm=\"CUPS\", nonce=\"%s\"",
2555 con->http.hostname);
2556#ifdef HAVE_GSSAPI
5bd77a73 2557 else if (auth_type == CUPSD_AUTH_NEGOTIATE && con->gss_output_token.length == 0)
f7deaa1a 2558 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2559#endif /* HAVE_GSSAPI */
2560
2561#ifdef HAVE_AUTHORIZATION_H
5bd77a73 2562 if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE)
ef416fc2 2563 {
f7deaa1a 2564 int i; /* Looping var */
2565 char *auth_key; /* Auth key buffer */
2566 size_t auth_size; /* Size of remaining buffer */
2567
2568
2569 auth_key = auth_str + strlen(auth_str);
2570 auth_size = sizeof(auth_str) - (auth_key - auth_str);
2571
2572 for (i = 0; i < con->best->num_names; i ++)
2573 {
2574 if (!strncasecmp(con->best->names[i], "@AUTHKEY(", 9))
2575 {
2576 snprintf(auth_key, auth_size, ", authkey=\"%s\"",
2577 con->best->names[i] + 9);
2578 /* end parenthesis is stripped in conf.c */
2579 break;
2580 }
2581 else if (!strcasecmp(con->best->names[i], "@SYSTEM") &&
2582 SystemGroupAuthKey)
2583 {
2584 snprintf(auth_key, auth_size, ", authkey=\"%s\"", SystemGroupAuthKey);
2585 break;
2586 }
2587 }
ef416fc2 2588 }
f7deaa1a 2589#endif /* HAVE_AUTHORIZATION_H */
2590
bc44d920 2591 if (auth_str[0])
2592 {
355e94dc 2593 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdSendHeader: WWW-Authenticate: %s",
bc44d920 2594 auth_str);
2595
2596 if (httpPrintf(HTTP(con), "WWW-Authenticate: %s\r\n", auth_str) < 0)
2597 return (0);
2598 }
ef416fc2 2599 }
2600
f7deaa1a 2601#ifdef HAVE_GSSAPI
2602 /*
2603 * WWW-Authenticate: Negotiate can be included even for
2604 * non-401 replies...
2605 */
2606
5a738aea 2607 if (con->gss_output_token.length > 0 && con->gss_output_token.length <= 65536)
f7deaa1a 2608 {
f7deaa1a 2609 OM_uint32 minor_status; /* Minor status code */
5a738aea
MS
2610 int bufsize; /* Size of output token buffer */
2611
2612
2613 bufsize = con->gss_output_token.length * 4 / 3 + 2;
2614
2615 if (bufsize > gss_bufsize)
2616 {
2617 char *buf; /* New buffer */
2618
f7deaa1a 2619
5a738aea 2620 bufsize = (bufsize + 1023) & 1023;/* Round up */
f7deaa1a 2621
5a738aea
MS
2622 if (gss_buf)
2623 buf = realloc(gss_buf, bufsize);
2624 else
2625 buf = malloc(bufsize);
2626
2627 if (!buf)
2628 {
2629 cupsdLogMessage(CUPSD_LOG_ERROR,
2630 "Unable to allocate %d bytes for Kerberos credentials!",
2631 bufsize);
2632 return (0);
2633 }
2634
2635 gss_buf = buf;
2636 gss_bufsize = bufsize;
2637 }
2638
2639 httpEncode64_2(gss_buf, gss_bufsize,
2640 con->gss_output_token.value,
f7deaa1a 2641 con->gss_output_token.length);
2642 gss_release_buffer(&minor_status, &con->gss_output_token);
2643
355e94dc 2644 cupsdLogMessage(CUPSD_LOG_DEBUG,
5a738aea 2645 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf);
355e94dc 2646
5a738aea
MS
2647 if (httpPrintf(HTTP(con), "WWW-Authenticate: Negotiate %s\r\n",
2648 gss_buf) < 0)
f7deaa1a 2649 return (0);
2650 }
5a738aea
MS
2651 else if (con->gss_output_token.length > 65536)
2652 {
2653 cupsdLogMessage(CUPSD_LOG_ERROR,
2654 "Kerberos credentials larger than 64k (%d)!",
ac884b6a 2655 (int)con->gss_output_token.length);
5a738aea
MS
2656 return (0);
2657 }
f7deaa1a 2658#endif /* HAVE_GSSAPI */
2659
e1d6a774 2660 if (con->language && strcmp(con->language->language, "C"))
ef416fc2 2661 {
2662 if (httpPrintf(HTTP(con), "Content-Language: %s\r\n",
2663 con->language->language) < 0)
2664 return (0);
2665 }
2666
e1d6a774 2667 if (type)
ef416fc2 2668 {
2669 if (!strcmp(type, "text/html"))
2670 {
2671 if (httpPrintf(HTTP(con),
2672 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2673 return (0);
2674 }
2675 else if (httpPrintf(HTTP(con), "Content-Type: %s\r\n", type) < 0)
2676 return (0);
2677 }
2678
2679 return (1);
2680}
2681
2682
2683/*
2684 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2685 */
2686
2687void
2688cupsdUpdateCGI(void)
2689{
2690 char *ptr, /* Pointer to end of line in buffer */
2691 message[1024]; /* Pointer to message text */
2692 int loglevel; /* Log level for message */
2693
2694
2695 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2696 message, sizeof(message))) != NULL)
2697 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2698 break;
2699
d09495fa 2700 if (ptr == NULL && !CGIStatusBuffer->bufused)
ef416fc2 2701 {
2702 /*
2703 * Fatal error on pipe - should never happen!
2704 */
2705
2706 cupsdLogMessage(CUPSD_LOG_CRIT,
2707 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2708 strerror(errno));
2709 }
2710}
2711
2712
2713/*
2714 * 'cupsdWriteClient()' - Write data to a client as needed.
2715 */
2716
f7deaa1a 2717void
ef416fc2 2718cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2719{
2720 int bytes; /* Number of bytes written */
2721 char buf[16385]; /* Data buffer */
2722 char *bufptr; /* Pointer into buffer */
2723 ipp_state_t ipp_state; /* IPP state value */
2724
2725
2726#ifdef DEBUG
2727 cupsdLogMessage(CUPSD_LOG_DEBUG2,
b94498cf 2728 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
ef416fc2 2729 "pipe_pid=%d state=%d",
ae71f5de
MS
2730 con, con->http.fd, con->response,
2731 con->response ? con->response->state : -1,
b94498cf 2732 con->file, con->pipe_pid, con->http.state);
ef416fc2 2733#endif /* DEBUG */
2734
2735 if (con->http.state != HTTP_GET_SEND &&
2736 con->http.state != HTTP_POST_SEND)
f7deaa1a 2737 return;
2738
2739 if (con->pipe_pid)
2740 {
2741 /*
2742 * Make sure we select on the CGI output...
2743 */
2744
f899b121 2745 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
f7deaa1a 2746
2747 if (!con->file_ready)
2748 {
2749 /*
2750 * Try again later when there is CGI output available...
2751 */
2752
2753 cupsdRemoveSelect(con->http.fd);
2754 return;
2755 }
2756
2757 con->file_ready = 0;
2758 }
ef416fc2 2759
b94498cf 2760 if (con->response && con->response->state != IPP_DATA)
ef416fc2 2761 {
07725fee 2762 ipp_state = ippWrite(HTTP(con), con->response);
b94498cf 2763 bytes = ipp_state != IPP_ERROR &&
2764 (con->file >= 0 || ipp_state != IPP_DATA);
ef416fc2 2765 }
2766 else if ((bytes = read(con->file, buf, sizeof(buf) - 1)) > 0)
2767 {
2768 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2769 "cupsdWriteClient: Read %d bytes from file %d...",
2770 bytes, con->file);
2771
2772 if (con->pipe_pid && !con->got_fields)
2773 {
2774 /*
2775 * Inspect the data for Content-Type and other fields.
2776 */
2777
2778 buf[bytes] = '\0';
2779
2780 for (bufptr = buf; !con->got_fields && *bufptr; bufptr ++)
2781 if (*bufptr == '\n')
2782 {
2783 /*
2784 * Send line to client...
2785 */
2786
2787 if (bufptr > buf && bufptr[-1] == '\r')
2788 bufptr[-1] = '\0';
2789 *bufptr++ = '\0';
2790
2791 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Script header: %s", buf);
2792
2793 if (!con->sent_header)
2794 {
2795 /*
2796 * Handle redirection and CGI status codes...
2797 */
2798
2799 if (!strncasecmp(buf, "Location:", 9))
d6ae789d 2800 {
5bd77a73 2801 cupsdSendHeader(con, HTTP_SEE_OTHER, NULL, CUPSD_AUTH_NONE);
07725fee 2802 con->sent_header = 2;
2803
d6ae789d 2804 if (httpPrintf(HTTP(con), "Content-Length: 0\r\n") < 0)
f7deaa1a 2805 return;
d6ae789d 2806 }
ef416fc2 2807 else if (!strncasecmp(buf, "Status:", 7))
07725fee 2808 {
5bd77a73 2809 cupsdSendError(con, (http_status_t)atoi(buf + 7), CUPSD_AUTH_NONE);
07725fee 2810 con->sent_header = 2;
2811 }
ef416fc2 2812 else
4744bd90 2813 {
5bd77a73 2814 cupsdSendHeader(con, HTTP_OK, NULL, CUPSD_AUTH_NONE);
07725fee 2815 con->sent_header = 1;
ef416fc2 2816
4744bd90 2817 if (con->http.version == HTTP_1_1)
2818 {
4744bd90 2819 if (httpPrintf(HTTP(con), "Transfer-Encoding: chunked\r\n") < 0)
f7deaa1a 2820 return;
4744bd90 2821 }
2822 }
ef416fc2 2823 }
2824
2825 if (strncasecmp(buf, "Status:", 7))
2826 httpPrintf(HTTP(con), "%s\r\n", buf);
2827
2828 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d %s",
2829 con->http.fd, buf);
2830
2831 /*
2832 * Update buffer...
2833 */
2834
2835 bytes -= (bufptr - buf);
2836 memmove(buf, bufptr, bytes + 1);
2837 bufptr = buf - 1;
2838
2839 /*
2840 * See if the line was empty...
2841 */
2842
2843 if (con->field_col == 0)
d09495fa 2844 {
ef416fc2 2845 con->got_fields = 1;
d09495fa 2846
07725fee 2847 if (cupsdFlushHeader(con) < 0)
2848 {
2849 cupsdCloseClient(con);
f7deaa1a 2850 return;
07725fee 2851 }
d09495fa 2852
2853 if (con->http.version == HTTP_1_1)
2854 con->http.data_encoding = HTTP_ENCODE_CHUNKED;
2855 }
ef416fc2 2856 else
2857 con->field_col = 0;
2858 }
2859 else if (*bufptr != '\r')
2860 con->field_col ++;
2861
2862 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2863 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2864 con->http.fd, bytes, con->got_fields);
2865
2866 if (bytes > 0 && !con->got_fields)
2867 {
2868 /*
2869 * Remaining text needs to go out...
2870 */
2871
2872 httpPrintf(HTTP(con), "%s", buf);
2873
2874 con->http.activity = time(NULL);
f7deaa1a 2875 return;
ef416fc2 2876 }
2877 else if (bytes == 0)
47879b8b 2878 {
ef416fc2 2879 con->http.activity = time(NULL);
47879b8b
MS
2880 return;
2881 }
ef416fc2 2882 }
2883
4744bd90 2884 if (bytes > 0)
ef416fc2 2885 {
4744bd90 2886 if (httpWrite2(HTTP(con), buf, bytes) < 0)
2887 {
2888 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2889 "cupsdWriteClient: %d Write of %d bytes failed!",
2890 con->http.fd, bytes);
ef416fc2 2891
4744bd90 2892 cupsdCloseClient(con);
f7deaa1a 2893 return;
4744bd90 2894 }
ef416fc2 2895
01ce6322
MS
2896 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED)
2897 httpFlushWrite(HTTP(con));
ae71f5de 2898
4744bd90 2899 con->bytes += bytes;
ef416fc2 2900
4744bd90 2901 if (con->http.state == HTTP_WAITING)
2902 bytes = 0;
2903 }
ef416fc2 2904 }
2905
2906 if (bytes <= 0)
2907 {
2908 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d bytes < 0",
2909 con->http.fd);
2910
2911 cupsdLogRequest(con, HTTP_OK);
2912
2913 httpFlushWrite(HTTP(con));
2914
07725fee 2915 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED && con->sent_header == 1)
ef416fc2 2916 {
07725fee 2917 if (httpWrite2(HTTP(con), "", 0) < 0)
ef416fc2 2918 {
2919 cupsdCloseClient(con);
f7deaa1a 2920 return;
ef416fc2 2921 }
2922 }
2923
2924 con->http.state = HTTP_WAITING;
2925
f7deaa1a 2926 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 2927
2928 if (con->file >= 0)
2929 {
f7deaa1a 2930 cupsdRemoveSelect(con->file);
ef416fc2 2931
2932 if (con->pipe_pid)
2933 cupsdEndProcess(con->pipe_pid, 0);
2934
2935 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2936 "cupsdWriteClient: %d Closing data file %d.",
2937 con->http.fd, con->file);
2938
2939 close(con->file);
2940 con->file = -1;
2941 con->pipe_pid = 0;
2942 }
2943
2944 if (con->filename)
2945 {
2946 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2947 "cupsdWriteClient: %d Removing temp file %s",
2948 con->http.fd, con->filename);
2949 unlink(con->filename);
2950 cupsdClearString(&con->filename);
2951 }
2952
2abf387c 2953 if (con->request)
ef416fc2 2954 {
2955 ippDelete(con->request);
2956 con->request = NULL;
2957 }
2958
2abf387c 2959 if (con->response)
ef416fc2 2960 {
2961 ippDelete(con->response);
2962 con->response = NULL;
2963 }
2964
2965 cupsdClearString(&con->command);
2966 cupsdClearString(&con->options);
b86bc4cf 2967 cupsdClearString(&con->query_string);
ef416fc2 2968
2969 if (!con->http.keep_alive)
2970 {
2971 cupsdCloseClient(con);
f7deaa1a 2972 return;
ef416fc2 2973 }
2974 }
2975
2976 con->http.activity = time(NULL);
f7deaa1a 2977}
ef416fc2 2978
f7deaa1a 2979
e1d6a774 2980/*
2981 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2982 */
2983
2984static int /* O - 1 if modified since */
2985check_if_modified(
2986 cupsd_client_t *con, /* I - Client connection */
2987 struct stat *filestats) /* I - File information */
2988{
2989 char *ptr; /* Pointer into field */
2990 time_t date; /* Time/date value */
2991 off_t size; /* Size/length value */
2992
2993
2994 size = 0;
2995 date = 0;
2996 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
2997
2998 if (*ptr == '\0')
2999 return (1);
3000
3001 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3002 "check_if_modified: %d If-Modified-Since=\"%s\"",
3003 con->http.fd, ptr);
3004
3005 while (*ptr != '\0')
3006 {
3007 while (isspace(*ptr) || *ptr == ';')
3008 ptr ++;
3009
3010 if (strncasecmp(ptr, "length=", 7) == 0)
3011 {
3012 ptr += 7;
3013 size = strtoll(ptr, NULL, 10);
3014
3015 while (isdigit(*ptr))
3016 ptr ++;
3017 }
3018 else if (isalpha(*ptr))
3019 {
3020 date = httpGetDateTime(ptr);
3021 while (*ptr != '\0' && *ptr != ';')
3022 ptr ++;
3023 }
e53920b9 3024 else
3025 ptr ++;
e1d6a774 3026 }
3027
3028 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3029 "check_if_modified: %d sizes=" CUPS_LLFMT ","
3030 CUPS_LLFMT " dates=%d,%d",
3031 con->http.fd, CUPS_LLCAST size,
3032 CUPS_LLCAST filestats->st_size, (int)date,
3033 (int)filestats->st_mtime);
3034
3035 return ((size != filestats->st_size && size != 0) ||
3036 (date < filestats->st_mtime && date != 0) ||
3037 (size == 0 && date == 0));
3038}
3039
3040
3dfe78b3
MS
3041/*
3042 * 'compare_clients()' - Compare two client connections.
3043 */
3044
3045static int /* O - Result of comparison */
3046compare_clients(cupsd_client_t *a, /* I - First client */
3047 cupsd_client_t *b, /* I - Second client */
3048 void *data) /* I - User data (not used) */
3049{
3050 (void)data;
3051
3052 if (a == b)
3053 return (0);
3054 else if (a < b)
3055 return (-1);
3056 else
3057 return (1);
3058}
3059
3060
ee571f26
MS
3061/*
3062 * 'data_ready()' - Check whether data is available from a client.
3063 */
3064
3065static int /* O - 1 if data is ready, 0 otherwise */
3066data_ready(cupsd_client_t *con) /* I - Client */
3067{
3068 if (con->http.used > 0)
3069 return (1);
3070#ifdef HAVE_SSL
3071 else if (con->http.tls)
3072 {
3073# ifdef HAVE_LIBSSL
3074 if (SSL_pending((SSL *)(con->http.tls)))
3075 return (1);
3076# elif defined(HAVE_GNUTLS)
3077 if (gnutls_record_check_pending(((http_tls_t *)(con->http.tls))->session))
3078 return (1);
3079# elif defined(HAVE_CDSASSL)
3080 size_t bytes; /* Bytes that are available */
3081
3082 if (!SSLGetBufferedReadSize(((http_tls_t *)(con->http.tls))->session,
3083 &bytes) && bytes > 0)
3084 return (1);
3085# endif /* HAVE_LIBSSL */
3086 }
3087#endif /* HAVE_SSL */
3088
3089 return (0);
3090}
3091
3092
80ca4592 3093#ifdef HAVE_SSL
e1d6a774 3094/*
3095 * 'encrypt_client()' - Enable encryption for the client...
3096 */
3097
3098static int /* O - 1 on success, 0 on error */
3099encrypt_client(cupsd_client_t *con) /* I - Client to encrypt */
3100{
80ca4592 3101# ifdef HAVE_LIBSSL
e1d6a774 3102 SSL_CTX *context; /* Context for encryption */
3103 SSL *conn; /* Connection for encryption */
411affcf 3104 BIO *bio; /* BIO data */
e1d6a774 3105 unsigned long error; /* Error code */
3106
3107
8ca02f3c 3108 /*
3109 * Verify that we have a certificate...
3110 */
3111
3112 if (access(ServerKey, 0) || access(ServerCertificate, 0))
3113 {
3114 /*
3115 * Nope, make a self-signed certificate...
3116 */
3117
b86bc4cf 3118 if (!make_certificate(con))
8ca02f3c 3119 return (0);
3120 }
3121
e1d6a774 3122 /*
3123 * Create the SSL context and accept the connection...
3124 */
3125
3126 context = SSL_CTX_new(SSLv23_server_method());
3127
3128 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
b19ccc9e 3129 if (SSLOptions & CUPSD_SSL_NOEMPTY)
58dc1933 3130 SSL_CTX_set_options(context, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
e1d6a774 3131 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
58dc1933 3132 SSL_CTX_use_certificate_chain_file(context, ServerCertificate);
e1d6a774 3133
411affcf 3134 bio = BIO_new(_httpBIOMethods());
3135 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)HTTP(con));
3136
e1d6a774 3137 conn = SSL_new(context);
411affcf 3138 SSL_set_bio(conn, bio, bio);
e1d6a774 3139
e1d6a774 3140 if (SSL_accept(conn) != 1)
3141 {
3142 cupsdLogMessage(CUPSD_LOG_ERROR,
3143 "encrypt_client: Unable to encrypt connection from %s!",
3144 con->http.hostname);
3145
3146 while ((error = ERR_get_error()) != 0)
3147 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
3148 ERR_error_string(error, NULL));
3149
3150 SSL_CTX_free(context);
3151 SSL_free(conn);
3152 return (0);
3153 }
3154
3155 cupsdLogMessage(CUPSD_LOG_DEBUG,
3156 "encrypt_client: %d Connection from %s now encrypted.",
3157 con->http.fd, con->http.hostname);
3158
3159 con->http.tls = conn;
3160 return (1);
f7deaa1a 3161
80ca4592 3162# elif defined(HAVE_GNUTLS)
e1d6a774 3163 http_tls_t *conn; /* TLS session object */
3164 int error; /* Error code */
3165 gnutls_certificate_server_credentials *credentials;
3166 /* TLS credentials */
3167
3168
3169 /*
3170 * Verify that we have a certificate...
3171 */
3172
3173 if (access(ServerKey, 0) || access(ServerCertificate, 0))
3174 {
3175 /*
3176 * Nope, make a self-signed certificate...
3177 */
3178
b86bc4cf 3179 if (!make_certificate(con))
8ca02f3c 3180 return (0);
e1d6a774 3181 }
3182
3183 /*
3184 * Create the SSL object and perform the SSL handshake...
3185 */
3186
89d46774 3187 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
e1d6a774 3188
3189 if (conn == NULL)
3190 return (0);
3191
3192 credentials = (gnutls_certificate_server_credentials *)
3193 malloc(sizeof(gnutls_certificate_server_credentials));
3194 if (credentials == NULL)
3195 {
3196 cupsdLogMessage(CUPSD_LOG_ERROR,
3197 "encrypt_client: Unable to encrypt connection from %s!",
3198 con->http.hostname);
3199 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s", strerror(errno));
3200
3201 free(conn);
3202 return (0);
3203 }
3204
3205 gnutls_certificate_allocate_credentials(credentials);
f7deaa1a 3206 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
e1d6a774 3207 ServerKey, GNUTLS_X509_FMT_PEM);
3208
3209 gnutls_init(&(conn->session), GNUTLS_SERVER);
3210 gnutls_set_default_priority(conn->session);
3211 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
411affcf 3212 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)HTTP(con));
3213 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
3214 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
e1d6a774 3215
3216 error = gnutls_handshake(conn->session);
3217
3218 if (error != GNUTLS_E_SUCCESS)
3219 {
3220 cupsdLogMessage(CUPSD_LOG_ERROR,
3221 "encrypt_client: Unable to encrypt connection from %s!",
3222 con->http.hostname);
3223 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
3224 gnutls_strerror(error));
3225
3226 gnutls_deinit(conn->session);
3227 gnutls_certificate_free_credentials(*credentials);
3228 free(conn);
3229 free(credentials);
3230 return (0);
3231 }
3232
3233 cupsdLogMessage(CUPSD_LOG_DEBUG,
3234 "encrypt_client: %d Connection from %s now encrypted.",
3235 con->http.fd, con->http.hostname);
3236
3237 conn->credentials = credentials;
3238 con->http.tls = conn;
3239 return (1);
3240
80ca4592 3241# elif defined(HAVE_CDSASSL)
89d46774 3242 OSStatus error; /* Error code */
3243 http_tls_t *conn; /* CDSA connection information */
e1d6a774 3244
3245
89d46774 3246 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
3247 return (0);
e1d6a774 3248
89d46774 3249 error = 0;
3250 conn->session = NULL;
b86bc4cf 3251 conn->certsArray = get_cdsa_certificate(con);
e1d6a774 3252
8ca02f3c 3253 if (!conn->certsArray)
3254 {
3255 /*
3256 * No keychain (yet), make a self-signed certificate...
3257 */
3258
b86bc4cf 3259 if (make_certificate(con))
3260 conn->certsArray = get_cdsa_certificate(con);
8ca02f3c 3261 }
3262
89d46774 3263 if (!conn->certsArray)
e1d6a774 3264 {
3265 cupsdLogMessage(CUPSD_LOG_ERROR,
411affcf 3266 "encrypt_client: Could not find signing key in keychain "
e1d6a774 3267 "\"%s\"", ServerCertificate);
3268 error = errSSLBadCert; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3269 }
3270
3271 if (!error)
89d46774 3272 error = SSLNewContext(true, &conn->session);
e1d6a774 3273
3274 if (!error)
89d46774 3275 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
3276
3277 if (!error)
ed486911 3278 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
e1d6a774 3279
3280 if (!error)
411affcf 3281 error = SSLSetConnection(conn->session, HTTP(con));
e1d6a774 3282
3283 if (!error)
89d46774 3284 error = SSLSetAllowsExpiredCerts(conn->session, true);
e1d6a774 3285
3286 if (!error)
89d46774 3287 error = SSLSetAllowsAnyRoot(conn->session, true);
ef416fc2 3288
89d46774 3289 if (!error)
3290 error = SSLSetCertificate(conn->session, conn->certsArray);
ef416fc2 3291
e1d6a774 3292 if (!error)
3293 {
3294 /*
3295 * Perform SSL/TLS handshake
3296 */
ef416fc2 3297
89d46774 3298 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
e1d6a774 3299 usleep(1000);
3300 }
ef416fc2 3301
e1d6a774 3302 if (error)
3303 {
3304 cupsdLogMessage(CUPSD_LOG_ERROR,
3305 "encrypt_client: Unable to encrypt connection from %s!",
3306 con->http.hostname);
ef416fc2 3307
ed486911 3308 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s (%d)",
3309 cssmErrorString(error), (int)error);
ef416fc2 3310
e1d6a774 3311 con->http.error = error;
3312 con->http.status = HTTP_ERROR;
ef416fc2 3313
89d46774 3314 if (conn->session)
3315 SSLDisposeContext(conn->session);
3316
3317 if (conn->certsArray)
3318 CFRelease(conn->certsArray);
3319
3320 free(conn);
ef416fc2 3321
e1d6a774 3322 return (0);
ef416fc2 3323 }
3324
e1d6a774 3325 cupsdLogMessage(CUPSD_LOG_DEBUG,
3326 "encrypt_client: %d Connection from %s now encrypted.",
3327 con->http.fd, con->http.hostname);
ef416fc2 3328
e1d6a774 3329 con->http.tls = conn;
3330 return (1);
3331
80ca4592 3332# endif /* HAVE_LIBSSL */
ef416fc2 3333}
80ca4592 3334#endif /* HAVE_SSL */
ef416fc2 3335
3336
3337#ifdef HAVE_CDSASSL
3338/*
b86bc4cf 3339 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
ef416fc2 3340 */
3341
b86bc4cf 3342static CFArrayRef /* O - Array of certificates */
3343get_cdsa_certificate(cupsd_client_t *con) /* I - Client connection */
ef416fc2 3344{
3345 OSStatus err; /* Error info */
b86bc4cf 3346 SecKeychainRef keychain; /* Keychain reference */
3347 SecIdentitySearchRef search; /* Search reference */
ef416fc2 3348 SecIdentityRef identity; /* Identity */
b86bc4cf 3349 CFArrayRef certificates = NULL;
3350 /* Certificate array */
ef416fc2 3351
3352
b86bc4cf 3353 if ((err = SecKeychainOpen(ServerCertificate, &keychain)))
3354 {
3355 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\", %s",
3356 ServerCertificate, cssmErrorString(err));
3357 return (NULL);
3358 }
ef416fc2 3359
b86bc4cf 3360# if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3361 /*
3362 * Use a policy to search for valid certificates who's common name matches the
3363 * servername...
3364 */
3365
3366 SecPolicySearchRef policy_search; /* Policy search ref */
3367 SecPolicyRef policy; /* Policy ref */
3368 CSSM_DATA options; /* Policy options */
3369 CSSM_APPLE_TP_SSL_OPTIONS
3370 ssl_options; /* SSL Option for hostname */
3371
3372
1f0275e3
MS
3373 if (SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL,
3374 NULL, &policy_search))
ef416fc2 3375 {
b86bc4cf 3376 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create a policy search reference");
3377 CFRelease(keychain);
3378 return (NULL);
3379 }
ef416fc2 3380
1f0275e3 3381 if (SecPolicySearchCopyNext(policy_search, &policy))
b86bc4cf 3382 {
3383 cupsdLogMessage(CUPSD_LOG_ERROR,
3384 "Cannot find a policy to use for searching");
3385 CFRelease(keychain);
3386 CFRelease(policy_search);
3387 return (NULL);
3388 }
ef416fc2 3389
b86bc4cf 3390 memset(&ssl_options, 0, sizeof(ssl_options));
3391 ssl_options.Version = CSSM_APPLE_TP_SSL_OPTS_VERSION;
3392 ssl_options.ServerName = con->servername;
3393 ssl_options.ServerNameLen = strlen(con->servername);
ef416fc2 3394
b86bc4cf 3395 options.Data = (uint8 *)&ssl_options;
3396 options.Length = sizeof(ssl_options);
3397
1f0275e3 3398 if (SecPolicySetValue(policy, &options))
b86bc4cf 3399 {
3400 cupsdLogMessage(CUPSD_LOG_ERROR,
3401 "Cannot set policy value to use for searching");
3402 CFRelease(keychain);
3403 CFRelease(policy_search);
3404 return (NULL);
3405 }
3406
3407 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3408 keychain, FALSE, &search);
3409# else
3410 /*
3411 * Assume there is exactly one SecIdentity in the keychain...
3412 */
3413
3414 err = SecIdentitySearchCreate(keychain, CSSM_KEYUSE_SIGN, &search);
3415# endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3416
3417 if (err)
3418 cupsdLogMessage(CUPSD_LOG_DEBUG,
3419 "Cannot create keychain search reference: %s",
3420 cssmErrorString(err));
3421 else
3422 {
3423 if ((err = SecIdentitySearchCopyNext(search, &identity)))
3424 {
3425 cupsdLogMessage(CUPSD_LOG_DEBUG,
ef416fc2 3426 "Cannot find signing key in keychain \"%s\", error %d",
3427 ServerCertificate, (int)err);
b86bc4cf 3428 }
3429 else
3430 {
3431 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3432 cupsdLogMessage(CUPSD_LOG_ERROR,
3433 "SecIdentitySearchCopyNext CFTypeID failure!");
ef416fc2 3434 else
3435 {
b86bc4cf 3436 if ((certificates = CFArrayCreate(NULL, (const void **)&identity,
3437 1, &kCFTypeArrayCallBacks)) == NULL)
3438 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create certificate array");
ef416fc2 3439 }
3440
b86bc4cf 3441 CFRelease(identity);
ef416fc2 3442 }
3443
b86bc4cf 3444 CFRelease(search);
ef416fc2 3445 }
3446
b86bc4cf 3447# if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3448 CFRelease(policy);
3449 CFRelease(policy_search);
3450# endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3451
3452 return (certificates);
ef416fc2 3453}
3454#endif /* HAVE_CDSASSL */
3455
3456
3457/*
3458 * 'get_file()' - Get a filename and state info.
3459 */
3460
3461static char * /* O - Real filename */
3462get_file(cupsd_client_t *con, /* I - Client connection */
3463 struct stat *filestats, /* O - File information */
3464 char *filename, /* IO - Filename buffer */
3465 int len) /* I - Buffer length */
3466{
3467 int status; /* Status of filesystem calls */
3468 char *ptr; /* Pointer info filename */
3469 int plen; /* Remaining length after pointer */
db1f069b 3470 char language[7]; /* Language subdirectory, if any */
ef416fc2 3471
3472
3473 /*
f7deaa1a 3474 * Figure out the real filename...
ef416fc2 3475 */
3476
db1f069b
MS
3477 language[0] = '\0';
3478
ef416fc2 3479 if (!strncmp(con->uri, "/ppd/", 5))
3480 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
f7deaa1a 3481 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3482 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
ef416fc2 3483 else if (!strncmp(con->uri, "/admin/conf/", 12))
3484 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3485 else if (!strncmp(con->uri, "/admin/log/", 11))
3486 {
2e4ff8af 3487 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
ef416fc2 3488 strlcpy(filename, AccessLog, len);
2e4ff8af 3489 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
ef416fc2 3490 strlcpy(filename, ErrorLog, len);
2e4ff8af 3491 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
ef416fc2 3492 strlcpy(filename, PageLog, len);
3493 else
3494 return (NULL);
3495 }
d6ae789d 3496 else if (con->language)
db1f069b
MS
3497 {
3498 snprintf(language, sizeof(language), "/%s", con->language->language);
3499 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3500 }
ef416fc2 3501 else
3502 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3503
3504 if ((ptr = strchr(filename, '?')) != NULL)
3505 *ptr = '\0';
3506
3507 /*
3508 * Grab the status for this language; if there isn't a language-specific file
3509 * then fallback to the default one...
3510 */
3511
db1f069b 3512 if ((status = stat(filename, filestats)) != 0 && language[0] &&
d6ae789d 3513 strncmp(con->uri, "/ppd/", 5) &&
3514 strncmp(con->uri, "/admin/conf/", 12) &&
3515 strncmp(con->uri, "/admin/log/", 11))
ef416fc2 3516 {
3517 /*
d6ae789d 3518 * Drop the country code...
ef416fc2 3519 */
3520
db1f069b
MS
3521 language[3] = '\0';
3522 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
d6ae789d 3523
3524 if ((ptr = strchr(filename, '?')) != NULL)
3525 *ptr = '\0';
3526
3527 if ((status = stat(filename, filestats)) != 0)
ef416fc2 3528 {
d6ae789d 3529 /*
3530 * Drop the language prefix and try the root directory...
3531 */
3532
db1f069b 3533 language[0] = '\0';
ef416fc2 3534 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3535
3536 if ((ptr = strchr(filename, '?')) != NULL)
3537 *ptr = '\0';
3538
3539 status = stat(filename, filestats);
3540 }
3541 }
3542
3543 /*
3544 * If we're found a directory, get the index.html file instead...
3545 */
3546
3547 if (!status && S_ISDIR(filestats->st_mode))
3548 {
db1f069b
MS
3549 /*
3550 * Make sure the URI ends with a slash...
3551 */
ef416fc2 3552
db1f069b
MS
3553 if (con->uri[strlen(con->uri) - 1] != '/')
3554 strlcat(con->uri, "/", sizeof(con->uri));
ef416fc2 3555
db1f069b
MS
3556 /*
3557 * Find the directory index file, trying every language...
3558 */
ef416fc2 3559
db1f069b 3560 do
ef416fc2 3561 {
db1f069b
MS
3562 if (status && language[0])
3563 {
3564 /*
3565 * Try a different language subset...
3566 */
3567
3568 if (language[3])
3569 language[0] = '\0'; /* Strip country code */
3570 else
3571 language[0] = '\0'; /* Strip language */
3572 }
3573
3574 /*
3575 * Look for the index file...
3576 */
3577
3578 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3579
3580 if ((ptr = strchr(filename, '?')) != NULL)
3581 *ptr = '\0';
3582
3583 ptr = filename + strlen(filename);
3584 plen = len - (ptr - filename);
3585
3586 strlcpy(ptr, "index.html", plen);
ef416fc2 3587 status = stat(filename, filestats);
db1f069b
MS
3588
3589#ifdef HAVE_JAVA
3590 if (status)
3591 {
3592 strlcpy(ptr, "index.class", plen);
3593 status = stat(filename, filestats);
3594 }
ef416fc2 3595#endif /* HAVE_JAVA */
3596
3597#ifdef HAVE_PERL
db1f069b
MS
3598 if (status)
3599 {
3600 strlcpy(ptr, "index.pl", plen);
3601 status = stat(filename, filestats);
3602 }
ef416fc2 3603#endif /* HAVE_PERL */
3604
3605#ifdef HAVE_PHP
db1f069b
MS
3606 if (status)
3607 {
3608 strlcpy(ptr, "index.php", plen);
3609 status = stat(filename, filestats);
3610 }
ef416fc2 3611#endif /* HAVE_PHP */
3612
3613#ifdef HAVE_PYTHON
db1f069b
MS
3614 if (status)
3615 {
3616 strlcpy(ptr, "index.pyc", plen);
3617 status = stat(filename, filestats);
3618 }
ef416fc2 3619
db1f069b
MS
3620 if (status)
3621 {
3622 strlcpy(ptr, "index.py", plen);
3623 status = stat(filename, filestats);
3624 }
ef416fc2 3625#endif /* HAVE_PYTHON */
db1f069b
MS
3626
3627 }
3628 while (status && language[0]);
ef416fc2 3629 }
3630
3631 cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_file: %d filename=%s size=%d",
3632 con->http.fd, filename,
3633 status ? -1 : (int)filestats->st_size);
3634
3635 if (!status)
3636 con->http.data_remaining = (int)filestats->st_size;
3637
3638 if (status)
3639 return (NULL);
3640 else
3641 return (filename);
3642}
3643
3644
3645/*
3646 * 'install_conf_file()' - Install a configuration file.
3647 */
3648
3649static http_status_t /* O - Status */
3650install_conf_file(cupsd_client_t *con) /* I - Connection */
3651{
3652 cups_file_t *in, /* Input file */
3653 *out; /* Output file */
3654 char buffer[1024]; /* Copy buffer */
3655 int bytes; /* Number of bytes */
3656 char conffile[1024], /* Configuration filename */
3657 newfile[1024], /* New config filename */
3658 oldfile[1024]; /* Old config filename */
3659 struct stat confinfo; /* Config file info */
3660
3661
3662 /*
3663 * First construct the filenames...
3664 */
3665
3666 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3667 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3668 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3669
3670 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3671
3672 /*
3673 * Get the owner, group, and permissions of the configuration file.
3674 * If it doesn't exist, assign it to the User and Group in the
3675 * cupsd.conf file with mode 0640 permissions.
3676 */
3677
3678 if (stat(conffile, &confinfo))
3679 {
3680 confinfo.st_uid = User;
3681 confinfo.st_gid = Group;
3682 confinfo.st_mode = ConfigFilePerm;
3683 }
3684
3685 /*
3686 * Open the request file and new config file...
3687 */
3688
3689 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3690 {
3691 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3692 con->filename, strerror(errno));
3693 return (HTTP_SERVER_ERROR);
3694 }
3695
3696 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3697 {
3698 cupsFileClose(in);
3699 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3700 newfile, strerror(errno));
3701 return (HTTP_SERVER_ERROR);
3702 }
3703
3704 fchmod(cupsFileNumber(out), confinfo.st_mode);
3705 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3706
3707 /*
3708 * Copy from the request to the new config file...
3709 */
3710
3711 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3712 if (cupsFileWrite(out, buffer, bytes) < bytes)
3713 {
3714 cupsdLogMessage(CUPSD_LOG_ERROR,
3715 "Unable to copy to config file \"%s\" - %s",
3716 newfile, strerror(errno));
3717
3718 cupsFileClose(in);
3719 cupsFileClose(out);
3720 unlink(newfile);
3721
3722 return (HTTP_SERVER_ERROR);
3723 }
3724
3725 /*
3726 * Close the files...
3727 */
3728
3729 cupsFileClose(in);
3730 if (cupsFileClose(out))
3731 {
3732 cupsdLogMessage(CUPSD_LOG_ERROR,
3733 "Error file closing config file \"%s\" - %s",
3734 newfile, strerror(errno));
3735
3736 unlink(newfile);
3737
3738 return (HTTP_SERVER_ERROR);
3739 }
3740
3741 /*
3742 * Remove the request file...
3743 */
3744
3745 unlink(con->filename);
3746 cupsdClearString(&con->filename);
3747
3748 /*
3749 * Unlink the old backup, rename the current config file to the backup
3750 * filename, and rename the new config file to the config file name...
3751 */
3752
3753 if (unlink(oldfile))
3754 if (errno != ENOENT)
3755 {
3756 cupsdLogMessage(CUPSD_LOG_ERROR,
3757 "Unable to remove backup config file \"%s\" - %s",
3758 oldfile, strerror(errno));
3759
3760 unlink(newfile);
3761
3762 return (HTTP_SERVER_ERROR);
3763 }
3764
3765 if (rename(conffile, oldfile))
3766 if (errno != ENOENT)
3767 {
3768 cupsdLogMessage(CUPSD_LOG_ERROR,
3769 "Unable to rename old config file \"%s\" - %s",
3770 conffile, strerror(errno));
3771
3772 unlink(newfile);
3773
3774 return (HTTP_SERVER_ERROR);
3775 }
3776
3777 if (rename(newfile, conffile))
3778 {
3779 cupsdLogMessage(CUPSD_LOG_ERROR,
3780 "Unable to rename new config file \"%s\" - %s",
3781 newfile, strerror(errno));
3782
3783 rename(oldfile, conffile);
3784 unlink(newfile);
3785
3786 return (HTTP_SERVER_ERROR);
3787 }
3788
3789 /*
3790 * If the cupsd.conf file was updated, set the NeedReload flag...
3791 */
3792
3793 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3794 NeedReload = RELOAD_CUPSD;
3795 else
3796 NeedReload = RELOAD_ALL;
3797
3798 ReloadTime = time(NULL);
3799
3800 /*
3801 * Return that the file was created successfully...
3802 */
3803
3804 return (HTTP_CREATED);
3805}
3806
3807
e1d6a774 3808/*
3809 * 'is_cgi()' - Is the resource a CGI script/program?
3810 */
3811
3812static int /* O - 1 = CGI, 0 = file */
3813is_cgi(cupsd_client_t *con, /* I - Client connection */
3814 const char *filename, /* I - Real filename */
3815 struct stat *filestats, /* I - File information */
3816 mime_type_t *type) /* I - MIME type */
3817{
3818 const char *options; /* Options on URL */
3819
3820
3821 cupsdLogMessage(CUPSD_LOG_DEBUG2,
75bd9771 3822 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
e1d6a774 3823 con, filename, filestats, type ? type->super : "unknown",
3824 type ? type->type : "unknown");
3825
3826 /*
3827 * Get the options, if any...
3828 */
3829
3830 if ((options = strchr(con->uri, '?')) != NULL)
a0f6818e
MS
3831 {
3832 options ++;
3833 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3834 }
b86bc4cf 3835
e1d6a774 3836 /*
3837 * Check for known types...
3838 */
3839
3840 if (!type || strcasecmp(type->super, "application"))
3841 {
3842 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3843 return (0);
3844 }
3845
3846 if (!strcasecmp(type->type, "x-httpd-cgi") &&
3847 (filestats->st_mode & 0111))
3848 {
3849 /*
3850 * "application/x-httpd-cgi" is a CGI script.
3851 */
3852
3853 cupsdSetString(&con->command, filename);
3854
a0f6818e
MS
3855 if (options)
3856 cupsdSetStringf(&con->options, " %s", options);
e1d6a774 3857
3858 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3859 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3860 con->command, con->options);
3861
3862 return (1);
3863 }
3864#ifdef HAVE_JAVA
3865 else if (!strcasecmp(type->type, "x-httpd-java"))
3866 {
3867 /*
3868 * "application/x-httpd-java" is a Java servlet.
3869 */
3870
3871 cupsdSetString(&con->command, CUPS_JAVA);
3872
3873 if (options)
b94498cf 3874 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3875 else
b94498cf 3876 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3877
3878 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3879 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3880 con->command, con->options);
3881
3882 return (1);
3883 }
3884#endif /* HAVE_JAVA */
3885#ifdef HAVE_PERL
3886 else if (!strcasecmp(type->type, "x-httpd-perl"))
3887 {
3888 /*
3889 * "application/x-httpd-perl" is a Perl page.
3890 */
3891
3892 cupsdSetString(&con->command, CUPS_PERL);
3893
3894 if (options)
b94498cf 3895 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3896 else
b94498cf 3897 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3898
3899 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3900 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3901 con->command, con->options);
3902
3903 return (1);
3904 }
3905#endif /* HAVE_PERL */
3906#ifdef HAVE_PHP
3907 else if (!strcasecmp(type->type, "x-httpd-php"))
3908 {
3909 /*
3910 * "application/x-httpd-php" is a PHP page.
3911 */
3912
3913 cupsdSetString(&con->command, CUPS_PHP);
3914
3915 if (options)
b94498cf 3916 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3917 else
b94498cf 3918 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3919
3920 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3921 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3922 con->command, con->options);
3923
3924 return (1);
3925 }
3926#endif /* HAVE_PHP */
3927#ifdef HAVE_PYTHON
3928 else if (!strcasecmp(type->type, "x-httpd-python"))
3929 {
3930 /*
3931 * "application/x-httpd-python" is a Python page.
3932 */
3933
3934 cupsdSetString(&con->command, CUPS_PYTHON);
3935
3936 if (options)
b94498cf 3937 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3938 else
b94498cf 3939 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3940
3941 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3942 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3943 con->command, con->options);
3944
3945 return (1);
3946 }
3947#endif /* HAVE_PYTHON */
3948
3949 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3950
3951 return (0);
3952}
3953
3954
ef416fc2 3955/*
3956 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3957 */
3958
3959static int /* O - 0 if relative, 1 if absolute */
3960is_path_absolute(const char *path) /* I - Input path */
3961{
3962 /*
3963 * Check for a leading slash...
3964 */
3965
3966 if (path[0] != '/')
3967 return (0);
3968
3969 /*
3970 * Check for "/.." in the path...
3971 */
3972
3973 while ((path = strstr(path, "/..")) != NULL)
3974 {
3975 if (!path[3] || path[3] == '/')
3976 return (0);
3977
3978 path ++;
3979 }
3980
3981 /*
3982 * If we haven't found any relative paths, return 1 indicating an
3983 * absolute path...
3984 */
3985
3986 return (1);
3987}
3988
3989
8ca02f3c 3990#ifdef HAVE_SSL
4744bd90 3991/*
3992 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3993 */
3994
8ca02f3c 3995static int /* O - 1 on success, 0 on failure */
b86bc4cf 3996make_certificate(cupsd_client_t *con) /* I - Client connection */
4744bd90 3997{
8ca02f3c 3998#if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
d09495fa 3999 int pid, /* Process ID of command */
4000 status; /* Status of command */
4001 char command[1024], /* Command */
f7deaa1a 4002 *argv[12], /* Command-line arguments */
d09495fa 4003 *envp[MAX_ENV + 1], /* Environment variables */
4004 home[1024], /* HOME environment variable */
4005 infofile[1024], /* Type-in information for cert */
4006 seedfile[1024]; /* Random number seed file */
4007 int envc, /* Number of environment variables */
4008 bytes; /* Bytes written */
4009 cups_file_t *fp; /* Seed/info file */
4010 int infofd; /* Info file descriptor */
8ca02f3c 4011
4012
4013 /*
d09495fa 4014 * Run the "openssl" command to seed the random number generator and
4015 * generate a self-signed certificate that is good for 10 years:
4016 *
4017 * openssl rand -rand seedfile 1
8ca02f3c 4018 *
4019 * openssl req -new -x509 -keyout ServerKey \
4020 * -out ServerCertificate -days 3650 -nodes
d09495fa 4021 *
4022 * The seeding step is crucial in ensuring that the openssl command
4023 * does not block on systems without sufficient entropy...
8ca02f3c 4024 */
4025
4026 if (!cupsFileFind("openssl", getenv("PATH"), 1, command, sizeof(command)))
4027 {
4028 cupsdLogMessage(CUPSD_LOG_ERROR,
4029 "No SSL certificate and openssl command not found!");
4030 return (0);
4031 }
4032
d09495fa 4033 if (access("/dev/urandom", 0))
4034 {
4035 /*
4036 * If the system doesn't provide /dev/urandom, then any random source
4037 * will probably be blocking-style, so generate some random data to
4038 * use as a seed for the certificate. Note that we have already
4039 * seeded the random number generator in cupsdInitCerts()...
4040 */
4041
4042 cupsdLogMessage(CUPSD_LOG_INFO,
4043 "Seeding the random number generator...");
4044
4045 snprintf(home, sizeof(home), "HOME=%s", TempDir);
4046
4047 /*
4048 * Write the seed file...
4049 */
4050
4051 if ((fp = cupsTempFile2(seedfile, sizeof(seedfile))) == NULL)
4052 {
4053 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create seed file %s - %s",
4054 seedfile, strerror(errno));
4055 return (0);
4056 }
4057
4058 for (bytes = 0; bytes < 262144; bytes ++)
4059 cupsFilePutChar(fp, random());
4060
4061 cupsFileClose(fp);
4062
4063 /*
4064 * Run the openssl command to seed its random number generator...
4065 */
4066
4067 argv[0] = "openssl";
4068 argv[1] = "rand";
4069 argv[2] = "-rand";
4070 argv[3] = seedfile;
4071 argv[4] = "1";
4072 argv[5] = NULL;
4073
4074 envc = cupsdLoadEnv(envp, MAX_ENV);
4075 envp[envc++] = home;
4076 envp[envc] = NULL;
4077
a4924f6c
MS
4078 if (!cupsdStartProcess(command, argv, envp, -1, -1, -1, -1, -1, 1, NULL,
4079 &pid))
d09495fa 4080 {
4081 unlink(seedfile);
4082 return (0);
4083 }
4084
4085 while (waitpid(pid, &status, 0) < 0)
4086 if (errno != EINTR)
4087 {
4088 status = 1;
4089 break;
4090 }
4091
4092 cupsdFinishProcess(pid, command, sizeof(command));
4093
4094 /*
4095 * Remove the seed file, as it is no longer needed...
4096 */
4097
4098 unlink(seedfile);
4099
4100 if (status)
4101 {
4102 if (WIFEXITED(status))
4103 cupsdLogMessage(CUPSD_LOG_ERROR,
4104 "Unable to seed random number generator - "
4105 "the openssl command stopped with status %d!",
4106 WEXITSTATUS(status));
4107 else
4108 cupsdLogMessage(CUPSD_LOG_ERROR,
4109 "Unable to seed random number generator - "
4110 "the openssl command crashed on signal %d!",
4111 WTERMSIG(status));
4112
4113 return (0);
4114 }
4115 }
4116
4117 /*
4118 * Create a file with the certificate information fields...
4119 *
4120 * Note: This assumes that the default questions are asked by the openssl
4121 * command...
4122 */
4123
4124 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4125 {
4126 cupsdLogMessage(CUPSD_LOG_ERROR,
4127 "Unable to create certificate information file %s - %s",
4128 infofile, strerror(errno));
4129 return (0);
4130 }
4131
4132 cupsFilePrintf(fp, ".\n.\n.\n%s\n.\n%s\n%s\n",
4133 ServerName, ServerName, ServerAdmin);
4134 cupsFileClose(fp);
4135
8ca02f3c 4136 cupsdLogMessage(CUPSD_LOG_INFO,
4137 "Generating SSL server key and certificate...");
4138
4139 argv[0] = "openssl";
4140 argv[1] = "req";
4141 argv[2] = "-new";
4142 argv[3] = "-x509";
4143 argv[4] = "-keyout";
4144 argv[5] = ServerKey;
4145 argv[6] = "-out";
4146 argv[7] = ServerCertificate;
4147 argv[8] = "-days";
4148 argv[9] = "3650";
4149 argv[10] = "-nodes";
4150 argv[11] = NULL;
4151
4152 cupsdLoadEnv(envp, MAX_ENV);
4153
d09495fa 4154 infofd = open(infofile, O_RDONLY);
4155
a4924f6c
MS
4156 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4157 &pid))
d09495fa 4158 {
4159 close(infofd);
4160 unlink(infofile);
8ca02f3c 4161 return (0);
d09495fa 4162 }
4163
4164 close(infofd);
4165 unlink(infofile);
8ca02f3c 4166
4167 while (waitpid(pid, &status, 0) < 0)
4168 if (errno != EINTR)
4169 {
4170 status = 1;
4171 break;
4172 }
4173
4174 cupsdFinishProcess(pid, command, sizeof(command));
4175
4176 if (status)
4177 {
4178 if (WIFEXITED(status))
4179 cupsdLogMessage(CUPSD_LOG_ERROR,
4180 "Unable to create SSL server key and certificate - "
4181 "the openssl command stopped with status %d!",
4182 WEXITSTATUS(status));
4183 else
4184 cupsdLogMessage(CUPSD_LOG_ERROR,
4185 "Unable to create SSL server key and certificate - "
4186 "the openssl command crashed on signal %d!",
4187 WTERMSIG(status));
4188 }
4189 else
4190 {
4191 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4192 ServerKey);
4193 cupsdLogMessage(CUPSD_LOG_INFO,
4194 "Created SSL server certificate file \"%s\"...",
4195 ServerCertificate);
4196 }
4197
4198 return (!status);
4199
4200#elif defined(HAVE_GNUTLS)
4744bd90 4201 gnutls_x509_crt crt; /* Self-signed certificate */
4202 gnutls_x509_privkey key; /* Encryption key */
4203 cups_lang_t *language; /* Default language info */
4204 cups_file_t *fp; /* Key/cert file */
4205 unsigned char buffer[8192]; /* Buffer for x509 data */
4206 size_t bytes; /* Number of bytes of data */
4207 unsigned char serial[4]; /* Serial number buffer */
4208 time_t curtime; /* Current time */
4209 int result; /* Result of GNU TLS calls */
4210
4211
4212 /*
4213 * Create the encryption key...
4214 */
4215
8ca02f3c 4216 cupsdLogMessage(CUPSD_LOG_INFO, "Generating SSL server key...");
4744bd90 4217
4218 gnutls_x509_privkey_init(&key);
4219 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
4220
4221 /*
4222 * Save it...
4223 */
4224
4225 bytes = sizeof(buffer);
4226
4227 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM,
4228 buffer, &bytes)) < 0)
4229 {
8ca02f3c 4230 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to export SSL server key - %s",
4744bd90 4231 gnutls_strerror(result));
4232 gnutls_x509_privkey_deinit(key);
8ca02f3c 4233 return (0);
4744bd90 4234 }
4235 else if ((fp = cupsFileOpen(ServerKey, "w")) != NULL)
4236 {
4237 cupsFileWrite(fp, (char *)buffer, bytes);
4238 cupsFileClose(fp);
4239
8ca02f3c 4240 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4744bd90 4241 ServerKey);
4242 }
4243 else
4244 {
4245 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4246 "Unable to create SSL server key file \"%s\" - %s",
4744bd90 4247 ServerKey, strerror(errno));
4248 gnutls_x509_privkey_deinit(key);
8ca02f3c 4249 return (0);
4744bd90 4250 }
4251
4252 /*
4253 * Create the self-signed certificate...
4254 */
4255
8ca02f3c 4256 cupsdLogMessage(CUPSD_LOG_INFO, "Generating self-signed SSL certificate...");
4744bd90 4257
4258 language = cupsLangDefault();
4259 curtime = time(NULL);
4260 serial[0] = curtime >> 24;
4261 serial[1] = curtime >> 16;
4262 serial[2] = curtime >> 8;
4263 serial[3] = curtime;
4264
4265 gnutls_x509_crt_init(&crt);
4266 if (strlen(language->language) == 5)
4267 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4268 language->language + 3, 2);
4269 else
4270 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4271 "US", 2);
4272 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
4273 ServerName, strlen(ServerName));
4274 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
4275 ServerName, strlen(ServerName));
4276 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
4277 0, "Unknown", 7);
4278 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
4279 "Unknown", 7);
4280 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
4281 "Unknown", 7);
4282 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
4283 ServerAdmin, strlen(ServerAdmin));
4284 gnutls_x509_crt_set_key(crt, key);
4285 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
4286 gnutls_x509_crt_set_activation_time(crt, curtime);
4287 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
4288 gnutls_x509_crt_set_ca_status(crt, 0);
4289 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME,
4290 ServerName);
4291 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
4292 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
4293 gnutls_x509_crt_set_version(crt, 3);
4294
4295 bytes = sizeof(buffer);
4296 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
4297 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
4298
4299 gnutls_x509_crt_sign(crt, crt, key);
4300
4301 /*
4302 * Save it...
4303 */
4304
4305 bytes = sizeof(buffer);
4306 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM,
4307 buffer, &bytes)) < 0)
4308 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4309 "Unable to export SSL server certificate - %s",
4744bd90 4310 gnutls_strerror(result));
4311 else if ((fp = cupsFileOpen(ServerCertificate, "w")) != NULL)
4312 {
4313 cupsFileWrite(fp, (char *)buffer, bytes);
4314 cupsFileClose(fp);
4315
4316 cupsdLogMessage(CUPSD_LOG_INFO,
8ca02f3c 4317 "Created SSL server certificate file \"%s\"...",
4744bd90 4318 ServerCertificate);
4319 }
4320 else
4321 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4322 "Unable to create SSL server certificate file \"%s\" - %s",
4744bd90 4323 ServerCertificate, strerror(errno));
4324
4325 /*
4326 * Cleanup...
4327 */
4328
4329 gnutls_x509_crt_deinit(crt);
4330 gnutls_x509_privkey_deinit(key);
8ca02f3c 4331
4332 return (1);
4333
4334#elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
b86bc4cf 4335 int pid, /* Process ID of command */
4336 status; /* Status of command */
4337 char command[1024], /* Command */
4338 *argv[4], /* Command-line arguments */
4339 *envp[MAX_ENV + 1], /* Environment variables */
4340 keychain[1024], /* Keychain argument */
4341 infofile[1024]; /* Type-in information for cert */
4342 cups_file_t *fp; /* Seed/info file */
4343 int infofd; /* Info file descriptor */
8ca02f3c 4344
4345
4346 /*
b86bc4cf 4347 * Run the "certtool" command to generate a self-signed certificate...
8ca02f3c 4348 */
4349
4350 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
4351 {
4352 cupsdLogMessage(CUPSD_LOG_ERROR,
4353 "No SSL certificate and certtool command not found!");
4354 return (0);
4355 }
4356
b86bc4cf 4357 /*
4358 * Create a file with the certificate information fields...
4359 *
4360 * Note: This assumes that the default questions are asked by the certtool
4361 * command...
4362 */
4363
4364 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4365 {
4366 cupsdLogMessage(CUPSD_LOG_ERROR,
4367 "Unable to create certificate information file %s - %s",
4368 infofile, strerror(errno));
4369 return (0);
4370 }
4371
4372 cupsFilePrintf(fp, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4373 con->servername, con->servername, ServerAdmin);
4374 cupsFileClose(fp);
4375
8ca02f3c 4376 cupsdLogMessage(CUPSD_LOG_INFO,
4377 "Generating SSL server key and certificate...");
4378
4379 snprintf(keychain, sizeof(keychain), "k=%s", ServerCertificate);
4380
4381 argv[0] = "certtool";
4382 argv[1] = "c";
b86bc4cf 4383 argv[2] = keychain;
4384 argv[3] = NULL;
8ca02f3c 4385
4386 cupsdLoadEnv(envp, MAX_ENV);
4387
b86bc4cf 4388 infofd = open(infofile, O_RDONLY);
4389
a4924f6c
MS
4390 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4391 &pid))
b86bc4cf 4392 {
4393 close(infofd);
4394 unlink(infofile);
8ca02f3c 4395 return (0);
b86bc4cf 4396 }
4397
4398 close(infofd);
4399 unlink(infofile);
8ca02f3c 4400
4401 while (waitpid(pid, &status, 0) < 0)
4402 if (errno != EINTR)
4403 {
4404 status = 1;
4405 break;
4406 }
4407
4408 cupsdFinishProcess(pid, command, sizeof(command));
4409
4410 if (status)
4411 {
4412 if (WIFEXITED(status))
4413 cupsdLogMessage(CUPSD_LOG_ERROR,
4414 "Unable to create SSL server key and certificate - "
4415 "the certtool command stopped with status %d!",
4416 WEXITSTATUS(status));
4417 else
4418 cupsdLogMessage(CUPSD_LOG_ERROR,
4419 "Unable to create SSL server key and certificate - "
4420 "the certtool command crashed on signal %d!",
4421 WTERMSIG(status));
4422 }
4423 else
4424 {
4425 cupsdLogMessage(CUPSD_LOG_INFO,
4426 "Created SSL server certificate file \"%s\"...",
4427 ServerCertificate);
4428 }
4429
4430 return (!status);
4431
4432#else
4433 return (0);
4434#endif /* HAVE_LIBSSL && HAVE_WAITPID */
4744bd90 4435}
8ca02f3c 4436#endif /* HAVE_SSL */
4744bd90 4437
4438
ef416fc2 4439/*
4440 * 'pipe_command()' - Pipe the output of a command to the remote client.
4441 */
4442
4443static int /* O - Process ID */
4444pipe_command(cupsd_client_t *con, /* I - Client connection */
4445 int infile, /* I - Standard input for command */
4446 int *outfile, /* O - Standard output for command */
4447 char *command, /* I - Command to run */
4448 char *options, /* I - Options for command */
4449 int root) /* I - Run as root? */
4450{
4451 int i; /* Looping var */
4452 int pid; /* Process ID */
b423cd4c 4453 char *commptr, /* Command string pointer */
4454 commch; /* Command string character */
ef416fc2 4455 char *uriptr; /* URI string pointer */
4456 int fds[2]; /* Pipe FDs */
4457 int argc; /* Number of arguments */
4458 int envc; /* Number of environment variables */
4459 char argbuf[10240], /* Argument buffer */
4460 *argv[100], /* Argument strings */
b94498cf 4461 *envp[MAX_ENV + 20]; /* Environment variables */
5bd77a73 4462 char auth_type[256], /* CUPSD_AUTH_TYPE environment variable */
b94498cf 4463 content_length[1024], /* CONTENT_LENGTH environment variable */
ef416fc2 4464 content_type[1024], /* CONTENT_TYPE environment variable */
4465 http_cookie[32768], /* HTTP_COOKIE environment variable */
f7deaa1a 4466 http_referer[1024], /* HTTP_REFERER environment variable */
ef416fc2 4467 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
4468 lang[1024], /* LANG environment variable */
b423cd4c 4469 path_info[1024], /* PATH_INFO environment variable */
ef416fc2 4470 remote_addr[1024], /* REMOTE_ADDR environment variable */
4471 remote_host[1024], /* REMOTE_HOST environment variable */
4472 remote_user[1024], /* REMOTE_USER environment variable */
b94498cf 4473 script_filename[1024], /* SCRIPT_FILENAME environment variable */
ef416fc2 4474 script_name[1024], /* SCRIPT_NAME environment variable */
4475 server_name[1024], /* SERVER_NAME environment variable */
4476 server_port[1024]; /* SERVER_PORT environment variable */
7dfedb92 4477 ipp_attribute_t *attr; /* attributes-natural-language attribute */
5bd77a73
MS
4478#ifdef HAVE_GSSAPI
4479 krb5_ccache ccache = NULL; /* Kerberos credentials */
e6013cfa 4480# if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
5bd77a73 4481 char krb5ccname[1024]; /* KRB5CCNAME environment variable */
e6013cfa 4482# endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
5bd77a73 4483#endif /* HAVE_GSSAPI */
ef416fc2 4484
4485
4486 /*
4487 * Parse a copy of the options string, which is of the form:
4488 *
b423cd4c 4489 * argument+argument+argument
4490 * ?argument+argument+argument
4491 * param=value&param=value
4492 * ?param=value&param=value
4493 * /name?argument+argument+argument
4494 * /name?param=value&param=value
ef416fc2 4495 *
4496 * If the string contains an "=" character after the initial name,
4497 * then we treat it as a HTTP GET form request and make a copy of
4498 * the remaining string for the environment variable.
4499 *
4500 * The string is always parsed out as command-line arguments, to
4501 * be consistent with Apache...
4502 */
4503
4504 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4505 "pipe_command: command=\"%s\", options=\"%s\"",
f301802f 4506 command, options ? options : "(null)");
ef416fc2 4507
b86bc4cf 4508 argv[0] = command;
ef416fc2 4509
b423cd4c 4510 if (options)
4511 strlcpy(argbuf, options, sizeof(argbuf));
4512 else
4513 argbuf[0] = '\0';
4514
4515 if (argbuf[0] == '/')
ef416fc2 4516 {
4517 /*
b423cd4c 4518 * Found some trailing path information, set PATH_INFO...
ef416fc2 4519 */
4520
b423cd4c 4521 if ((commptr = strchr(argbuf, '?')) == NULL)
4522 commptr = argbuf + strlen(argbuf);
ef416fc2 4523
b423cd4c 4524 commch = *commptr;
4525 *commptr = '\0';
4526 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
4527 *commptr = commch;
4528 }
4529 else
4530 {
4531 commptr = argbuf;
4532 path_info[0] = '\0';
b94498cf 4533
4534 if (*commptr == ' ')
4535 commptr ++;
b423cd4c 4536 }
ef416fc2 4537
b86bc4cf 4538 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
b423cd4c 4539 {
4540 commptr ++;
b86bc4cf 4541 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
b423cd4c 4542 }
ef416fc2 4543
b423cd4c 4544 argc = 1;
ef416fc2 4545
b423cd4c 4546 if (*commptr)
4547 {
4548 argv[argc ++] = commptr;
ef416fc2 4549
b423cd4c 4550 for (; *commptr && argc < 99; commptr ++)
4551 {
ef416fc2 4552 /*
b423cd4c 4553 * Break arguments whenever we see a + or space...
ef416fc2 4554 */
4555
b423cd4c 4556 if (*commptr == ' ' || *commptr == '+')
4557 {
4558 while (*commptr == ' ' || *commptr == '+')
4559 *commptr++ = '\0';
ef416fc2 4560
b423cd4c 4561 /*
4562 * If we don't have a blank string, save it as another argument...
4563 */
ef416fc2 4564
b423cd4c 4565 if (*commptr)
4566 {
4567 argv[argc] = commptr;
4568 argc ++;
4569 }
4570 else
4571 break;
4572 }
4573 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
4574 isxdigit(commptr[2] & 255))
4575 {
4576 /*
4577 * Convert the %xx notation to the individual character.
4578 */
ef416fc2 4579
b423cd4c 4580 if (commptr[1] >= '0' && commptr[1] <= '9')
4581 *commptr = (commptr[1] - '0') << 4;
4582 else
4583 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
ef416fc2 4584
b423cd4c 4585 if (commptr[2] >= '0' && commptr[2] <= '9')
4586 *commptr |= commptr[2] - '0';
4587 else
4588 *commptr |= tolower(commptr[2]) - 'a' + 10;
ef416fc2 4589
b423cd4c 4590 _cups_strcpy(commptr + 1, commptr + 3);
ef416fc2 4591
b423cd4c 4592 /*
4593 * Check for a %00 and break if that is the case...
4594 */
ef416fc2 4595
b423cd4c 4596 if (!*commptr)
4597 break;
4598 }
ef416fc2 4599 }
4600 }
4601
4602 argv[argc] = NULL;
4603
ef416fc2 4604 /*
4605 * Setup the environment variables as needed...
4606 */
4607
b94498cf 4608 if (con->username[0])
4609 {
5bd77a73 4610 snprintf(auth_type, sizeof(auth_type), "CUPSD_AUTH_TYPE=%s",
b94498cf 4611 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
4612
4613 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
4614 *uriptr = '\0';
4615 }
4616 else
4617 auth_type[0] = '\0';
4618
7dfedb92
MS
4619 if (con->request &&
4620 (attr = ippFindAttribute(con->request, "attributes-natural-language",
4621 IPP_TAG_LANGUAGE)) != NULL)
4622 {
4623 switch (strlen(attr->values[0].string.text))
4624 {
4625 default :
4626 /*
4627 * This is an unknown or badly formatted language code; use
4628 * the POSIX locale...
4629 */
4630
4631 strcpy(lang, "LANG=C");
4632 break;
4633
4634 case 2 :
4635 /*
4636 * Just the language code (ll)...
4637 */
4638
4639 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
4640 attr->values[0].string.text);
4641 break;
4642
4643 case 5 :
4644 /*
4645 * Language and country code (ll-cc)...
4646 */
4647
4648 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
4649 attr->values[0].string.text[0],
4650 attr->values[0].string.text[1],
4651 toupper(attr->values[0].string.text[3] & 255),
4652 toupper(attr->values[0].string.text[4] & 255));
4653 break;
4654 }
4655 }
4656 else if (con->language)
4657 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
ef416fc2 4658 else
4659 strcpy(lang, "LANG=C");
4660
4661 strcpy(remote_addr, "REMOTE_ADDR=");
4662 httpAddrString(con->http.hostaddr, remote_addr + 12,
4663 sizeof(remote_addr) - 12);
4664
4665 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
4666 con->http.hostname);
4667
4668 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
4669 if ((uriptr = strchr(script_name, '?')) != NULL)
4670 *uriptr = '\0';
4671
b94498cf 4672 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
4673 DocumentRoot, script_name + 12);
4674
ef416fc2 4675 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
4676
4677 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
4678 con->servername);
4679
4680 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
4681
b94498cf 4682 if (auth_type[0])
4683 envp[envc ++] = auth_type;
4684
ef416fc2 4685 envp[envc ++] = lang;
4686 envp[envc ++] = "REDIRECT_STATUS=1";
b94498cf 4687 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
ef416fc2 4688 envp[envc ++] = server_name;
4689 envp[envc ++] = server_port;
4690 envp[envc ++] = remote_addr;
4691 envp[envc ++] = remote_host;
4692 envp[envc ++] = script_name;
b94498cf 4693 envp[envc ++] = script_filename;
ef416fc2 4694
b423cd4c 4695 if (path_info[0])
4696 envp[envc ++] = path_info;
4697
ef416fc2 4698 if (con->username[0])
4699 {
4700 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
4701
4702 envp[envc ++] = remote_user;
5bd77a73
MS
4703
4704 /*
4705 * Save Kerberos credentials, if any...
4706 */
4707
4708#ifdef HAVE_GSSAPI
4709 if (con->gss_have_creds)
4710 {
4711# if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4712 cupsdLogMessage(CUPSD_LOG_INFO,
4713 "Sorry, your version of Kerberos does not support "
4714 "delegated credentials!");
4715
4716# else
4717 krb5_error_code error; /* Kerberos error code */
4718 OM_uint32 major_status, /* Major status code */
4719 minor_status; /* Minor status code */
4720 krb5_principal principal; /* Kerberos principal */
4721
4722
4723# ifdef __APPLE__
4724 /*
4725 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4726 * to use it...
4727 */
4728
4729 if (krb5_init_context != NULL)
4730 {
4731# endif /* __APPLE__ */
4732
0af14961
MS
4733 if (!KerberosInitialized)
4734 {
4735 /*
4736 * Setup a Kerberos context for the scheduler to use...
4737 */
4738
4739 KerberosInitialized = 1;
4740
4741 if (krb5_init_context(&KerberosContext))
4742 {
4743 KerberosContext = NULL;
4744
4745 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to initialize Kerberos context");
4746 }
4747 }
4748
5bd77a73
MS
4749 /*
4750 * We MUST create a file-based cache because memory-based caches are
4751 * only valid for the current process/address space.
4752 *
4753 * Due to various bugs/features in different versions of Kerberos, we
4754 * need either the krb5_cc_new_unique() function or Heimdal's version
4755 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4756 * can be passed to the backend. These functions create a temporary
4757 * file (typically in /tmp) containing the cached credentials, which
4758 * are removed when we have successfully printed a job.
4759 */
4760
0af14961
MS
4761 if (KerberosContext)
4762 {
5bd77a73 4763# ifdef HAVE_KRB5_CC_NEW_UNIQUE
0af14961
MS
4764 if ((error = krb5_cc_new_unique(KerberosContext, "FILE", NULL,
4765 &ccache)) != 0)
5bd77a73 4766# else /* HAVE_HEIMDAL */
0af14961
MS
4767 if ((error = krb5_cc_gen_new(KerberosContext, &krb5_fcc_ops,
4768 &ccache)) != 0)
5bd77a73 4769# endif /* HAVE_KRB5_CC_NEW_UNIQUE */
5bd77a73 4770 {
0af14961
MS
4771 cupsdLogMessage(CUPSD_LOG_ERROR,
4772 "Unable to create new credentials cache (%d/%s)",
4773 error, strerror(errno));
4774 ccache = NULL;
4775 }
4776 else if ((error = krb5_parse_name(KerberosContext, con->username,
4777 &principal)) != 0)
4778 {
4779 cupsdLogMessage(CUPSD_LOG_ERROR,
4780 "Unable to parse kerberos username (%d/%s)", error,
4781 strerror(errno));
4782 krb5_cc_destroy(KerberosContext, ccache);
4783 ccache = NULL;
4784 }
4785 else if ((error = krb5_cc_initialize(KerberosContext, ccache,
4786 principal)))
4787 {
4788 cupsdLogMessage(CUPSD_LOG_ERROR,
4789 "Unable to initialize credentials cache (%d/%s)", error,
4790 strerror(errno));
5bd77a73 4791 krb5_cc_destroy(KerberosContext, ccache);
0af14961 4792 krb5_free_principal(KerberosContext, principal);
5bd77a73
MS
4793 ccache = NULL;
4794 }
4795 else
4796 {
0af14961
MS
4797 krb5_free_principal(KerberosContext, principal);
4798
5bd77a73 4799 /*
0af14961 4800 * Copy the user's credentials to the new cache file...
5bd77a73
MS
4801 */
4802
0af14961
MS
4803 major_status = gss_krb5_copy_ccache(&minor_status,
4804 con->gss_delegated_cred, ccache);
5bd77a73 4805
0af14961
MS
4806 if (GSS_ERROR(major_status))
4807 {
4808 cupsdLogGSSMessage(CUPSD_LOG_ERROR, major_status, minor_status,
4809 "Unable to import client credentials cache");
4810 krb5_cc_destroy(KerberosContext, ccache);
4811 ccache = NULL;
4812 }
4813 else
4814 {
4815 /*
4816 * Add the KRB5CCNAME environment variable to the job so that the
4817 * backend can use the credentials when printing.
4818 */
4819
4820 snprintf(krb5ccname, sizeof(krb5ccname), "KRB5CCNAME=FILE:%s",
4821 krb5_cc_get_name(KerberosContext, ccache));
4822 envp[envc++] = krb5ccname;
4823
4824 if (!RunUser)
4825 chown(krb5_cc_get_name(KerberosContext, ccache), User, Group);
4826 }
4827 }
5bd77a73
MS
4828 }
4829# ifdef __APPLE__
4830 }
4831# endif /* __APPLE__ */
4832# endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4833 }
4834#endif /* HAVE_GSSAPI */
ef416fc2 4835 }
4836
4837 if (con->http.version == HTTP_1_1)
4838 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
4839 else if (con->http.version == HTTP_1_0)
4840 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
4841 else
4842 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
4843
4844 if (con->http.cookie)
4845 {
4846 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
4847 con->http.cookie);
4848 envp[envc ++] = http_cookie;
4849 }
4850
4851 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
4852 {
4853 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
4854 con->http.fields[HTTP_FIELD_USER_AGENT]);
4855 envp[envc ++] = http_user_agent;
4856 }
4857
f7deaa1a 4858 if (con->http.fields[HTTP_FIELD_REFERER][0])
4859 {
4860 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
4861 con->http.fields[HTTP_FIELD_REFERER]);
4862 envp[envc ++] = http_referer;
4863 }
4864
ef416fc2 4865 if (con->operation == HTTP_GET)
4866 {
ef416fc2 4867 envp[envc ++] = "REQUEST_METHOD=GET";
4868
b86bc4cf 4869 if (con->query_string)
ef416fc2 4870 {
4871 /*
4872 * Add GET form variables after ?...
4873 */
4874
b86bc4cf 4875 envp[envc ++] = con->query_string;
ef416fc2 4876 }
3dfe78b3
MS
4877 else
4878 envp[envc ++] = "QUERY_STRING=";
ef416fc2 4879 }
4880 else
4881 {
e1d6a774 4882 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
4883 CUPS_LLCAST con->bytes);
ef416fc2 4884 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
4885 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
4886
4887 envp[envc ++] = "REQUEST_METHOD=POST";
4888 envp[envc ++] = content_length;
4889 envp[envc ++] = content_type;
4890 }
4891
4892 /*
4893 * Tell the CGI if we are using encryption...
4894 */
4895
a74454a7 4896 if (con->http.tls)
ef416fc2 4897 envp[envc ++] = "HTTPS=ON";
4898
4899 /*
4900 * Terminate the environment array...
4901 */
4902
4903 envp[envc] = NULL;
4904
4905 if (LogLevel == CUPSD_LOG_DEBUG2)
4906 {
4907 for (i = 0; i < argc; i ++)
4908 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4909 "pipe_command: argv[%d] = \"%s\"", i, argv[i]);
4910 for (i = 0; i < envc; i ++)
4911 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4912 "pipe_command: envp[%d] = \"%s\"", i, envp[i]);
4913 }
4914
4915 /*
4916 * Create a pipe for the output...
4917 */
4918
4919 if (cupsdOpenPipe(fds))
4920 {
ef416fc2 4921 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create pipes for CGI %s - %s",
4922 argv[0], strerror(errno));
4923 return (0);
4924 }
4925
4926 /*
4927 * Then execute the command...
4928 */
4929
4930 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
a4924f6c 4931 -1, -1, root, DefaultProfile, &pid) < 0)
ef416fc2 4932 {
4933 /*
4934 * Error - can't fork!
4935 */
4936
4937 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork for CGI %s - %s", argv[0],
4938 strerror(errno));
4939
4940 cupsdClosePipe(fds);
4941 pid = 0;
4942 }
4943 else
4944 {
4945 /*
4946 * Fork successful - return the PID...
4947 */
4948
4949 if (con->username[0])
5bd77a73
MS
4950#ifdef HAVE_GSSAPI
4951 cupsdAddCert(pid, con->username, ccache);
4952#else
4953 cupsdAddCert(pid, con->username, NULL);
4954#endif /* HAVE_GSSAPI */
ef416fc2 4955
355e94dc
MS
4956 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] %s started - PID = %d",
4957 command, pid);
ef416fc2 4958
4959 *outfile = fds[0];
4960 close(fds[1]);
4961 }
4962
ef416fc2 4963 return (pid);
4964}
4965
4966
4967/*
a74454a7 4968 * 'write_file()' - Send a file via HTTP.
e1d6a774 4969 */
4970
4971static int /* O - 0 on failure, 1 on success */
a74454a7 4972write_file(cupsd_client_t *con, /* I - Client connection */
4973 http_status_t code, /* I - HTTP status */
4974 char *filename, /* I - Filename */
4975 char *type, /* I - File type */
4976 struct stat *filestats) /* O - File information */
e1d6a774 4977{
4978 con->file = open(filename, O_RDONLY);
4979
355e94dc 4980 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_file: %d file=%d", con->http.fd,
e1d6a774 4981 con->file);
4982
4983 if (con->file < 0)
4984 return (0);
4985
4986 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4987
4988 con->pipe_pid = 0;
4989
5bd77a73 4990 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
e1d6a774 4991 return (0);
4992
4993 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
4994 httpGetDateString(filestats->st_mtime)) < 0)
4995 return (0);
4996 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
4997 CUPS_LLCAST filestats->st_size) < 0)
4998 return (0);
4999 if (httpPrintf(HTTP(con), "\r\n") < 0)
5000 return (0);
5001
07725fee 5002 if (cupsdFlushHeader(con) < 0)
5003 return (0);
d09495fa 5004
e1d6a774 5005 con->http.data_encoding = HTTP_ENCODE_LENGTH;
5006 con->http.data_remaining = filestats->st_size;
5007
5008 if (con->http.data_remaining <= INT_MAX)
5009 con->http._data_remaining = con->http.data_remaining;
5010 else
5011 con->http._data_remaining = INT_MAX;
5012
f7deaa1a 5013 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
5014 (cupsd_selfunc_t)cupsdWriteClient, con);
e1d6a774 5015
5016 return (1);
5017}
5018
5019
5020/*
f899b121 5021 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5022 */
5023
5024static void
5025write_pipe(cupsd_client_t *con) /* I - Client connection */
5026{
5027 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d...",
5028 con->file);
5029
5030 con->file_ready = 1;
5031
5032 cupsdRemoveSelect(con->file);
5033 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
5034}
5035
5036
5037/*
b19ccc9e 5038 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".
ef416fc2 5039 */