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