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