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