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