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