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