]> git.ipfire.org Git - thirdparty/cups.git/blame - scheduler/client.c
Merge changes from CUPS 1.4svn-r7582.
[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)
ef416fc2 2785 con->http.activity = time(NULL);
ef416fc2 2786 }
2787
4744bd90 2788 if (bytes > 0)
ef416fc2 2789 {
4744bd90 2790 if (httpWrite2(HTTP(con), buf, bytes) < 0)
2791 {
2792 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2793 "cupsdWriteClient: %d Write of %d bytes failed!",
2794 con->http.fd, bytes);
ef416fc2 2795
4744bd90 2796 cupsdCloseClient(con);
f7deaa1a 2797 return;
4744bd90 2798 }
ef416fc2 2799
01ce6322
MS
2800 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED)
2801 httpFlushWrite(HTTP(con));
ae71f5de 2802
4744bd90 2803 con->bytes += bytes;
ef416fc2 2804
4744bd90 2805 if (con->http.state == HTTP_WAITING)
2806 bytes = 0;
2807 }
ef416fc2 2808 }
2809
2810 if (bytes <= 0)
2811 {
2812 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdWriteClient: %d bytes < 0",
2813 con->http.fd);
2814
2815 cupsdLogRequest(con, HTTP_OK);
2816
2817 httpFlushWrite(HTTP(con));
2818
07725fee 2819 if (con->http.data_encoding == HTTP_ENCODE_CHUNKED && con->sent_header == 1)
ef416fc2 2820 {
07725fee 2821 if (httpWrite2(HTTP(con), "", 0) < 0)
ef416fc2 2822 {
2823 cupsdCloseClient(con);
f7deaa1a 2824 return;
ef416fc2 2825 }
2826 }
2827
2828 con->http.state = HTTP_WAITING;
2829
f7deaa1a 2830 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient, NULL, con);
ef416fc2 2831
2832 if (con->file >= 0)
2833 {
f7deaa1a 2834 cupsdRemoveSelect(con->file);
ef416fc2 2835
2836 if (con->pipe_pid)
2837 cupsdEndProcess(con->pipe_pid, 0);
2838
2839 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2840 "cupsdWriteClient: %d Closing data file %d.",
2841 con->http.fd, con->file);
2842
2843 close(con->file);
2844 con->file = -1;
2845 con->pipe_pid = 0;
2846 }
2847
2848 if (con->filename)
2849 {
2850 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2851 "cupsdWriteClient: %d Removing temp file %s",
2852 con->http.fd, con->filename);
2853 unlink(con->filename);
2854 cupsdClearString(&con->filename);
2855 }
2856
2abf387c 2857 if (con->request)
ef416fc2 2858 {
2859 ippDelete(con->request);
2860 con->request = NULL;
2861 }
2862
2abf387c 2863 if (con->response)
ef416fc2 2864 {
2865 ippDelete(con->response);
2866 con->response = NULL;
2867 }
2868
2869 cupsdClearString(&con->command);
2870 cupsdClearString(&con->options);
b86bc4cf 2871 cupsdClearString(&con->query_string);
ef416fc2 2872
2873 if (!con->http.keep_alive)
2874 {
2875 cupsdCloseClient(con);
f7deaa1a 2876 return;
ef416fc2 2877 }
2878 }
2879
2880 con->http.activity = time(NULL);
f7deaa1a 2881}
ef416fc2 2882
f7deaa1a 2883
e1d6a774 2884/*
2885 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2886 */
2887
2888static int /* O - 1 if modified since */
2889check_if_modified(
2890 cupsd_client_t *con, /* I - Client connection */
2891 struct stat *filestats) /* I - File information */
2892{
2893 char *ptr; /* Pointer into field */
2894 time_t date; /* Time/date value */
2895 off_t size; /* Size/length value */
2896
2897
2898 size = 0;
2899 date = 0;
2900 ptr = con->http.fields[HTTP_FIELD_IF_MODIFIED_SINCE];
2901
2902 if (*ptr == '\0')
2903 return (1);
2904
2905 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2906 "check_if_modified: %d If-Modified-Since=\"%s\"",
2907 con->http.fd, ptr);
2908
2909 while (*ptr != '\0')
2910 {
2911 while (isspace(*ptr) || *ptr == ';')
2912 ptr ++;
2913
2914 if (strncasecmp(ptr, "length=", 7) == 0)
2915 {
2916 ptr += 7;
2917 size = strtoll(ptr, NULL, 10);
2918
2919 while (isdigit(*ptr))
2920 ptr ++;
2921 }
2922 else if (isalpha(*ptr))
2923 {
2924 date = httpGetDateTime(ptr);
2925 while (*ptr != '\0' && *ptr != ';')
2926 ptr ++;
2927 }
e53920b9 2928 else
2929 ptr ++;
e1d6a774 2930 }
2931
2932 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2933 "check_if_modified: %d sizes=" CUPS_LLFMT ","
2934 CUPS_LLFMT " dates=%d,%d",
2935 con->http.fd, CUPS_LLCAST size,
2936 CUPS_LLCAST filestats->st_size, (int)date,
2937 (int)filestats->st_mtime);
2938
2939 return ((size != filestats->st_size && size != 0) ||
2940 (date < filestats->st_mtime && date != 0) ||
2941 (size == 0 && date == 0));
2942}
2943
2944
3dfe78b3
MS
2945/*
2946 * 'compare_clients()' - Compare two client connections.
2947 */
2948
2949static int /* O - Result of comparison */
2950compare_clients(cupsd_client_t *a, /* I - First client */
2951 cupsd_client_t *b, /* I - Second client */
2952 void *data) /* I - User data (not used) */
2953{
2954 (void)data;
2955
2956 if (a == b)
2957 return (0);
2958 else if (a < b)
2959 return (-1);
2960 else
2961 return (1);
2962}
2963
2964
80ca4592 2965#ifdef HAVE_SSL
e1d6a774 2966/*
2967 * 'encrypt_client()' - Enable encryption for the client...
2968 */
2969
2970static int /* O - 1 on success, 0 on error */
2971encrypt_client(cupsd_client_t *con) /* I - Client to encrypt */
2972{
80ca4592 2973# ifdef HAVE_LIBSSL
e1d6a774 2974 SSL_CTX *context; /* Context for encryption */
2975 SSL *conn; /* Connection for encryption */
411affcf 2976 BIO *bio; /* BIO data */
e1d6a774 2977 unsigned long error; /* Error code */
2978
2979
8ca02f3c 2980 /*
2981 * Verify that we have a certificate...
2982 */
2983
2984 if (access(ServerKey, 0) || access(ServerCertificate, 0))
2985 {
2986 /*
2987 * Nope, make a self-signed certificate...
2988 */
2989
b86bc4cf 2990 if (!make_certificate(con))
8ca02f3c 2991 return (0);
2992 }
2993
e1d6a774 2994 /*
2995 * Create the SSL context and accept the connection...
2996 */
2997
2998 context = SSL_CTX_new(SSLv23_server_method());
2999
3000 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
3001 SSL_CTX_use_PrivateKey_file(context, ServerKey, SSL_FILETYPE_PEM);
3002 SSL_CTX_use_certificate_file(context, ServerCertificate, SSL_FILETYPE_PEM);
3003
411affcf 3004 bio = BIO_new(_httpBIOMethods());
3005 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)HTTP(con));
3006
e1d6a774 3007 conn = SSL_new(context);
411affcf 3008 SSL_set_bio(conn, bio, bio);
e1d6a774 3009
e1d6a774 3010 if (SSL_accept(conn) != 1)
3011 {
3012 cupsdLogMessage(CUPSD_LOG_ERROR,
3013 "encrypt_client: Unable to encrypt connection from %s!",
3014 con->http.hostname);
3015
3016 while ((error = ERR_get_error()) != 0)
3017 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
3018 ERR_error_string(error, NULL));
3019
3020 SSL_CTX_free(context);
3021 SSL_free(conn);
3022 return (0);
3023 }
3024
3025 cupsdLogMessage(CUPSD_LOG_DEBUG,
3026 "encrypt_client: %d Connection from %s now encrypted.",
3027 con->http.fd, con->http.hostname);
3028
3029 con->http.tls = conn;
3030 return (1);
f7deaa1a 3031
80ca4592 3032# elif defined(HAVE_GNUTLS)
e1d6a774 3033 http_tls_t *conn; /* TLS session object */
3034 int error; /* Error code */
3035 gnutls_certificate_server_credentials *credentials;
3036 /* TLS credentials */
3037
3038
3039 /*
3040 * Verify that we have a certificate...
3041 */
3042
3043 if (access(ServerKey, 0) || access(ServerCertificate, 0))
3044 {
3045 /*
3046 * Nope, make a self-signed certificate...
3047 */
3048
b86bc4cf 3049 if (!make_certificate(con))
8ca02f3c 3050 return (0);
e1d6a774 3051 }
3052
3053 /*
3054 * Create the SSL object and perform the SSL handshake...
3055 */
3056
89d46774 3057 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
e1d6a774 3058
3059 if (conn == NULL)
3060 return (0);
3061
3062 credentials = (gnutls_certificate_server_credentials *)
3063 malloc(sizeof(gnutls_certificate_server_credentials));
3064 if (credentials == NULL)
3065 {
3066 cupsdLogMessage(CUPSD_LOG_ERROR,
3067 "encrypt_client: Unable to encrypt connection from %s!",
3068 con->http.hostname);
3069 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s", strerror(errno));
3070
3071 free(conn);
3072 return (0);
3073 }
3074
3075 gnutls_certificate_allocate_credentials(credentials);
f7deaa1a 3076 gnutls_certificate_set_x509_key_file(*credentials, ServerCertificate,
e1d6a774 3077 ServerKey, GNUTLS_X509_FMT_PEM);
3078
3079 gnutls_init(&(conn->session), GNUTLS_SERVER);
3080 gnutls_set_default_priority(conn->session);
3081 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
411affcf 3082 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)HTTP(con));
3083 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
3084 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
e1d6a774 3085
3086 error = gnutls_handshake(conn->session);
3087
3088 if (error != GNUTLS_E_SUCCESS)
3089 {
3090 cupsdLogMessage(CUPSD_LOG_ERROR,
3091 "encrypt_client: Unable to encrypt connection from %s!",
3092 con->http.hostname);
3093 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s",
3094 gnutls_strerror(error));
3095
3096 gnutls_deinit(conn->session);
3097 gnutls_certificate_free_credentials(*credentials);
3098 free(conn);
3099 free(credentials);
3100 return (0);
3101 }
3102
3103 cupsdLogMessage(CUPSD_LOG_DEBUG,
3104 "encrypt_client: %d Connection from %s now encrypted.",
3105 con->http.fd, con->http.hostname);
3106
3107 conn->credentials = credentials;
3108 con->http.tls = conn;
3109 return (1);
3110
80ca4592 3111# elif defined(HAVE_CDSASSL)
89d46774 3112 OSStatus error; /* Error code */
3113 http_tls_t *conn; /* CDSA connection information */
e1d6a774 3114
3115
89d46774 3116 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
3117 return (0);
e1d6a774 3118
89d46774 3119 error = 0;
3120 conn->session = NULL;
b86bc4cf 3121 conn->certsArray = get_cdsa_certificate(con);
e1d6a774 3122
8ca02f3c 3123 if (!conn->certsArray)
3124 {
3125 /*
3126 * No keychain (yet), make a self-signed certificate...
3127 */
3128
b86bc4cf 3129 if (make_certificate(con))
3130 conn->certsArray = get_cdsa_certificate(con);
8ca02f3c 3131 }
3132
89d46774 3133 if (!conn->certsArray)
e1d6a774 3134 {
3135 cupsdLogMessage(CUPSD_LOG_ERROR,
411affcf 3136 "encrypt_client: Could not find signing key in keychain "
e1d6a774 3137 "\"%s\"", ServerCertificate);
3138 error = errSSLBadCert; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3139 }
3140
3141 if (!error)
89d46774 3142 error = SSLNewContext(true, &conn->session);
e1d6a774 3143
3144 if (!error)
89d46774 3145 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
3146
3147 if (!error)
ed486911 3148 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
e1d6a774 3149
3150 if (!error)
411affcf 3151 error = SSLSetConnection(conn->session, HTTP(con));
e1d6a774 3152
3153 if (!error)
89d46774 3154 error = SSLSetAllowsExpiredCerts(conn->session, true);
e1d6a774 3155
3156 if (!error)
89d46774 3157 error = SSLSetAllowsAnyRoot(conn->session, true);
ef416fc2 3158
89d46774 3159 if (!error)
3160 error = SSLSetCertificate(conn->session, conn->certsArray);
ef416fc2 3161
e1d6a774 3162 if (!error)
3163 {
3164 /*
3165 * Perform SSL/TLS handshake
3166 */
ef416fc2 3167
89d46774 3168 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
e1d6a774 3169 usleep(1000);
3170 }
ef416fc2 3171
e1d6a774 3172 if (error)
3173 {
3174 cupsdLogMessage(CUPSD_LOG_ERROR,
3175 "encrypt_client: Unable to encrypt connection from %s!",
3176 con->http.hostname);
ef416fc2 3177
ed486911 3178 cupsdLogMessage(CUPSD_LOG_ERROR, "encrypt_client: %s (%d)",
3179 cssmErrorString(error), (int)error);
ef416fc2 3180
e1d6a774 3181 con->http.error = error;
3182 con->http.status = HTTP_ERROR;
ef416fc2 3183
89d46774 3184 if (conn->session)
3185 SSLDisposeContext(conn->session);
3186
3187 if (conn->certsArray)
3188 CFRelease(conn->certsArray);
3189
3190 free(conn);
ef416fc2 3191
e1d6a774 3192 return (0);
ef416fc2 3193 }
3194
e1d6a774 3195 cupsdLogMessage(CUPSD_LOG_DEBUG,
3196 "encrypt_client: %d Connection from %s now encrypted.",
3197 con->http.fd, con->http.hostname);
ef416fc2 3198
e1d6a774 3199 con->http.tls = conn;
3200 return (1);
3201
80ca4592 3202# endif /* HAVE_LIBSSL */
ef416fc2 3203}
80ca4592 3204#endif /* HAVE_SSL */
ef416fc2 3205
3206
3207#ifdef HAVE_CDSASSL
3208/*
b86bc4cf 3209 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
ef416fc2 3210 */
3211
b86bc4cf 3212static CFArrayRef /* O - Array of certificates */
3213get_cdsa_certificate(cupsd_client_t *con) /* I - Client connection */
ef416fc2 3214{
3215 OSStatus err; /* Error info */
b86bc4cf 3216 SecKeychainRef keychain; /* Keychain reference */
3217 SecIdentitySearchRef search; /* Search reference */
ef416fc2 3218 SecIdentityRef identity; /* Identity */
b86bc4cf 3219 CFArrayRef certificates = NULL;
3220 /* Certificate array */
ef416fc2 3221
3222
b86bc4cf 3223 if ((err = SecKeychainOpen(ServerCertificate, &keychain)))
3224 {
3225 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot open keychain \"%s\", %s",
3226 ServerCertificate, cssmErrorString(err));
3227 return (NULL);
3228 }
ef416fc2 3229
b86bc4cf 3230# if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3231 /*
3232 * Use a policy to search for valid certificates who's common name matches the
3233 * servername...
3234 */
3235
3236 SecPolicySearchRef policy_search; /* Policy search ref */
3237 SecPolicyRef policy; /* Policy ref */
3238 CSSM_DATA options; /* Policy options */
3239 CSSM_APPLE_TP_SSL_OPTIONS
3240 ssl_options; /* SSL Option for hostname */
3241
3242
3243 if ((err = SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_SSL,
3244 NULL, &policy_search)))
ef416fc2 3245 {
b86bc4cf 3246 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create a policy search reference");
3247 CFRelease(keychain);
3248 return (NULL);
3249 }
ef416fc2 3250
b86bc4cf 3251 if ((err = SecPolicySearchCopyNext(policy_search, &policy)))
3252 {
3253 cupsdLogMessage(CUPSD_LOG_ERROR,
3254 "Cannot find a policy to use for searching");
3255 CFRelease(keychain);
3256 CFRelease(policy_search);
3257 return (NULL);
3258 }
ef416fc2 3259
b86bc4cf 3260 memset(&ssl_options, 0, sizeof(ssl_options));
3261 ssl_options.Version = CSSM_APPLE_TP_SSL_OPTS_VERSION;
3262 ssl_options.ServerName = con->servername;
3263 ssl_options.ServerNameLen = strlen(con->servername);
ef416fc2 3264
b86bc4cf 3265 options.Data = (uint8 *)&ssl_options;
3266 options.Length = sizeof(ssl_options);
3267
3268 if ((err = SecPolicySetValue(policy, &options)))
3269 {
3270 cupsdLogMessage(CUPSD_LOG_ERROR,
3271 "Cannot set policy value to use for searching");
3272 CFRelease(keychain);
3273 CFRelease(policy_search);
3274 return (NULL);
3275 }
3276
3277 err = SecIdentitySearchCreateWithPolicy(policy, NULL, CSSM_KEYUSE_SIGN,
3278 keychain, FALSE, &search);
3279# else
3280 /*
3281 * Assume there is exactly one SecIdentity in the keychain...
3282 */
3283
3284 err = SecIdentitySearchCreate(keychain, CSSM_KEYUSE_SIGN, &search);
3285# endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3286
3287 if (err)
3288 cupsdLogMessage(CUPSD_LOG_DEBUG,
3289 "Cannot create keychain search reference: %s",
3290 cssmErrorString(err));
3291 else
3292 {
3293 if ((err = SecIdentitySearchCopyNext(search, &identity)))
3294 {
3295 cupsdLogMessage(CUPSD_LOG_DEBUG,
ef416fc2 3296 "Cannot find signing key in keychain \"%s\", error %d",
3297 ServerCertificate, (int)err);
b86bc4cf 3298 }
3299 else
3300 {
3301 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3302 cupsdLogMessage(CUPSD_LOG_ERROR,
3303 "SecIdentitySearchCopyNext CFTypeID failure!");
ef416fc2 3304 else
3305 {
b86bc4cf 3306 if ((certificates = CFArrayCreate(NULL, (const void **)&identity,
3307 1, &kCFTypeArrayCallBacks)) == NULL)
3308 cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot create certificate array");
ef416fc2 3309 }
3310
b86bc4cf 3311 CFRelease(identity);
ef416fc2 3312 }
3313
b86bc4cf 3314 CFRelease(search);
ef416fc2 3315 }
3316
b86bc4cf 3317# if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3318 CFRelease(policy);
3319 CFRelease(policy_search);
3320# endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3321
3322 return (certificates);
ef416fc2 3323}
3324#endif /* HAVE_CDSASSL */
3325
3326
3327/*
3328 * 'get_file()' - Get a filename and state info.
3329 */
3330
3331static char * /* O - Real filename */
3332get_file(cupsd_client_t *con, /* I - Client connection */
3333 struct stat *filestats, /* O - File information */
3334 char *filename, /* IO - Filename buffer */
3335 int len) /* I - Buffer length */
3336{
3337 int status; /* Status of filesystem calls */
3338 char *ptr; /* Pointer info filename */
3339 int plen; /* Remaining length after pointer */
db1f069b 3340 char language[7]; /* Language subdirectory, if any */
ef416fc2 3341
3342
3343 /*
f7deaa1a 3344 * Figure out the real filename...
ef416fc2 3345 */
3346
db1f069b
MS
3347 language[0] = '\0';
3348
ef416fc2 3349 if (!strncmp(con->uri, "/ppd/", 5))
3350 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
f7deaa1a 3351 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
3352 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
ef416fc2 3353 else if (!strncmp(con->uri, "/admin/conf/", 12))
3354 snprintf(filename, len, "%s%s", ServerRoot, con->uri + 11);
3355 else if (!strncmp(con->uri, "/admin/log/", 11))
3356 {
2e4ff8af 3357 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
ef416fc2 3358 strlcpy(filename, AccessLog, len);
2e4ff8af 3359 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
ef416fc2 3360 strlcpy(filename, ErrorLog, len);
2e4ff8af 3361 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
ef416fc2 3362 strlcpy(filename, PageLog, len);
3363 else
3364 return (NULL);
3365 }
d6ae789d 3366 else if (con->language)
db1f069b
MS
3367 {
3368 snprintf(language, sizeof(language), "/%s", con->language->language);
3369 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3370 }
ef416fc2 3371 else
3372 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3373
3374 if ((ptr = strchr(filename, '?')) != NULL)
3375 *ptr = '\0';
3376
3377 /*
3378 * Grab the status for this language; if there isn't a language-specific file
3379 * then fallback to the default one...
3380 */
3381
db1f069b 3382 if ((status = stat(filename, filestats)) != 0 && language[0] &&
d6ae789d 3383 strncmp(con->uri, "/ppd/", 5) &&
3384 strncmp(con->uri, "/admin/conf/", 12) &&
3385 strncmp(con->uri, "/admin/log/", 11))
ef416fc2 3386 {
3387 /*
d6ae789d 3388 * Drop the country code...
ef416fc2 3389 */
3390
db1f069b
MS
3391 language[3] = '\0';
3392 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
d6ae789d 3393
3394 if ((ptr = strchr(filename, '?')) != NULL)
3395 *ptr = '\0';
3396
3397 if ((status = stat(filename, filestats)) != 0)
ef416fc2 3398 {
d6ae789d 3399 /*
3400 * Drop the language prefix and try the root directory...
3401 */
3402
db1f069b 3403 language[0] = '\0';
ef416fc2 3404 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3405
3406 if ((ptr = strchr(filename, '?')) != NULL)
3407 *ptr = '\0';
3408
3409 status = stat(filename, filestats);
3410 }
3411 }
3412
3413 /*
3414 * If we're found a directory, get the index.html file instead...
3415 */
3416
3417 if (!status && S_ISDIR(filestats->st_mode))
3418 {
db1f069b
MS
3419 /*
3420 * Make sure the URI ends with a slash...
3421 */
ef416fc2 3422
db1f069b
MS
3423 if (con->uri[strlen(con->uri) - 1] != '/')
3424 strlcat(con->uri, "/", sizeof(con->uri));
ef416fc2 3425
db1f069b
MS
3426 /*
3427 * Find the directory index file, trying every language...
3428 */
ef416fc2 3429
db1f069b 3430 do
ef416fc2 3431 {
db1f069b
MS
3432 if (status && language[0])
3433 {
3434 /*
3435 * Try a different language subset...
3436 */
3437
3438 if (language[3])
3439 language[0] = '\0'; /* Strip country code */
3440 else
3441 language[0] = '\0'; /* Strip language */
3442 }
3443
3444 /*
3445 * Look for the index file...
3446 */
3447
3448 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3449
3450 if ((ptr = strchr(filename, '?')) != NULL)
3451 *ptr = '\0';
3452
3453 ptr = filename + strlen(filename);
3454 plen = len - (ptr - filename);
3455
3456 strlcpy(ptr, "index.html", plen);
ef416fc2 3457 status = stat(filename, filestats);
db1f069b
MS
3458
3459#ifdef HAVE_JAVA
3460 if (status)
3461 {
3462 strlcpy(ptr, "index.class", plen);
3463 status = stat(filename, filestats);
3464 }
ef416fc2 3465#endif /* HAVE_JAVA */
3466
3467#ifdef HAVE_PERL
db1f069b
MS
3468 if (status)
3469 {
3470 strlcpy(ptr, "index.pl", plen);
3471 status = stat(filename, filestats);
3472 }
ef416fc2 3473#endif /* HAVE_PERL */
3474
3475#ifdef HAVE_PHP
db1f069b
MS
3476 if (status)
3477 {
3478 strlcpy(ptr, "index.php", plen);
3479 status = stat(filename, filestats);
3480 }
ef416fc2 3481#endif /* HAVE_PHP */
3482
3483#ifdef HAVE_PYTHON
db1f069b
MS
3484 if (status)
3485 {
3486 strlcpy(ptr, "index.pyc", plen);
3487 status = stat(filename, filestats);
3488 }
ef416fc2 3489
db1f069b
MS
3490 if (status)
3491 {
3492 strlcpy(ptr, "index.py", plen);
3493 status = stat(filename, filestats);
3494 }
ef416fc2 3495#endif /* HAVE_PYTHON */
db1f069b
MS
3496
3497 }
3498 while (status && language[0]);
ef416fc2 3499 }
3500
3501 cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_file: %d filename=%s size=%d",
3502 con->http.fd, filename,
3503 status ? -1 : (int)filestats->st_size);
3504
3505 if (!status)
3506 con->http.data_remaining = (int)filestats->st_size;
3507
3508 if (status)
3509 return (NULL);
3510 else
3511 return (filename);
3512}
3513
3514
3515/*
3516 * 'install_conf_file()' - Install a configuration file.
3517 */
3518
3519static http_status_t /* O - Status */
3520install_conf_file(cupsd_client_t *con) /* I - Connection */
3521{
3522 cups_file_t *in, /* Input file */
3523 *out; /* Output file */
3524 char buffer[1024]; /* Copy buffer */
3525 int bytes; /* Number of bytes */
3526 char conffile[1024], /* Configuration filename */
3527 newfile[1024], /* New config filename */
3528 oldfile[1024]; /* Old config filename */
3529 struct stat confinfo; /* Config file info */
3530
3531
3532 /*
3533 * First construct the filenames...
3534 */
3535
3536 snprintf(conffile, sizeof(conffile), "%s%s", ServerRoot, con->uri + 11);
3537 snprintf(newfile, sizeof(newfile), "%s%s.N", ServerRoot, con->uri + 11);
3538 snprintf(oldfile, sizeof(oldfile), "%s%s.O", ServerRoot, con->uri + 11);
3539
3540 cupsdLogMessage(CUPSD_LOG_INFO, "Installing config file \"%s\"...", conffile);
3541
3542 /*
3543 * Get the owner, group, and permissions of the configuration file.
3544 * If it doesn't exist, assign it to the User and Group in the
3545 * cupsd.conf file with mode 0640 permissions.
3546 */
3547
3548 if (stat(conffile, &confinfo))
3549 {
3550 confinfo.st_uid = User;
3551 confinfo.st_gid = Group;
3552 confinfo.st_mode = ConfigFilePerm;
3553 }
3554
3555 /*
3556 * Open the request file and new config file...
3557 */
3558
3559 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3560 {
3561 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open request file \"%s\" - %s",
3562 con->filename, strerror(errno));
3563 return (HTTP_SERVER_ERROR);
3564 }
3565
3566 if ((out = cupsFileOpen(newfile, "wb")) == NULL)
3567 {
3568 cupsFileClose(in);
3569 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open config file \"%s\" - %s",
3570 newfile, strerror(errno));
3571 return (HTTP_SERVER_ERROR);
3572 }
3573
3574 fchmod(cupsFileNumber(out), confinfo.st_mode);
3575 fchown(cupsFileNumber(out), confinfo.st_uid, confinfo.st_gid);
3576
3577 /*
3578 * Copy from the request to the new config file...
3579 */
3580
3581 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3582 if (cupsFileWrite(out, buffer, bytes) < bytes)
3583 {
3584 cupsdLogMessage(CUPSD_LOG_ERROR,
3585 "Unable to copy to config file \"%s\" - %s",
3586 newfile, strerror(errno));
3587
3588 cupsFileClose(in);
3589 cupsFileClose(out);
3590 unlink(newfile);
3591
3592 return (HTTP_SERVER_ERROR);
3593 }
3594
3595 /*
3596 * Close the files...
3597 */
3598
3599 cupsFileClose(in);
3600 if (cupsFileClose(out))
3601 {
3602 cupsdLogMessage(CUPSD_LOG_ERROR,
3603 "Error file closing config file \"%s\" - %s",
3604 newfile, strerror(errno));
3605
3606 unlink(newfile);
3607
3608 return (HTTP_SERVER_ERROR);
3609 }
3610
3611 /*
3612 * Remove the request file...
3613 */
3614
3615 unlink(con->filename);
3616 cupsdClearString(&con->filename);
3617
3618 /*
3619 * Unlink the old backup, rename the current config file to the backup
3620 * filename, and rename the new config file to the config file name...
3621 */
3622
3623 if (unlink(oldfile))
3624 if (errno != ENOENT)
3625 {
3626 cupsdLogMessage(CUPSD_LOG_ERROR,
3627 "Unable to remove backup config file \"%s\" - %s",
3628 oldfile, strerror(errno));
3629
3630 unlink(newfile);
3631
3632 return (HTTP_SERVER_ERROR);
3633 }
3634
3635 if (rename(conffile, oldfile))
3636 if (errno != ENOENT)
3637 {
3638 cupsdLogMessage(CUPSD_LOG_ERROR,
3639 "Unable to rename old config file \"%s\" - %s",
3640 conffile, strerror(errno));
3641
3642 unlink(newfile);
3643
3644 return (HTTP_SERVER_ERROR);
3645 }
3646
3647 if (rename(newfile, conffile))
3648 {
3649 cupsdLogMessage(CUPSD_LOG_ERROR,
3650 "Unable to rename new config file \"%s\" - %s",
3651 newfile, strerror(errno));
3652
3653 rename(oldfile, conffile);
3654 unlink(newfile);
3655
3656 return (HTTP_SERVER_ERROR);
3657 }
3658
3659 /*
3660 * If the cupsd.conf file was updated, set the NeedReload flag...
3661 */
3662
3663 if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
3664 NeedReload = RELOAD_CUPSD;
3665 else
3666 NeedReload = RELOAD_ALL;
3667
3668 ReloadTime = time(NULL);
3669
3670 /*
3671 * Return that the file was created successfully...
3672 */
3673
3674 return (HTTP_CREATED);
3675}
3676
3677
e1d6a774 3678/*
3679 * 'is_cgi()' - Is the resource a CGI script/program?
3680 */
3681
3682static int /* O - 1 = CGI, 0 = file */
3683is_cgi(cupsd_client_t *con, /* I - Client connection */
3684 const char *filename, /* I - Real filename */
3685 struct stat *filestats, /* I - File information */
3686 mime_type_t *type) /* I - MIME type */
3687{
3688 const char *options; /* Options on URL */
3689
3690
3691 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3692 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3693 con, filename, filestats, type ? type->super : "unknown",
3694 type ? type->type : "unknown");
3695
3696 /*
3697 * Get the options, if any...
3698 */
3699
3700 if ((options = strchr(con->uri, '?')) != NULL)
a0f6818e
MS
3701 {
3702 options ++;
3703 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3704 }
b86bc4cf 3705
e1d6a774 3706 /*
3707 * Check for known types...
3708 */
3709
3710 if (!type || strcasecmp(type->super, "application"))
3711 {
3712 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3713 return (0);
3714 }
3715
3716 if (!strcasecmp(type->type, "x-httpd-cgi") &&
3717 (filestats->st_mode & 0111))
3718 {
3719 /*
3720 * "application/x-httpd-cgi" is a CGI script.
3721 */
3722
3723 cupsdSetString(&con->command, filename);
3724
3725 filename = strrchr(filename, '/') + 1; /* Filename always absolute */
3726
a0f6818e
MS
3727 if (options)
3728 cupsdSetStringf(&con->options, " %s", options);
e1d6a774 3729
3730 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3731 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3732 con->command, con->options);
3733
3734 return (1);
3735 }
3736#ifdef HAVE_JAVA
3737 else if (!strcasecmp(type->type, "x-httpd-java"))
3738 {
3739 /*
3740 * "application/x-httpd-java" is a Java servlet.
3741 */
3742
3743 cupsdSetString(&con->command, CUPS_JAVA);
3744
3745 if (options)
b94498cf 3746 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3747 else
b94498cf 3748 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3749
3750 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3751 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3752 con->command, con->options);
3753
3754 return (1);
3755 }
3756#endif /* HAVE_JAVA */
3757#ifdef HAVE_PERL
3758 else if (!strcasecmp(type->type, "x-httpd-perl"))
3759 {
3760 /*
3761 * "application/x-httpd-perl" is a Perl page.
3762 */
3763
3764 cupsdSetString(&con->command, CUPS_PERL);
3765
3766 if (options)
b94498cf 3767 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3768 else
b94498cf 3769 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3770
3771 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3772 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3773 con->command, con->options);
3774
3775 return (1);
3776 }
3777#endif /* HAVE_PERL */
3778#ifdef HAVE_PHP
3779 else if (!strcasecmp(type->type, "x-httpd-php"))
3780 {
3781 /*
3782 * "application/x-httpd-php" is a PHP page.
3783 */
3784
3785 cupsdSetString(&con->command, CUPS_PHP);
3786
3787 if (options)
b94498cf 3788 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3789 else
b94498cf 3790 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3791
3792 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3793 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3794 con->command, con->options);
3795
3796 return (1);
3797 }
3798#endif /* HAVE_PHP */
3799#ifdef HAVE_PYTHON
3800 else if (!strcasecmp(type->type, "x-httpd-python"))
3801 {
3802 /*
3803 * "application/x-httpd-python" is a Python page.
3804 */
3805
3806 cupsdSetString(&con->command, CUPS_PYTHON);
3807
3808 if (options)
b94498cf 3809 cupsdSetStringf(&con->options, " %s %s", filename, options);
e1d6a774 3810 else
b94498cf 3811 cupsdSetStringf(&con->options, " %s", filename);
e1d6a774 3812
3813 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3814 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3815 con->command, con->options);
3816
3817 return (1);
3818 }
3819#endif /* HAVE_PYTHON */
3820
3821 cupsdLogMessage(CUPSD_LOG_DEBUG2, "is_cgi: Returning 0...");
3822
3823 return (0);
3824}
3825
3826
ef416fc2 3827/*
3828 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3829 */
3830
3831static int /* O - 0 if relative, 1 if absolute */
3832is_path_absolute(const char *path) /* I - Input path */
3833{
3834 /*
3835 * Check for a leading slash...
3836 */
3837
3838 if (path[0] != '/')
3839 return (0);
3840
3841 /*
3842 * Check for "/.." in the path...
3843 */
3844
3845 while ((path = strstr(path, "/..")) != NULL)
3846 {
3847 if (!path[3] || path[3] == '/')
3848 return (0);
3849
3850 path ++;
3851 }
3852
3853 /*
3854 * If we haven't found any relative paths, return 1 indicating an
3855 * absolute path...
3856 */
3857
3858 return (1);
3859}
3860
3861
8ca02f3c 3862#ifdef HAVE_SSL
4744bd90 3863/*
3864 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3865 */
3866
8ca02f3c 3867static int /* O - 1 on success, 0 on failure */
b86bc4cf 3868make_certificate(cupsd_client_t *con) /* I - Client connection */
4744bd90 3869{
8ca02f3c 3870#if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
d09495fa 3871 int pid, /* Process ID of command */
3872 status; /* Status of command */
3873 char command[1024], /* Command */
f7deaa1a 3874 *argv[12], /* Command-line arguments */
d09495fa 3875 *envp[MAX_ENV + 1], /* Environment variables */
3876 home[1024], /* HOME environment variable */
3877 infofile[1024], /* Type-in information for cert */
3878 seedfile[1024]; /* Random number seed file */
3879 int envc, /* Number of environment variables */
3880 bytes; /* Bytes written */
3881 cups_file_t *fp; /* Seed/info file */
3882 int infofd; /* Info file descriptor */
8ca02f3c 3883
3884
3885 /*
d09495fa 3886 * Run the "openssl" command to seed the random number generator and
3887 * generate a self-signed certificate that is good for 10 years:
3888 *
3889 * openssl rand -rand seedfile 1
8ca02f3c 3890 *
3891 * openssl req -new -x509 -keyout ServerKey \
3892 * -out ServerCertificate -days 3650 -nodes
d09495fa 3893 *
3894 * The seeding step is crucial in ensuring that the openssl command
3895 * does not block on systems without sufficient entropy...
8ca02f3c 3896 */
3897
3898 if (!cupsFileFind("openssl", getenv("PATH"), 1, command, sizeof(command)))
3899 {
3900 cupsdLogMessage(CUPSD_LOG_ERROR,
3901 "No SSL certificate and openssl command not found!");
3902 return (0);
3903 }
3904
d09495fa 3905 if (access("/dev/urandom", 0))
3906 {
3907 /*
3908 * If the system doesn't provide /dev/urandom, then any random source
3909 * will probably be blocking-style, so generate some random data to
3910 * use as a seed for the certificate. Note that we have already
3911 * seeded the random number generator in cupsdInitCerts()...
3912 */
3913
3914 cupsdLogMessage(CUPSD_LOG_INFO,
3915 "Seeding the random number generator...");
3916
3917 snprintf(home, sizeof(home), "HOME=%s", TempDir);
3918
3919 /*
3920 * Write the seed file...
3921 */
3922
3923 if ((fp = cupsTempFile2(seedfile, sizeof(seedfile))) == NULL)
3924 {
3925 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create seed file %s - %s",
3926 seedfile, strerror(errno));
3927 return (0);
3928 }
3929
3930 for (bytes = 0; bytes < 262144; bytes ++)
3931 cupsFilePutChar(fp, random());
3932
3933 cupsFileClose(fp);
3934
3935 /*
3936 * Run the openssl command to seed its random number generator...
3937 */
3938
3939 argv[0] = "openssl";
3940 argv[1] = "rand";
3941 argv[2] = "-rand";
3942 argv[3] = seedfile;
3943 argv[4] = "1";
3944 argv[5] = NULL;
3945
3946 envc = cupsdLoadEnv(envp, MAX_ENV);
3947 envp[envc++] = home;
3948 envp[envc] = NULL;
3949
a4924f6c
MS
3950 if (!cupsdStartProcess(command, argv, envp, -1, -1, -1, -1, -1, 1, NULL,
3951 &pid))
d09495fa 3952 {
3953 unlink(seedfile);
3954 return (0);
3955 }
3956
3957 while (waitpid(pid, &status, 0) < 0)
3958 if (errno != EINTR)
3959 {
3960 status = 1;
3961 break;
3962 }
3963
3964 cupsdFinishProcess(pid, command, sizeof(command));
3965
3966 /*
3967 * Remove the seed file, as it is no longer needed...
3968 */
3969
3970 unlink(seedfile);
3971
3972 if (status)
3973 {
3974 if (WIFEXITED(status))
3975 cupsdLogMessage(CUPSD_LOG_ERROR,
3976 "Unable to seed random number generator - "
3977 "the openssl command stopped with status %d!",
3978 WEXITSTATUS(status));
3979 else
3980 cupsdLogMessage(CUPSD_LOG_ERROR,
3981 "Unable to seed random number generator - "
3982 "the openssl command crashed on signal %d!",
3983 WTERMSIG(status));
3984
3985 return (0);
3986 }
3987 }
3988
3989 /*
3990 * Create a file with the certificate information fields...
3991 *
3992 * Note: This assumes that the default questions are asked by the openssl
3993 * command...
3994 */
3995
3996 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
3997 {
3998 cupsdLogMessage(CUPSD_LOG_ERROR,
3999 "Unable to create certificate information file %s - %s",
4000 infofile, strerror(errno));
4001 return (0);
4002 }
4003
4004 cupsFilePrintf(fp, ".\n.\n.\n%s\n.\n%s\n%s\n",
4005 ServerName, ServerName, ServerAdmin);
4006 cupsFileClose(fp);
4007
8ca02f3c 4008 cupsdLogMessage(CUPSD_LOG_INFO,
4009 "Generating SSL server key and certificate...");
4010
4011 argv[0] = "openssl";
4012 argv[1] = "req";
4013 argv[2] = "-new";
4014 argv[3] = "-x509";
4015 argv[4] = "-keyout";
4016 argv[5] = ServerKey;
4017 argv[6] = "-out";
4018 argv[7] = ServerCertificate;
4019 argv[8] = "-days";
4020 argv[9] = "3650";
4021 argv[10] = "-nodes";
4022 argv[11] = NULL;
4023
4024 cupsdLoadEnv(envp, MAX_ENV);
4025
d09495fa 4026 infofd = open(infofile, O_RDONLY);
4027
a4924f6c
MS
4028 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4029 &pid))
d09495fa 4030 {
4031 close(infofd);
4032 unlink(infofile);
8ca02f3c 4033 return (0);
d09495fa 4034 }
4035
4036 close(infofd);
4037 unlink(infofile);
8ca02f3c 4038
4039 while (waitpid(pid, &status, 0) < 0)
4040 if (errno != EINTR)
4041 {
4042 status = 1;
4043 break;
4044 }
4045
4046 cupsdFinishProcess(pid, command, sizeof(command));
4047
4048 if (status)
4049 {
4050 if (WIFEXITED(status))
4051 cupsdLogMessage(CUPSD_LOG_ERROR,
4052 "Unable to create SSL server key and certificate - "
4053 "the openssl command stopped with status %d!",
4054 WEXITSTATUS(status));
4055 else
4056 cupsdLogMessage(CUPSD_LOG_ERROR,
4057 "Unable to create SSL server key and certificate - "
4058 "the openssl command crashed on signal %d!",
4059 WTERMSIG(status));
4060 }
4061 else
4062 {
4063 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4064 ServerKey);
4065 cupsdLogMessage(CUPSD_LOG_INFO,
4066 "Created SSL server certificate file \"%s\"...",
4067 ServerCertificate);
4068 }
4069
4070 return (!status);
4071
4072#elif defined(HAVE_GNUTLS)
4744bd90 4073 gnutls_x509_crt crt; /* Self-signed certificate */
4074 gnutls_x509_privkey key; /* Encryption key */
4075 cups_lang_t *language; /* Default language info */
4076 cups_file_t *fp; /* Key/cert file */
4077 unsigned char buffer[8192]; /* Buffer for x509 data */
4078 size_t bytes; /* Number of bytes of data */
4079 unsigned char serial[4]; /* Serial number buffer */
4080 time_t curtime; /* Current time */
4081 int result; /* Result of GNU TLS calls */
4082
4083
4084 /*
4085 * Create the encryption key...
4086 */
4087
8ca02f3c 4088 cupsdLogMessage(CUPSD_LOG_INFO, "Generating SSL server key...");
4744bd90 4089
4090 gnutls_x509_privkey_init(&key);
4091 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
4092
4093 /*
4094 * Save it...
4095 */
4096
4097 bytes = sizeof(buffer);
4098
4099 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM,
4100 buffer, &bytes)) < 0)
4101 {
8ca02f3c 4102 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to export SSL server key - %s",
4744bd90 4103 gnutls_strerror(result));
4104 gnutls_x509_privkey_deinit(key);
8ca02f3c 4105 return (0);
4744bd90 4106 }
4107 else if ((fp = cupsFileOpen(ServerKey, "w")) != NULL)
4108 {
4109 cupsFileWrite(fp, (char *)buffer, bytes);
4110 cupsFileClose(fp);
4111
8ca02f3c 4112 cupsdLogMessage(CUPSD_LOG_INFO, "Created SSL server key file \"%s\"...",
4744bd90 4113 ServerKey);
4114 }
4115 else
4116 {
4117 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4118 "Unable to create SSL server key file \"%s\" - %s",
4744bd90 4119 ServerKey, strerror(errno));
4120 gnutls_x509_privkey_deinit(key);
8ca02f3c 4121 return (0);
4744bd90 4122 }
4123
4124 /*
4125 * Create the self-signed certificate...
4126 */
4127
8ca02f3c 4128 cupsdLogMessage(CUPSD_LOG_INFO, "Generating self-signed SSL certificate...");
4744bd90 4129
4130 language = cupsLangDefault();
4131 curtime = time(NULL);
4132 serial[0] = curtime >> 24;
4133 serial[1] = curtime >> 16;
4134 serial[2] = curtime >> 8;
4135 serial[3] = curtime;
4136
4137 gnutls_x509_crt_init(&crt);
4138 if (strlen(language->language) == 5)
4139 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4140 language->language + 3, 2);
4141 else
4142 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
4143 "US", 2);
4144 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
4145 ServerName, strlen(ServerName));
4146 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
4147 ServerName, strlen(ServerName));
4148 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
4149 0, "Unknown", 7);
4150 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
4151 "Unknown", 7);
4152 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
4153 "Unknown", 7);
4154 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
4155 ServerAdmin, strlen(ServerAdmin));
4156 gnutls_x509_crt_set_key(crt, key);
4157 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
4158 gnutls_x509_crt_set_activation_time(crt, curtime);
4159 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
4160 gnutls_x509_crt_set_ca_status(crt, 0);
4161 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME,
4162 ServerName);
4163 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
4164 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
4165 gnutls_x509_crt_set_version(crt, 3);
4166
4167 bytes = sizeof(buffer);
4168 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
4169 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
4170
4171 gnutls_x509_crt_sign(crt, crt, key);
4172
4173 /*
4174 * Save it...
4175 */
4176
4177 bytes = sizeof(buffer);
4178 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM,
4179 buffer, &bytes)) < 0)
4180 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4181 "Unable to export SSL server certificate - %s",
4744bd90 4182 gnutls_strerror(result));
4183 else if ((fp = cupsFileOpen(ServerCertificate, "w")) != NULL)
4184 {
4185 cupsFileWrite(fp, (char *)buffer, bytes);
4186 cupsFileClose(fp);
4187
4188 cupsdLogMessage(CUPSD_LOG_INFO,
8ca02f3c 4189 "Created SSL server certificate file \"%s\"...",
4744bd90 4190 ServerCertificate);
4191 }
4192 else
4193 cupsdLogMessage(CUPSD_LOG_ERROR,
8ca02f3c 4194 "Unable to create SSL server certificate file \"%s\" - %s",
4744bd90 4195 ServerCertificate, strerror(errno));
4196
4197 /*
4198 * Cleanup...
4199 */
4200
4201 gnutls_x509_crt_deinit(crt);
4202 gnutls_x509_privkey_deinit(key);
8ca02f3c 4203
4204 return (1);
4205
4206#elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
b86bc4cf 4207 int pid, /* Process ID of command */
4208 status; /* Status of command */
4209 char command[1024], /* Command */
4210 *argv[4], /* Command-line arguments */
4211 *envp[MAX_ENV + 1], /* Environment variables */
4212 keychain[1024], /* Keychain argument */
4213 infofile[1024]; /* Type-in information for cert */
4214 cups_file_t *fp; /* Seed/info file */
4215 int infofd; /* Info file descriptor */
8ca02f3c 4216
4217
4218 /*
b86bc4cf 4219 * Run the "certtool" command to generate a self-signed certificate...
8ca02f3c 4220 */
4221
4222 if (!cupsFileFind("certtool", getenv("PATH"), 1, command, sizeof(command)))
4223 {
4224 cupsdLogMessage(CUPSD_LOG_ERROR,
4225 "No SSL certificate and certtool command not found!");
4226 return (0);
4227 }
4228
b86bc4cf 4229 /*
4230 * Create a file with the certificate information fields...
4231 *
4232 * Note: This assumes that the default questions are asked by the certtool
4233 * command...
4234 */
4235
4236 if ((fp = cupsTempFile2(infofile, sizeof(infofile))) == NULL)
4237 {
4238 cupsdLogMessage(CUPSD_LOG_ERROR,
4239 "Unable to create certificate information file %s - %s",
4240 infofile, strerror(errno));
4241 return (0);
4242 }
4243
4244 cupsFilePrintf(fp, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4245 con->servername, con->servername, ServerAdmin);
4246 cupsFileClose(fp);
4247
8ca02f3c 4248 cupsdLogMessage(CUPSD_LOG_INFO,
4249 "Generating SSL server key and certificate...");
4250
4251 snprintf(keychain, sizeof(keychain), "k=%s", ServerCertificate);
4252
4253 argv[0] = "certtool";
4254 argv[1] = "c";
b86bc4cf 4255 argv[2] = keychain;
4256 argv[3] = NULL;
8ca02f3c 4257
4258 cupsdLoadEnv(envp, MAX_ENV);
4259
b86bc4cf 4260 infofd = open(infofile, O_RDONLY);
4261
a4924f6c
MS
4262 if (!cupsdStartProcess(command, argv, envp, infofd, -1, -1, -1, -1, 1, NULL,
4263 &pid))
b86bc4cf 4264 {
4265 close(infofd);
4266 unlink(infofile);
8ca02f3c 4267 return (0);
b86bc4cf 4268 }
4269
4270 close(infofd);
4271 unlink(infofile);
8ca02f3c 4272
4273 while (waitpid(pid, &status, 0) < 0)
4274 if (errno != EINTR)
4275 {
4276 status = 1;
4277 break;
4278 }
4279
4280 cupsdFinishProcess(pid, command, sizeof(command));
4281
4282 if (status)
4283 {
4284 if (WIFEXITED(status))
4285 cupsdLogMessage(CUPSD_LOG_ERROR,
4286 "Unable to create SSL server key and certificate - "
4287 "the certtool command stopped with status %d!",
4288 WEXITSTATUS(status));
4289 else
4290 cupsdLogMessage(CUPSD_LOG_ERROR,
4291 "Unable to create SSL server key and certificate - "
4292 "the certtool command crashed on signal %d!",
4293 WTERMSIG(status));
4294 }
4295 else
4296 {
4297 cupsdLogMessage(CUPSD_LOG_INFO,
4298 "Created SSL server certificate file \"%s\"...",
4299 ServerCertificate);
4300 }
4301
4302 return (!status);
4303
4304#else
4305 return (0);
4306#endif /* HAVE_LIBSSL && HAVE_WAITPID */
4744bd90 4307}
8ca02f3c 4308#endif /* HAVE_SSL */
4744bd90 4309
4310
ef416fc2 4311/*
4312 * 'pipe_command()' - Pipe the output of a command to the remote client.
4313 */
4314
4315static int /* O - Process ID */
4316pipe_command(cupsd_client_t *con, /* I - Client connection */
4317 int infile, /* I - Standard input for command */
4318 int *outfile, /* O - Standard output for command */
4319 char *command, /* I - Command to run */
4320 char *options, /* I - Options for command */
4321 int root) /* I - Run as root? */
4322{
4323 int i; /* Looping var */
4324 int pid; /* Process ID */
b423cd4c 4325 char *commptr, /* Command string pointer */
4326 commch; /* Command string character */
ef416fc2 4327 char *uriptr; /* URI string pointer */
4328 int fds[2]; /* Pipe FDs */
4329 int argc; /* Number of arguments */
4330 int envc; /* Number of environment variables */
4331 char argbuf[10240], /* Argument buffer */
4332 *argv[100], /* Argument strings */
b94498cf 4333 *envp[MAX_ENV + 20]; /* Environment variables */
5bd77a73 4334 char auth_type[256], /* CUPSD_AUTH_TYPE environment variable */
b94498cf 4335 content_length[1024], /* CONTENT_LENGTH environment variable */
ef416fc2 4336 content_type[1024], /* CONTENT_TYPE environment variable */
4337 http_cookie[32768], /* HTTP_COOKIE environment variable */
f7deaa1a 4338 http_referer[1024], /* HTTP_REFERER environment variable */
ef416fc2 4339 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
4340 lang[1024], /* LANG environment variable */
b423cd4c 4341 path_info[1024], /* PATH_INFO environment variable */
ef416fc2 4342 remote_addr[1024], /* REMOTE_ADDR environment variable */
4343 remote_host[1024], /* REMOTE_HOST environment variable */
4344 remote_user[1024], /* REMOTE_USER environment variable */
b94498cf 4345 script_filename[1024], /* SCRIPT_FILENAME environment variable */
ef416fc2 4346 script_name[1024], /* SCRIPT_NAME environment variable */
4347 server_name[1024], /* SERVER_NAME environment variable */
4348 server_port[1024]; /* SERVER_PORT environment variable */
7dfedb92 4349 ipp_attribute_t *attr; /* attributes-natural-language attribute */
5bd77a73
MS
4350#ifdef HAVE_GSSAPI
4351 krb5_ccache ccache = NULL; /* Kerberos credentials */
4352 char krb5ccname[1024]; /* KRB5CCNAME environment variable */
4353#endif /* HAVE_GSSAPI */
ef416fc2 4354
4355
4356 /*
4357 * Parse a copy of the options string, which is of the form:
4358 *
b423cd4c 4359 * argument+argument+argument
4360 * ?argument+argument+argument
4361 * param=value&param=value
4362 * ?param=value&param=value
4363 * /name?argument+argument+argument
4364 * /name?param=value&param=value
ef416fc2 4365 *
4366 * If the string contains an "=" character after the initial name,
4367 * then we treat it as a HTTP GET form request and make a copy of
4368 * the remaining string for the environment variable.
4369 *
4370 * The string is always parsed out as command-line arguments, to
4371 * be consistent with Apache...
4372 */
4373
4374 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4375 "pipe_command: command=\"%s\", options=\"%s\"",
f301802f 4376 command, options ? options : "(null)");
ef416fc2 4377
b86bc4cf 4378 argv[0] = command;
ef416fc2 4379
b423cd4c 4380 if (options)
4381 strlcpy(argbuf, options, sizeof(argbuf));
4382 else
4383 argbuf[0] = '\0';
4384
4385 if (argbuf[0] == '/')
ef416fc2 4386 {
4387 /*
b423cd4c 4388 * Found some trailing path information, set PATH_INFO...
ef416fc2 4389 */
4390
b423cd4c 4391 if ((commptr = strchr(argbuf, '?')) == NULL)
4392 commptr = argbuf + strlen(argbuf);
ef416fc2 4393
b423cd4c 4394 commch = *commptr;
4395 *commptr = '\0';
4396 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
4397 *commptr = commch;
4398 }
4399 else
4400 {
4401 commptr = argbuf;
4402 path_info[0] = '\0';
b94498cf 4403
4404 if (*commptr == ' ')
4405 commptr ++;
b423cd4c 4406 }
ef416fc2 4407
b86bc4cf 4408 if (*commptr == '?' && con->operation == HTTP_GET && !con->query_string)
b423cd4c 4409 {
4410 commptr ++;
b86bc4cf 4411 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
b423cd4c 4412 }
ef416fc2 4413
b423cd4c 4414 argc = 1;
ef416fc2 4415
b423cd4c 4416 if (*commptr)
4417 {
4418 argv[argc ++] = commptr;
ef416fc2 4419
b423cd4c 4420 for (; *commptr && argc < 99; commptr ++)
4421 {
ef416fc2 4422 /*
b423cd4c 4423 * Break arguments whenever we see a + or space...
ef416fc2 4424 */
4425
b423cd4c 4426 if (*commptr == ' ' || *commptr == '+')
4427 {
4428 while (*commptr == ' ' || *commptr == '+')
4429 *commptr++ = '\0';
ef416fc2 4430
b423cd4c 4431 /*
4432 * If we don't have a blank string, save it as another argument...
4433 */
ef416fc2 4434
b423cd4c 4435 if (*commptr)
4436 {
4437 argv[argc] = commptr;
4438 argc ++;
4439 }
4440 else
4441 break;
4442 }
4443 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
4444 isxdigit(commptr[2] & 255))
4445 {
4446 /*
4447 * Convert the %xx notation to the individual character.
4448 */
ef416fc2 4449
b423cd4c 4450 if (commptr[1] >= '0' && commptr[1] <= '9')
4451 *commptr = (commptr[1] - '0') << 4;
4452 else
4453 *commptr = (tolower(commptr[1]) - 'a' + 10) << 4;
ef416fc2 4454
b423cd4c 4455 if (commptr[2] >= '0' && commptr[2] <= '9')
4456 *commptr |= commptr[2] - '0';
4457 else
4458 *commptr |= tolower(commptr[2]) - 'a' + 10;
ef416fc2 4459
b423cd4c 4460 _cups_strcpy(commptr + 1, commptr + 3);
ef416fc2 4461
b423cd4c 4462 /*
4463 * Check for a %00 and break if that is the case...
4464 */
ef416fc2 4465
b423cd4c 4466 if (!*commptr)
4467 break;
4468 }
ef416fc2 4469 }
4470 }
4471
4472 argv[argc] = NULL;
4473
ef416fc2 4474 /*
4475 * Setup the environment variables as needed...
4476 */
4477
b94498cf 4478 if (con->username[0])
4479 {
5bd77a73 4480 snprintf(auth_type, sizeof(auth_type), "CUPSD_AUTH_TYPE=%s",
b94498cf 4481 httpGetField(HTTP(con), HTTP_FIELD_AUTHORIZATION));
4482
4483 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
4484 *uriptr = '\0';
4485 }
4486 else
4487 auth_type[0] = '\0';
4488
7dfedb92
MS
4489 if (con->request &&
4490 (attr = ippFindAttribute(con->request, "attributes-natural-language",
4491 IPP_TAG_LANGUAGE)) != NULL)
4492 {
4493 switch (strlen(attr->values[0].string.text))
4494 {
4495 default :
4496 /*
4497 * This is an unknown or badly formatted language code; use
4498 * the POSIX locale...
4499 */
4500
4501 strcpy(lang, "LANG=C");
4502 break;
4503
4504 case 2 :
4505 /*
4506 * Just the language code (ll)...
4507 */
4508
4509 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
4510 attr->values[0].string.text);
4511 break;
4512
4513 case 5 :
4514 /*
4515 * Language and country code (ll-cc)...
4516 */
4517
4518 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
4519 attr->values[0].string.text[0],
4520 attr->values[0].string.text[1],
4521 toupper(attr->values[0].string.text[3] & 255),
4522 toupper(attr->values[0].string.text[4] & 255));
4523 break;
4524 }
4525 }
4526 else if (con->language)
4527 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
ef416fc2 4528 else
4529 strcpy(lang, "LANG=C");
4530
4531 strcpy(remote_addr, "REMOTE_ADDR=");
4532 httpAddrString(con->http.hostaddr, remote_addr + 12,
4533 sizeof(remote_addr) - 12);
4534
4535 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
4536 con->http.hostname);
4537
4538 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
4539 if ((uriptr = strchr(script_name, '?')) != NULL)
4540 *uriptr = '\0';
4541
b94498cf 4542 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
4543 DocumentRoot, script_name + 12);
4544
ef416fc2 4545 sprintf(server_port, "SERVER_PORT=%d", con->serverport);
4546
4547 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
4548 con->servername);
4549
4550 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
4551
b94498cf 4552 if (auth_type[0])
4553 envp[envc ++] = auth_type;
4554
ef416fc2 4555 envp[envc ++] = lang;
4556 envp[envc ++] = "REDIRECT_STATUS=1";
b94498cf 4557 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
ef416fc2 4558 envp[envc ++] = server_name;
4559 envp[envc ++] = server_port;
4560 envp[envc ++] = remote_addr;
4561 envp[envc ++] = remote_host;
4562 envp[envc ++] = script_name;
b94498cf 4563 envp[envc ++] = script_filename;
ef416fc2 4564
b423cd4c 4565 if (path_info[0])
4566 envp[envc ++] = path_info;
4567
ef416fc2 4568 if (con->username[0])
4569 {
4570 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
4571
4572 envp[envc ++] = remote_user;
5bd77a73
MS
4573
4574 /*
4575 * Save Kerberos credentials, if any...
4576 */
4577
4578#ifdef HAVE_GSSAPI
4579 if (con->gss_have_creds)
4580 {
4581# if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4582 cupsdLogMessage(CUPSD_LOG_INFO,
4583 "Sorry, your version of Kerberos does not support "
4584 "delegated credentials!");
4585
4586# else
4587 krb5_error_code error; /* Kerberos error code */
4588 OM_uint32 major_status, /* Major status code */
4589 minor_status; /* Minor status code */
4590 krb5_principal principal; /* Kerberos principal */
4591
4592
4593# ifdef __APPLE__
4594 /*
4595 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4596 * to use it...
4597 */
4598
4599 if (krb5_init_context != NULL)
4600 {
4601# endif /* __APPLE__ */
4602
4603 /*
4604 * We MUST create a file-based cache because memory-based caches are
4605 * only valid for the current process/address space.
4606 *
4607 * Due to various bugs/features in different versions of Kerberos, we
4608 * need either the krb5_cc_new_unique() function or Heimdal's version
4609 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4610 * can be passed to the backend. These functions create a temporary
4611 * file (typically in /tmp) containing the cached credentials, which
4612 * are removed when we have successfully printed a job.
4613 */
4614
4615# ifdef HAVE_KRB5_CC_NEW_UNIQUE
4616 if ((error = krb5_cc_new_unique(KerberosContext, "FILE", NULL,
4617 &ccache)) != 0)
4618# else /* HAVE_HEIMDAL */
4619 if ((error = krb5_cc_gen_new(KerberosContext, &krb5_fcc_ops,
4620 &ccache)) != 0)
4621# endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4622 {
4623 cupsdLogMessage(CUPSD_LOG_ERROR,
4624 "Unable to create new credentials cache (%d/%s)",
4625 error, strerror(errno));
4626 ccache = NULL;
4627 }
4628 else if ((error = krb5_parse_name(KerberosContext, con->username,
4629 &principal)) != 0)
4630 {
4631 cupsdLogMessage(CUPSD_LOG_ERROR,
4632 "Unable to parse kerberos username (%d/%s)", error,
4633 strerror(errno));
4634 krb5_cc_destroy(KerberosContext, ccache);
4635 ccache = NULL;
4636 }
4637 else if ((error = krb5_cc_initialize(KerberosContext, ccache,
4638 principal)))
4639 {
4640 cupsdLogMessage(CUPSD_LOG_ERROR,
4641 "Unable to initialize credentials cache (%d/%s)", error,
4642 strerror(errno));
4643 krb5_cc_destroy(KerberosContext, ccache);
4644 krb5_free_principal(KerberosContext, principal);
4645 ccache = NULL;
4646 }
4647 else
4648 {
4649 krb5_free_principal(KerberosContext, principal);
4650
4651 /*
4652 * Copy the user's credentials to the new cache file...
4653 */
4654
4655 major_status = gss_krb5_copy_ccache(&minor_status,
4656 con->gss_delegated_cred, ccache);
4657
4658 if (GSS_ERROR(major_status))
4659 {
4660 cupsdLogGSSMessage(CUPSD_LOG_ERROR, major_status, minor_status,
4661 "Unable to import client credentials cache");
4662 krb5_cc_destroy(KerberosContext, ccache);
4663 ccache = NULL;
4664 }
4665 else
4666 {
4667 /*
4668 * Add the KRB5CCNAME environment variable to the job so that the
4669 * backend can use the credentials when printing.
4670 */
4671
4672 snprintf(krb5ccname, sizeof(krb5ccname), "KRB5CCNAME=FILE:%s",
4673 krb5_cc_get_name(KerberosContext, ccache));
4674 envp[envc++] = krb5ccname;
4675
4676 if (!RunUser)
4677 chown(krb5_cc_get_name(KerberosContext, ccache), User, Group);
4678 }
4679 }
4680# ifdef __APPLE__
4681 }
4682# endif /* __APPLE__ */
4683# endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4684 }
4685#endif /* HAVE_GSSAPI */
4686
ef416fc2 4687 }
4688
4689 if (con->http.version == HTTP_1_1)
4690 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
4691 else if (con->http.version == HTTP_1_0)
4692 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
4693 else
4694 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
4695
4696 if (con->http.cookie)
4697 {
4698 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
4699 con->http.cookie);
4700 envp[envc ++] = http_cookie;
4701 }
4702
4703 if (con->http.fields[HTTP_FIELD_USER_AGENT][0])
4704 {
4705 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
4706 con->http.fields[HTTP_FIELD_USER_AGENT]);
4707 envp[envc ++] = http_user_agent;
4708 }
4709
f7deaa1a 4710 if (con->http.fields[HTTP_FIELD_REFERER][0])
4711 {
4712 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
4713 con->http.fields[HTTP_FIELD_REFERER]);
4714 envp[envc ++] = http_referer;
4715 }
4716
ef416fc2 4717 if (con->operation == HTTP_GET)
4718 {
ef416fc2 4719 envp[envc ++] = "REQUEST_METHOD=GET";
4720
b86bc4cf 4721 if (con->query_string)
ef416fc2 4722 {
4723 /*
4724 * Add GET form variables after ?...
4725 */
4726
b86bc4cf 4727 envp[envc ++] = con->query_string;
ef416fc2 4728 }
3dfe78b3
MS
4729 else
4730 envp[envc ++] = "QUERY_STRING=";
ef416fc2 4731 }
4732 else
4733 {
e1d6a774 4734 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
4735 CUPS_LLCAST con->bytes);
ef416fc2 4736 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
4737 con->http.fields[HTTP_FIELD_CONTENT_TYPE]);
4738
4739 envp[envc ++] = "REQUEST_METHOD=POST";
4740 envp[envc ++] = content_length;
4741 envp[envc ++] = content_type;
4742 }
4743
4744 /*
4745 * Tell the CGI if we are using encryption...
4746 */
4747
a74454a7 4748 if (con->http.tls)
ef416fc2 4749 envp[envc ++] = "HTTPS=ON";
4750
4751 /*
4752 * Terminate the environment array...
4753 */
4754
4755 envp[envc] = NULL;
4756
4757 if (LogLevel == CUPSD_LOG_DEBUG2)
4758 {
4759 for (i = 0; i < argc; i ++)
4760 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4761 "pipe_command: argv[%d] = \"%s\"", i, argv[i]);
4762 for (i = 0; i < envc; i ++)
4763 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4764 "pipe_command: envp[%d] = \"%s\"", i, envp[i]);
4765 }
4766
4767 /*
4768 * Create a pipe for the output...
4769 */
4770
4771 if (cupsdOpenPipe(fds))
4772 {
ef416fc2 4773 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create pipes for CGI %s - %s",
4774 argv[0], strerror(errno));
4775 return (0);
4776 }
4777
4778 /*
4779 * Then execute the command...
4780 */
4781
4782 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
a4924f6c 4783 -1, -1, root, DefaultProfile, &pid) < 0)
ef416fc2 4784 {
4785 /*
4786 * Error - can't fork!
4787 */
4788
4789 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork for CGI %s - %s", argv[0],
4790 strerror(errno));
4791
4792 cupsdClosePipe(fds);
4793 pid = 0;
4794 }
4795 else
4796 {
4797 /*
4798 * Fork successful - return the PID...
4799 */
4800
4801 if (con->username[0])
5bd77a73
MS
4802#ifdef HAVE_GSSAPI
4803 cupsdAddCert(pid, con->username, ccache);
4804#else
4805 cupsdAddCert(pid, con->username, NULL);
4806#endif /* HAVE_GSSAPI */
ef416fc2 4807
355e94dc
MS
4808 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] %s started - PID = %d",
4809 command, pid);
ef416fc2 4810
4811 *outfile = fds[0];
4812 close(fds[1]);
4813 }
4814
ef416fc2 4815 return (pid);
4816}
4817
4818
4819/*
a74454a7 4820 * 'write_file()' - Send a file via HTTP.
e1d6a774 4821 */
4822
4823static int /* O - 0 on failure, 1 on success */
a74454a7 4824write_file(cupsd_client_t *con, /* I - Client connection */
4825 http_status_t code, /* I - HTTP status */
4826 char *filename, /* I - Filename */
4827 char *type, /* I - File type */
4828 struct stat *filestats) /* O - File information */
e1d6a774 4829{
4830 con->file = open(filename, O_RDONLY);
4831
355e94dc 4832 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_file: %d file=%d", con->http.fd,
e1d6a774 4833 con->file);
4834
4835 if (con->file < 0)
4836 return (0);
4837
4838 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4839
4840 con->pipe_pid = 0;
4841
5bd77a73 4842 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
e1d6a774 4843 return (0);
4844
4845 if (httpPrintf(HTTP(con), "Last-Modified: %s\r\n",
4846 httpGetDateString(filestats->st_mtime)) < 0)
4847 return (0);
4848 if (httpPrintf(HTTP(con), "Content-Length: " CUPS_LLFMT "\r\n",
4849 CUPS_LLCAST filestats->st_size) < 0)
4850 return (0);
4851 if (httpPrintf(HTTP(con), "\r\n") < 0)
4852 return (0);
4853
07725fee 4854 if (cupsdFlushHeader(con) < 0)
4855 return (0);
d09495fa 4856
e1d6a774 4857 con->http.data_encoding = HTTP_ENCODE_LENGTH;
4858 con->http.data_remaining = filestats->st_size;
4859
4860 if (con->http.data_remaining <= INT_MAX)
4861 con->http._data_remaining = con->http.data_remaining;
4862 else
4863 con->http._data_remaining = INT_MAX;
4864
f7deaa1a 4865 cupsdAddSelect(con->http.fd, (cupsd_selfunc_t)cupsdReadClient,
4866 (cupsd_selfunc_t)cupsdWriteClient, con);
e1d6a774 4867
4868 return (1);
4869}
4870
4871
4872/*
f899b121 4873 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4874 */
4875
4876static void
4877write_pipe(cupsd_client_t *con) /* I - Client connection */
4878{
4879 cupsdLogMessage(CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d...",
4880 con->file);
4881
4882 con->file_ready = 1;
4883
4884 cupsdRemoveSelect(con->file);
4885 cupsdAddSelect(con->http.fd, NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4886}
4887
4888
4889/*
2e4ff8af 4890 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".
ef416fc2 4891 */