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