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