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