2 * "$Id: client.c,v 1.91.2.21 2002/09/25 12:52:41 mike Exp $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2002 by Easy Software Products, all rights reserved.
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
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * AcceptClient() - Accept a new client.
27 * CloseAllClients() - Close all remote clients immediately.
28 * CloseClient() - Close a remote client.
29 * EncryptClient() - Enable encryption for the client...
30 * ReadClient() - Read data from a client.
31 * SendCommand() - Send output from a command via HTTP.
32 * SendError() - Send an error message via HTTP.
33 * SendFile() - Send a file via HTTP.
34 * SendHeader() - Send an HTTP request.
35 * ShutdownClient() - Shutdown the receiving end of a connection.
36 * WriteClient() - Write data to a client as needed.
37 * check_if_modified() - Decode an "If-Modified-Since" line.
38 * decode_auth() - Decode an authorization string.
39 * get_file() - Get a filename and state info.
40 * install_conf_file() - Install a configuration file.
41 * pipe_command() - Pipe the output of a command to the remote client.
45 * Include necessary headers...
53 # include <openssl/err.h>
54 # include <openssl/ssl.h>
55 # include <openssl/rand.h>
56 #endif /* HAVE_LIBSSL */
63 static int check_if_modified(client_t
*con
,
64 struct stat
*filestats
);
65 static void decode_auth(client_t
*con
);
66 static char *get_file(client_t
*con
, struct stat
*filestats
);
67 static http_status_t
install_conf_file(client_t
*con
);
68 static int pipe_command(client_t
*con
, int infile
, int *outfile
,
69 char *command
, char *options
);
73 * 'AcceptClient()' - Accept a new client.
77 AcceptClient(listener_t
*lis
) /* I - Listener socket */
79 int i
; /* Looping var */
80 int val
; /* Parameter value */
81 client_t
*con
; /* New client pointer */
82 const struct hostent
*host
; /* Host entry for address */
83 char *hostname
;/* Hostname for address */
84 http_addr_t temp
; /* Temporary address variable */
87 LogMessage(L_DEBUG2
, "AcceptClient(%p) %d NumClients = %d",
88 lis
, lis
->fd
, NumClients
);
91 * Make sure we don't have a full set of clients already...
94 if (NumClients
== MaxClients
)
98 * Get a pointer to the next available client...
101 con
= Clients
+ NumClients
;
103 memset(con
, 0, sizeof(client_t
));
104 con
->http
.activity
= time(NULL
);
107 * Accept the client and get the remote address...
110 val
= sizeof(struct sockaddr_in
);
112 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
115 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
121 if (lis
->address
.addr
.sa_family
== AF_INET6
)
122 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
124 #endif /* AF_INET6 */
125 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
128 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
129 sizeof(con
->http
.hostname
));
133 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
134 sizeof(con
->http
.hostname
));
137 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
140 * Map accesses from the loopback interface to "localhost"...
143 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
145 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
148 * Map accesses from the same host to the server name.
151 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
154 if (hostname
== NULL
&& HostNameLookups
== 2)
157 * Can't have an unresolved IP address with double-lookups enabled...
160 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
164 closesocket(con
->http
.fd
);
169 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
174 if (HostNameLookups
== 2)
177 * Do double lookups as needed...
180 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
183 * See if the hostname maps to the same IP address...
186 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
189 * Not the right type of address...
197 * Compare all of the addresses against this one...
200 for (i
= 0; host
->h_addr_list
[i
]; i
++)
202 httpAddrLoad(host
, 0, i
, &temp
);
204 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
208 if (!host
->h_addr_list
[i
])
216 * Can't have a hostname that doesn't resolve to the same IP address
217 * with double-lookups enabled...
220 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
224 closesocket(con
->http
.fd
);
229 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
236 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
237 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
238 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
240 #endif /* AF_INET6 */
241 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
242 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
245 * Using TCP_NODELAY improves responsiveness, especially on systems
246 * with a slow loopback interface... Since we write large buffers
247 * when sending print files and requests, there shouldn't be any
248 * performance penalty for this...
252 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
255 * Add the socket to the select() input mask.
258 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
260 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
262 FD_SET(con
->http
.fd
, &InputSet
);
267 * Temporarily suspend accept()'s until we lose a client...
270 if (NumClients
== MaxClients
)
275 * See if we are connecting on a secure port...
278 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
281 * https connection; go secure...
284 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
288 #endif /* HAVE_LIBSSL */
293 * 'CloseAllClients()' - Close all remote clients immediately.
297 CloseAllClients(void)
299 while (NumClients
> 0)
300 CloseClient(Clients
);
305 * 'CloseClient()' - Close a remote client.
309 CloseClient(client_t
*con
) /* I - Client to close */
311 int status
; /* Exit status of pipe command */
313 SSL_CTX
*context
; /* Context for encryption */
314 SSL
*conn
; /* Connection for encryption */
315 unsigned long error
; /* Error code */
316 #endif /* HAVE_LIBSSL */
319 LogMessage(L_DEBUG
, "CloseClient() %d", con
->http
.fd
);
323 * Shutdown encryption as needed...
328 conn
= (SSL
*)(con
->http
.tls
);
329 context
= SSL_get_SSL_CTX(conn
);
331 switch (SSL_shutdown(conn
))
334 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
337 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
339 while ((error
= ERR_get_error()) != 0)
340 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
344 SSL_CTX_free(context
);
347 con
->http
.tls
= NULL
;
349 #endif /* HAVE_LIBSSL */
352 * Close the socket and clear the file from the input set for select()...
355 if (con
->http
.fd
>= 0)
357 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
360 FD_CLR(con
->http
.fd
, &InputSet
);
361 FD_CLR(con
->http
.fd
, &OutputSet
);
365 if (con
->pipe_pid
!= 0)
367 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet...",
369 FD_CLR(con
->file
, &InputSet
);
375 * Close the open data file...
380 kill(con
->pipe_pid
, SIGKILL
);
381 waitpid(con
->pipe_pid
, &status
, WNOHANG
);
384 LogMessage(L_DEBUG2
, "CloseClient() %d Closing data file %d.",
385 con
->http
.fd
, con
->file
);
386 LogMessage(L_DEBUG2
, "CloseClient() %d Removing fd %d from InputSet.",
387 con
->http
.fd
, con
->file
);
389 FD_CLR(con
->file
, &InputSet
);
396 ippDelete(con
->request
);
402 ippDelete(con
->response
);
403 con
->response
= NULL
;
408 cupsLangFree(con
->language
);
409 con
->language
= NULL
;
413 * Re-enable new client connections if we are going back under the
417 if (NumClients
== MaxClients
)
421 * Compact the list of clients as necessary...
426 if (con
< (Clients
+ NumClients
))
427 memcpy(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
432 * 'EncryptClient()' - Enable encryption for the client...
435 int /* O - 1 on success, 0 on error */
436 EncryptClient(client_t
*con
) /* I - Client to encrypt */
439 SSL_CTX
*context
; /* Context for encryption */
440 SSL
*conn
; /* Connection for encryption */
441 unsigned long error
; /* Error code */
445 * Create the SSL context and accept the connection...
448 context
= SSL_CTX_new(SSLv23_method());
449 conn
= SSL_new(context
);
451 SSL_use_PrivateKey_file(conn
, ServerKey
, SSL_FILETYPE_PEM
);
452 SSL_use_certificate_file(conn
, ServerCertificate
, SSL_FILETYPE_PEM
);
454 SSL_set_fd(conn
, con
->http
.fd
);
455 if (SSL_accept(conn
) != 1)
457 while ((error
= ERR_get_error()) != 0)
458 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
460 SSL_CTX_free(context
);
465 con
->http
.tls
= conn
;
469 #endif /* HAVE_LIBSSL */
474 * 'ReadClient()' - Read data from a client.
477 int /* O - 1 on success, 0 on error */
478 ReadClient(client_t
*con
) /* I - Client to read from */
480 char line
[32768], /* Line from client... */
481 operation
[64], /* Operation code from socket */
482 version
[64]; /* HTTP version number string */
483 int major
, minor
; /* HTTP version numbers */
484 http_status_t status
; /* Transfer status */
485 ipp_state_t ipp_state
; /* State of IPP transfer */
486 int bytes
; /* Number of bytes to POST */
487 char *filename
; /* Name of file for GET/HEAD */
488 struct stat filestats
; /* File information */
489 mime_type_t
*type
; /* MIME type of file */
490 printer_t
*p
; /* Printer */
491 location_t
*best
; /* Best match for authentication */
492 static unsigned request_id
= 0;/* Request ID for temp files */
495 status
= HTTP_CONTINUE
;
497 switch (con
->http
.state
)
501 * See if we've received a request line...
504 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
511 * Ignore blank request lines...
518 * Clear other state variables...
521 httpClearFields(HTTP(con
));
523 con
->http
.activity
= time(NULL
);
524 con
->http
.version
= HTTP_1_0
;
525 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
526 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
527 con
->http
.data_remaining
= 0;
528 con
->operation
= HTTP_WAITING
;
532 con
->command
[0] = '\0';
533 con
->username
[0] = '\0';
534 con
->password
[0] = '\0';
537 if (con
->language
!= NULL
)
539 cupsLangFree(con
->language
);
540 con
->language
= NULL
;
544 * Grab the request line...
547 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
550 SendError(con
, HTTP_BAD_REQUEST
);
554 con
->http
.version
= HTTP_0_9
;
557 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
559 SendError(con
, HTTP_BAD_REQUEST
);
566 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
567 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
568 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
570 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
574 SendError(con
, HTTP_NOT_SUPPORTED
);
582 * Process the request...
585 if (strcmp(operation
, "GET") == 0)
586 con
->http
.state
= HTTP_GET
;
587 else if (strcmp(operation
, "PUT") == 0)
588 con
->http
.state
= HTTP_PUT
;
589 else if (strcmp(operation
, "POST") == 0)
590 con
->http
.state
= HTTP_POST
;
591 else if (strcmp(operation
, "DELETE") == 0)
592 con
->http
.state
= HTTP_DELETE
;
593 else if (strcmp(operation
, "TRACE") == 0)
594 con
->http
.state
= HTTP_TRACE
;
595 else if (strcmp(operation
, "OPTIONS") == 0)
596 con
->http
.state
= HTTP_OPTIONS
;
597 else if (strcmp(operation
, "HEAD") == 0)
598 con
->http
.state
= HTTP_HEAD
;
601 SendError(con
, HTTP_BAD_REQUEST
);
606 con
->start
= time(NULL
);
607 con
->operation
= con
->http
.state
;
609 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
611 con
->http
.version
/ 100, con
->http
.version
% 100);
613 con
->http
.status
= HTTP_OK
;
623 * Parse incoming parameters until the status changes...
626 status
= httpUpdate(HTTP(con
));
628 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
630 SendError(con
, HTTP_BAD_REQUEST
);
637 break; /* Anti-compiler-warning-code */
641 * Handle new transfers...
644 if (status
== HTTP_OK
)
646 con
->language
= cupsLangGet(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
650 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
652 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
654 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
655 con
->http
.version
>= HTTP_1_1
)
658 * HTTP/1.1 and higher require the "Host:" field...
661 if (!SendError(con
, HTTP_BAD_REQUEST
))
667 else if (con
->operation
== HTTP_OPTIONS
)
670 * Do OPTIONS command...
673 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
674 best
->type
!= AUTH_NONE
)
676 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
683 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
684 con
->http
.tls
== NULL
)
688 * Do encryption stuff...
691 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
697 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
698 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
699 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
700 httpPrintf(HTTP(con
), "\r\n");
704 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
709 #endif /* HAVE_LIBSSL */
712 if (!SendHeader(con
, HTTP_OK
, NULL
))
718 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
719 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
720 httpPrintf(HTTP(con
), "\r\n");
722 else if (strstr(con
->uri
, "..") != NULL
)
725 * Protect against malicious users!
728 if (!SendError(con
, HTTP_FORBIDDEN
))
734 else if (con
->uri
[0] != '/')
737 * Don't allow proxying (yet)...
740 if (!SendError(con
, HTTP_METHOD_NOT_ALLOWED
))
748 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
749 con
->http
.tls
== NULL
)
753 * Do encryption stuff...
756 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
762 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
763 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
764 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
765 httpPrintf(HTTP(con
), "\r\n");
769 status
= IsAuthorized(con
);
771 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
776 #endif /* HAVE_LIBSSL */
779 if (status
!= HTTP_OK
)
781 SendError(con
, status
);
786 switch (con
->http
.state
)
789 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
790 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
793 * Send PPD file - get the real printer name since printer
794 * names are not case sensitive but filenames can be...
797 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
799 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
800 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
803 if (!SendError(con
, HTTP_NOT_FOUND
))
813 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
814 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
815 strncmp(con
->uri
, "/printers", 9) == 0 ||
816 strncmp(con
->uri
, "/classes", 8) == 0 ||
817 strncmp(con
->uri
, "/jobs", 5) == 0)
823 if (strncmp(con
->uri
, "/admin", 6) == 0)
825 snprintf(con
->command
, sizeof(con
->command
),
826 "%s/cgi-bin/admin.cgi", ServerBin
);
827 con
->options
= con
->uri
+ 6;
829 else if (strncmp(con
->uri
, "/printers", 9) == 0)
831 snprintf(con
->command
, sizeof(con
->command
),
832 "%s/cgi-bin/printers.cgi", ServerBin
);
833 con
->options
= con
->uri
+ 9;
835 else if (strncmp(con
->uri
, "/classes", 8) == 0)
837 snprintf(con
->command
, sizeof(con
->command
),
838 "%s/cgi-bin/classes.cgi", ServerBin
);
839 con
->options
= con
->uri
+ 8;
843 snprintf(con
->command
, sizeof(con
->command
),
844 "%s/cgi-bin/jobs.cgi", ServerBin
);
845 con
->options
= con
->uri
+ 5;
848 if (con
->options
[0] == '/')
851 if (!SendCommand(con
, con
->command
, con
->options
))
853 if (!SendError(con
, HTTP_NOT_FOUND
))
860 LogRequest(con
, HTTP_OK
);
862 if (con
->http
.version
<= HTTP_1_0
)
863 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
865 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
866 (strchr(con
->uri
+ 12, '/') != NULL
||
867 strlen(con
->uri
) == 12))
870 * GET can only be done to configuration files under
874 if (!SendError(con
, HTTP_FORBIDDEN
))
888 if ((filename
= get_file(con
, &filestats
)) == NULL
)
890 if (!SendError(con
, HTTP_NOT_FOUND
))
896 else if (!check_if_modified(con
, &filestats
))
898 if (!SendError(con
, HTTP_NOT_MODIFIED
))
906 type
= mimeFileType(MimeDatabase
, filename
);
908 strcpy(line
, "text/plain");
910 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
912 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
921 case HTTP_POST_RECV
:
923 * See if the POST request includes a Content-Length field, and if
924 * so check the length against any limits that are set...
927 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
928 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
930 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
931 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
935 * Request too large...
938 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
948 * See what kind of POST request this is; for IPP requests the
949 * content-type field will be "application/ipp"...
952 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
953 con
->request
= ippNew();
954 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
955 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
956 strncmp(con
->uri
, "/printers", 9) == 0 ||
957 strncmp(con
->uri
, "/classes", 8) == 0 ||
958 strncmp(con
->uri
, "/jobs", 5) == 0)
964 if (strncmp(con
->uri
, "/admin", 6) == 0)
966 snprintf(con
->command
, sizeof(con
->command
),
967 "%s/cgi-bin/admin.cgi", ServerBin
);
968 con
->options
= con
->uri
+ 6;
970 else if (strncmp(con
->uri
, "/printers", 9) == 0)
972 snprintf(con
->command
, sizeof(con
->command
),
973 "%s/cgi-bin/printers.cgi", ServerBin
);
974 con
->options
= con
->uri
+ 9;
976 else if (strncmp(con
->uri
, "/classes", 8) == 0)
978 snprintf(con
->command
, sizeof(con
->command
),
979 "%s/cgi-bin/classes.cgi", ServerBin
);
980 con
->options
= con
->uri
+ 8;
984 snprintf(con
->command
, sizeof(con
->command
),
985 "%s/cgi-bin/jobs.cgi", ServerBin
);
986 con
->options
= con
->uri
+ 5;
989 if (con
->options
[0] == '/')
992 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
993 con
->http
.fd
, con
->command
, con
->options
);
995 if (con
->http
.version
<= HTTP_1_0
)
996 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
998 else if (!SendError(con
, HTTP_UNAUTHORIZED
))
1005 case HTTP_PUT_RECV
:
1007 * Validate the resource name...
1010 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1011 strchr(con
->uri
+ 12, '/') != NULL
||
1012 strlen(con
->uri
) == 12)
1015 * PUT can only be done to configuration files under
1019 if (!SendError(con
, HTTP_FORBIDDEN
))
1029 * See if the PUT request includes a Content-Length field, and if
1030 * so check the length against any limits that are set...
1033 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1034 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1036 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1037 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1041 * Request too large...
1044 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1054 * Open a temporary file to hold the request...
1057 snprintf(con
->filename
, sizeof(con
->filename
), "%s/%08x",
1058 RequestRoot
, request_id
++);
1059 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1060 fchmod(con
->file
, 0640);
1061 fchown(con
->file
, User
, Group
);
1063 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1064 con
->filename
, con
->file
);
1068 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1078 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1079 ShutdownClient(con
);
1083 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1084 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1087 * Send PPD file - get the real printer name since printer
1088 * names are not case sensitive but filenames can be...
1091 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1093 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1094 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1097 if (!SendError(con
, HTTP_NOT_FOUND
))
1107 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1108 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1109 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1110 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1111 strncmp(con
->uri
, "/jobs/", 6) == 0)
1117 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1123 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1129 LogRequest(con
, HTTP_OK
);
1131 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1132 (strchr(con
->uri
+ 12, '/') != NULL
||
1133 strlen(con
->uri
) == 12))
1136 * HEAD can only be done to configuration files under
1140 if (!SendError(con
, HTTP_FORBIDDEN
))
1148 else if ((filename
= get_file(con
, &filestats
)) == NULL
)
1150 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1156 LogRequest(con
, HTTP_NOT_FOUND
);
1158 else if (!check_if_modified(con
, &filestats
))
1160 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1166 LogRequest(con
, HTTP_NOT_MODIFIED
);
1174 type
= mimeFileType(MimeDatabase
, filename
);
1176 strcpy(line
, "text/plain");
1178 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1180 if (!SendHeader(con
, HTTP_OK
, line
))
1186 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1187 httpGetDateString(filestats
.st_mtime
)) < 0)
1193 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1194 (unsigned long)filestats
.st_size
) < 0)
1200 LogRequest(con
, HTTP_OK
);
1203 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1209 con
->http
.state
= HTTP_WAITING
;
1213 break; /* Anti-compiler-warning-code */
1219 * Handle any incoming data...
1222 switch (con
->http
.state
)
1224 case HTTP_PUT_RECV
:
1225 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1227 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1228 con
->http
.data_remaining
, con
->file
);
1230 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1237 con
->bytes
+= bytes
;
1239 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1240 con
->http
.fd
, bytes
, con
->file
);
1242 if (write(con
->file
, line
, bytes
) < bytes
)
1244 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1245 bytes
, con
->filename
, strerror(errno
));
1247 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1252 unlink(con
->filename
);
1253 con
->filename
[0] = '\0';
1255 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1263 if (con
->http
.state
== HTTP_WAITING
)
1266 * End of file, see how big it is...
1269 fstat(con
->file
, &filestats
);
1271 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1272 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1277 if (filestats
.st_size
> MaxRequestSize
&&
1281 * Request is too big; remove it and send an error...
1284 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1285 con
->http
.fd
, con
->filename
);
1286 unlink(con
->filename
);
1287 con
->filename
[0] = '\0';
1289 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1297 * Install the configuration file...
1300 status
= install_conf_file(con
);
1303 * Return the status to the client...
1306 if (!SendError(con
, status
))
1314 case HTTP_POST_RECV
:
1315 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1317 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1318 con
->http
.data_remaining
, con
->file
);
1320 if (con
->request
!= NULL
)
1323 * Grab any request data from the connection...
1326 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1328 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1333 else if (ipp_state
!= IPP_DATA
)
1336 con
->bytes
+= ippLength(con
->request
);
1339 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
1342 * Create a file as needed for the request data...
1345 snprintf(con
->filename
, sizeof(con
->filename
), "%s/%08x",
1346 RequestRoot
, request_id
++);
1347 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1348 fchmod(con
->file
, 0640);
1349 fchown(con
->file
, User
, Group
);
1351 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1352 con
->filename
, con
->file
);
1356 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1364 if (con
->http
.state
!= HTTP_POST_SEND
)
1366 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1373 con
->bytes
+= bytes
;
1375 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1376 con
->http
.fd
, bytes
, con
->file
);
1378 if (write(con
->file
, line
, bytes
) < bytes
)
1380 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1381 bytes
, con
->filename
, strerror(errno
));
1383 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1388 unlink(con
->filename
);
1389 con
->filename
[0] = '\0';
1391 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1398 else if (con
->http
.state
!= HTTP_POST_SEND
)
1405 if (con
->http
.state
== HTTP_POST_SEND
)
1409 fstat(con
->file
, &filestats
);
1411 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1412 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1417 if (filestats
.st_size
> MaxRequestSize
&&
1421 * Request is too big; remove it and send an error...
1424 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1425 con
->http
.fd
, con
->filename
);
1426 unlink(con
->filename
);
1427 con
->filename
[0] = '\0';
1432 * Delete any IPP request data...
1435 ippDelete(con
->request
);
1436 con
->request
= NULL
;
1439 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1446 if (con
->command
[0])
1448 if (!SendCommand(con
, con
->command
, con
->options
))
1450 if (!SendError(con
, HTTP_NOT_FOUND
))
1457 LogRequest(con
, HTTP_OK
);
1462 ProcessIPPRequest(con
);
1467 break; /* Anti-compiler-warning-code */
1470 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1481 * 'SendCommand()' - Send output from a command via HTTP.
1485 SendCommand(client_t
*con
,
1492 if (con
->filename
[0])
1493 fd
= open(con
->filename
, O_RDONLY
);
1495 fd
= open("/dev/null", O_RDONLY
);
1497 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
1501 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
1503 LogMessage(L_DEBUG
, "SendCommand() %d file=%d", con
->http
.fd
, con
->file
);
1505 if (con
->pipe_pid
== 0)
1508 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1510 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
1511 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
1514 FD_SET(con
->file
, &InputSet
);
1515 FD_SET(con
->http
.fd
, &OutputSet
);
1517 if (!SendHeader(con
, HTTP_OK
, NULL
))
1520 if (con
->http
.version
== HTTP_1_1
)
1522 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
1524 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
1528 con
->got_fields
= 0;
1536 * 'SendError()' - Send an error message via HTTP.
1539 int /* O - 1 if successful, 0 otherwise */
1540 SendError(client_t
*con
, /* I - Connection */
1541 http_status_t code
) /* I - Error code */
1543 char message
[1024]; /* Message for user */
1547 * Put the request in the access_log file...
1550 if (con
->operation
> HTTP_WAITING
)
1551 LogRequest(con
, code
);
1553 LogMessage(L_DEBUG
, "SendError() %d code=%d", con
->http
.fd
, code
);
1556 * To work around bugs in some proxies, don't use Keep-Alive for some
1560 if (code
>= HTTP_BAD_REQUEST
)
1561 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1564 * Send an error message back to the client. If the error code is a
1565 * 400 or 500 series, make sure the message contains some text, too!
1568 if (!SendHeader(con
, code
, NULL
))
1572 if (code
== HTTP_UPGRADE_REQUIRED
)
1573 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
1576 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
1578 #endif /* HAVE_LIBSSL */
1580 if (con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
)
1582 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
1586 if (code
>= HTTP_BAD_REQUEST
)
1589 * Send a human-readable error message.
1592 snprintf(message
, sizeof(message
),
1593 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
1594 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
1595 code
, httpStatus(code
), httpStatus(code
),
1596 con
->language
? con
->language
->messages
[code
] :
1599 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
1601 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n", strlen(message
)) < 0)
1603 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1605 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
1608 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
1611 con
->http
.state
= HTTP_WAITING
;
1618 * 'SendFile()' - Send a file via HTTP.
1622 SendFile(client_t
*con
,
1626 struct stat
*filestats
)
1628 con
->file
= open(filename
, O_RDONLY
);
1630 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
1635 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1639 if (!SendHeader(con
, code
, type
))
1642 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
1644 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1645 (unsigned long)filestats
->st_size
) < 0)
1647 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1650 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
1652 FD_SET(con
->http
.fd
, &OutputSet
);
1659 * 'SendHeader()' - Send an HTTP request.
1662 int /* O - 1 on success, 0 on failure */
1663 SendHeader(client_t
*con
, /* I - Client to send to */
1664 http_status_t code
, /* I - HTTP status code */
1665 char *type
) /* I - MIME type of document */
1667 location_t
*loc
; /* Authentication location */
1670 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
1671 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
1673 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
1675 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
1677 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
1679 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
1681 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
1684 if (code
== HTTP_METHOD_NOT_ALLOWED
)
1685 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
1688 if (code
== HTTP_UNAUTHORIZED
)
1691 * This already succeeded in IsAuthorized...
1694 loc
= FindBest(con
->uri
, con
->http
.state
);
1696 if (loc
->type
!= AUTH_DIGEST
)
1698 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
1703 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
1704 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
1708 if (con
->language
!= NULL
)
1710 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
1711 con
->language
->language
) < 0)
1715 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
1716 cupsLangEncoding(con
->language
)) < 0)
1719 else if (type
!= NULL
)
1720 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
1728 * 'ShutdownClient()' - Shutdown the receiving end of a connection.
1732 ShutdownClient(client_t
*con
) /* I - Client connection */
1735 * Shutdown the receiving end of the socket, since the client
1736 * still needs to read the error message...
1739 shutdown(con
->http
.fd
, 0);
1741 LogMessage(L_DEBUG2
, "ShutdownClient: Removing fd %d from InputSet...",
1744 FD_CLR(con
->http
.fd
, &InputSet
);
1749 * 'WriteClient()' - Write data to a client as needed.
1752 int /* O - 1 if success, 0 if fail */
1753 WriteClient(client_t
*con
) /* I - Client connection */
1755 int bytes
; /* Number of bytes written */
1756 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
1757 char *bufptr
; /* Pointer into buffer */
1758 ipp_state_t ipp_state
; /* IPP state value */
1761 if (con
->http
.state
!= HTTP_GET_SEND
&&
1762 con
->http
.state
!= HTTP_POST_SEND
)
1765 if (con
->response
!= NULL
)
1767 ipp_state
= ippWrite(&(con
->http
), con
->response
);
1768 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
1770 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
1772 if (con
->pipe_pid
&& !con
->got_fields
)
1775 * Inspect the data for Content-Type and other fields.
1780 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
1781 if (*bufptr
== '\n')
1784 * Send line to client...
1787 if (bufptr
> buf
&& bufptr
[-1] == '\r')
1791 httpPrintf(HTTP(con
), "%s\r\n", buf
);
1792 LogMessage(L_DEBUG2
, "WriteClient() %d %s", con
->http
.fd
, buf
);
1798 bytes
-= (bufptr
- buf
);
1799 memcpy(buf
, bufptr
, bytes
+ 1);
1803 * See if the line was empty...
1806 if (con
->field_col
== 0)
1807 con
->got_fields
= 1;
1811 else if (*bufptr
!= '\r')
1814 if (bytes
> 0 && !con
->got_fields
)
1817 * Remaining text needs to go out...
1820 httpPrintf(HTTP(con
), "%s", buf
);
1822 con
->http
.activity
= time(NULL
);
1825 else if (bytes
== 0)
1827 con
->http
.activity
= time(NULL
);
1832 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
1838 con
->bytes
+= bytes
;
1843 LogRequest(con
, HTTP_OK
);
1845 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
1847 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
1854 con
->http
.state
= HTTP_WAITING
;
1856 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from OutputSet...",
1859 FD_CLR(con
->http
.fd
, &OutputSet
);
1863 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from InputSet...",
1865 FD_CLR(con
->file
, &InputSet
);
1868 kill(con
->pipe_pid
, SIGTERM
);
1870 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
1871 con
->http
.fd
, con
->file
);
1878 if (con
->filename
[0])
1880 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
1881 con
->http
.fd
, con
->filename
);
1882 unlink(con
->filename
);
1883 con
->filename
[0] = '\0';
1886 if (con
->request
!= NULL
)
1888 ippDelete(con
->request
);
1889 con
->request
= NULL
;
1892 if (con
->response
!= NULL
)
1894 ippDelete(con
->response
);
1895 con
->response
= NULL
;
1898 if (!con
->http
.keep_alive
)
1906 LogMessage(L_DEBUG2
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
1908 con
->http
.activity
= time(NULL
);
1915 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
1918 static int /* O - 1 if modified since */
1919 check_if_modified(client_t
*con
, /* I - Client connection */
1920 struct stat
*filestats
) /* I - File information */
1922 char *ptr
; /* Pointer into field */
1923 time_t date
; /* Time/date value */
1924 int size
; /* Size/length value */
1929 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
1934 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
1937 while (*ptr
!= '\0')
1939 while (isspace(*ptr
) || *ptr
== ';')
1942 if (strncasecmp(ptr
, "length=", 7) == 0)
1947 while (isdigit(*ptr
))
1950 else if (isalpha(*ptr
))
1952 date
= httpGetDateTime(ptr
);
1953 while (*ptr
!= '\0' && *ptr
!= ';')
1958 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
1959 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
1960 (int)filestats
->st_mtime
);
1962 return ((size
!= filestats
->st_size
&& size
!= 0) ||
1963 (date
< filestats
->st_mtime
&& date
!= 0) ||
1964 (size
== 0 && date
== 0));
1969 * 'decode_auth()' - Decode an authorization string.
1973 decode_auth(client_t
*con
) /* I - Client to decode to */
1975 char *s
, /* Authorization string */
1976 value
[1024]; /* Value string */
1977 const char *username
; /* Certificate username */
1981 * Decode the string...
1984 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
1986 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
1989 if (strncmp(s
, "Basic", 5) == 0)
1995 httpDecode64(value
, s
);
1998 * Pull the username and password out...
2001 if ((s
= strchr(value
, ':')) == NULL
)
2003 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2004 con
->http
.fd
, value
);
2010 strlcpy(con
->username
, value
, sizeof(con
->username
));
2011 strlcpy(con
->password
, s
, sizeof(con
->password
));
2013 else if (strncmp(s
, "Local", 5) == 0)
2019 if ((username
= FindCert(s
)) != NULL
)
2020 strlcpy(con
->username
, username
, sizeof(con
->username
));
2022 else if (strncmp(s
, "Digest", 5) == 0)
2025 * Get the username and password from the Digest attributes...
2028 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2030 strlcpy(con
->username
, value
, sizeof(con
->username
));
2032 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2034 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2037 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2038 con
->http
.fd
, con
->username
);
2043 * 'get_file()' - Get a filename and state info.
2046 static char * /* O - Real filename */
2047 get_file(client_t
*con
, /* I - Client connection */
2048 struct stat
*filestats
)/* O - File information */
2050 int status
; /* Status of filesystem calls */
2051 char *params
; /* Pointer to parameters in URI */
2052 static char filename
[1024]; /* Filename buffer */
2056 * Need to add DocumentRoot global...
2059 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2060 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
);
2061 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2062 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
+ 11);
2063 else if (con
->language
!= NULL
)
2064 snprintf(filename
, sizeof(filename
), "%s/%s%s", DocumentRoot
, con
->language
->language
,
2067 snprintf(filename
, sizeof(filename
), "%s%s", DocumentRoot
, con
->uri
);
2069 if ((params
= strchr(filename
, '?')) != NULL
)
2073 * Grab the status for this language; if there isn't a language-specific file
2074 * then fallback to the default one...
2077 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2080 * Drop the language prefix and try the current directory...
2083 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2084 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2086 snprintf(filename
, sizeof(filename
), "%s%s", DocumentRoot
, con
->uri
);
2088 status
= stat(filename
, filestats
);
2093 * If we're found a directory, get the index.html file instead...
2096 if (!status
&& S_ISDIR(filestats
->st_mode
))
2098 if (filename
[strlen(filename
) - 1] == '/')
2099 strlcat(filename
, "index.html", sizeof(filename
));
2101 strlcat(filename
, "/index.html", sizeof(filename
));
2103 status
= stat(filename
, filestats
);
2106 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2107 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2117 * 'install_conf_file()' - Install a configuration file.
2120 static http_status_t
/* O - Status */
2121 install_conf_file(client_t
*con
) /* I - Connection */
2123 FILE *in
, /* Input file */
2124 *out
; /* Output file */
2125 char buffer
[1024]; /* Copy buffer */
2126 int bytes
; /* Number of bytes */
2127 char conffile
[1024], /* Configuration filename */
2128 newfile
[1024], /* New config filename */
2129 oldfile
[1024]; /* Old config filename */
2130 struct stat confinfo
; /* Config file info */
2134 * First construct the filenames...
2137 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2138 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2139 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2141 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2144 * Get the owner, group, and permissions of the configuration file.
2145 * If it doesn't exist, assign it to the User and Group in the
2146 * cupsd.conf file with mode 0640 permissions.
2149 if (stat(conffile
, &confinfo
))
2151 confinfo
.st_uid
= User
;
2152 confinfo
.st_gid
= Group
;
2153 confinfo
.st_mode
= 0640;
2157 * Open the request file and new config file...
2160 if ((in
= fopen(con
->filename
, "rb")) == NULL
)
2162 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2163 con
->filename
, strerror(errno
));
2164 return (HTTP_SERVER_ERROR
);
2167 if ((out
= fopen(newfile
, "wb")) == NULL
)
2170 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2171 newfile
, strerror(errno
));
2172 return (HTTP_SERVER_ERROR
);
2175 fchmod(fileno(out
), confinfo
.st_mode
);
2176 fchown(fileno(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2179 * Copy from the request to the new config file...
2182 while ((bytes
= fread(buffer
, 1, sizeof(buffer
), in
)) > 0)
2183 if (fwrite(buffer
, 1, bytes
, out
) < bytes
)
2185 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2186 newfile
, strerror(errno
));
2192 return (HTTP_SERVER_ERROR
);
2196 * Close the files...
2202 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2203 newfile
, strerror(errno
));
2207 return (HTTP_SERVER_ERROR
);
2211 * Remove the request file...
2214 unlink(con
->filename
);
2215 con
->filename
[0] = '\0';
2218 * Unlink the old backup, rename the current config file to the backup
2219 * filename, and rename the new config file to the config file name...
2222 if (unlink(oldfile
))
2223 if (errno
!= ENOENT
)
2225 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2226 oldfile
, strerror(errno
));
2230 return (HTTP_SERVER_ERROR
);
2233 if (rename(conffile
, oldfile
))
2234 if (errno
!= ENOENT
)
2236 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2237 conffile
, strerror(errno
));
2241 return (HTTP_SERVER_ERROR
);
2244 if (rename(newfile
, conffile
))
2246 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2247 newfile
, strerror(errno
));
2249 rename(oldfile
, conffile
);
2252 return (HTTP_SERVER_ERROR
);
2256 * If the cupsd.conf file was updated, set the NeedReload flag...
2259 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2263 * Return that the file was created successfully...
2266 return (HTTP_CREATED
);
2271 * 'pipe_command()' - Pipe the output of a command to the remote client.
2274 static int /* O - Process ID */
2275 pipe_command(client_t
*con
, /* I - Client connection */
2276 int infile
, /* I - Standard input for command */
2277 int *outfile
, /* O - Standard output for command */
2278 char *command
, /* I - Command to run */
2279 char *options
) /* I - Options for command */
2281 int pid
; /* Process ID */
2282 char *commptr
; /* Command string pointer */
2283 int fd
; /* Looping var */
2284 int fds
[2]; /* Pipe FDs */
2285 int argc
; /* Number of arguments */
2286 int envc
; /* Number of environment variables */
2287 char argbuf
[10240], /* Argument buffer */
2288 *argv
[100], /* Argument strings */
2289 *envp
[100]; /* Environment variables */
2290 char lang
[1024], /* LANG env variable */
2291 content_length
[1024], /* CONTENT_LENGTH env variable */
2292 content_type
[1024], /* CONTENT_TYPE env variable */
2293 ipp_port
[1024], /* Default listen port */
2294 server_port
[1024], /* Default server port */
2295 server_name
[1024], /* Default listen hostname */
2296 remote_host
[1024], /* REMOTE_HOST env variable */
2297 remote_user
[1024], /* REMOTE_USER env variable */
2298 tmpdir
[1024], /* TMPDIR environment variable */
2299 ldpath
[1024], /* LD_LIBRARY_PATH environment variable */
2300 nlspath
[1024], /* NLSPATH environment variable */
2301 datadir
[1024], /* CUPS_DATADIR environment variable */
2302 root
[1024], /* CUPS_SERVERROOT environment variable */
2303 query_string
[10240]; /* QUERY_STRING env variable */
2304 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
2305 sigset_t oldmask
, /* POSIX signal masks */
2307 struct sigaction action
; /* POSIX signal handler */
2308 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
2312 * Copy the command string...
2315 strlcpy(argbuf
, options
, sizeof(argbuf
));
2318 * Parse the string; arguments can be separated by + and are terminated
2324 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
2325 if (*commptr
== ' ' || *commptr
== '+')
2329 while (*commptr
== ' ')
2332 if (*commptr
!= '\0')
2334 argv
[argc
] = commptr
;
2340 else if (*commptr
== '%')
2342 if (commptr
[1] >= '0' && commptr
[1] <= '9')
2343 *commptr
= (commptr
[1] - '0') << 4;
2345 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
2347 if (commptr
[2] >= '0' && commptr
[2] <= '9')
2348 *commptr
|= commptr
[2] - '0';
2350 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
2352 strcpy(commptr
+ 1, commptr
+ 3);
2354 else if (*commptr
== '?')
2359 if (argv
[0][0] == '\0')
2360 argv
[0] = strrchr(command
, '/') + 1;
2363 * Setup the environment variables as needed...
2366 snprintf(lang
, sizeof(lang
), "LANG=%s",
2367 con
->language
? con
->language
->language
: "C");
2369 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
2371 sprintf(ipp_port
, "IPP_PORT=%d", ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
2372 sprintf(server_port
, "SERVER_PORT=%d",
2373 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
2376 #endif /* AF_INET6 */
2378 sprintf(ipp_port
, "IPP_PORT=%d", ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
2379 sprintf(server_port
, "SERVER_PORT=%d",
2380 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
2383 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
2384 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
2385 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
2386 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
2387 snprintf(datadir
, sizeof(datadir
), "CUPS_DATADIR=%s", DataDir
);
2388 snprintf(root
, sizeof(root
), "CUPS_SERVERROOT=%s", ServerRoot
);
2390 if (getenv("LD_LIBRARY_PATH") != NULL
)
2391 snprintf(ldpath
, sizeof(ldpath
), "LD_LIBRARY_PATH=%s",
2392 getenv("LD_LIBRARY_PATH"));
2393 else if (getenv("DYLD_LIBRARY_PATH") != NULL
)
2394 snprintf(ldpath
, sizeof(ldpath
), "DYLD_LIBRARY_PATH=%s",
2395 getenv("DYLD_LIBRARY_PATH"));
2396 else if (getenv("SHLIB_PATH") != NULL
)
2397 snprintf(ldpath
, sizeof(ldpath
), "SHLIB_PATH=%s",
2398 getenv("SHLIB_PATH"));
2402 if (getenv("NLSPATH") != NULL
)
2403 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
2407 envp
[0] = "PATH=/bin:/usr/bin";
2408 envp
[1] = "SERVER_SOFTWARE=CUPS/1.2";
2409 envp
[2] = "GATEWAY_INTERFACE=CGI/1.1";
2410 envp
[3] = "SERVER_PROTOCOL=HTTP/1.1";
2412 envp
[5] = server_name
;
2413 envp
[6] = server_port
;
2414 envp
[7] = remote_host
;
2415 envp
[8] = remote_user
;
2425 envp
[envc
++] = ldpath
;
2428 envp
[envc
++] = nlspath
;
2430 if (con
->operation
== HTTP_GET
)
2432 envp
[envc
++] = "REQUEST_METHOD=GET";
2437 * Add GET form variables after ?...
2442 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
2443 envp
[envc
++] = query_string
;
2448 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
2449 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
2450 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
2452 envp
[envc
++] = "REQUEST_METHOD=POST";
2453 envp
[envc
++] = content_length
;
2454 envp
[envc
++] = content_type
;
2458 * Tell the CGI if we are using encryption...
2461 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
2463 envp
[envc
++] = "HTTPS=ON";
2464 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
2470 * Create a pipe for the output...
2475 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
2476 argv
[0], strerror(errno
));
2481 * Block signals before forking...
2487 #elif defined(HAVE_SIGACTION)
2488 sigemptyset(&newmask
);
2489 sigaddset(&newmask
, SIGTERM
);
2490 sigaddset(&newmask
, SIGCHLD
);
2491 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
2492 #endif /* HAVE_SIGSET */
2495 * Then execute the command...
2498 if ((pid
= fork()) == 0)
2501 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
2507 * Running as root, so change to a non-priviledged user...
2518 * Reset group membership to just the main one we belong to.
2524 * Update stdin/stdout/stderr...
2530 if (dup(infile
) < 0)
2535 if (dup(fds
[1]) < 0)
2539 open("/dev/null", O_WRONLY
);
2542 * Close extra file descriptors...
2545 for (fd
= 3; fd
< MaxFDs
; fd
++)
2549 * Change umask to restrict permissions on created files...
2555 * Unblock signals before doing the exec...
2559 sigset(SIGTERM
, SIG_DFL
);
2560 sigset(SIGCHLD
, SIG_DFL
);
2564 #elif defined(HAVE_SIGACTION)
2565 memset(&action
, 0, sizeof(action
));
2567 sigemptyset(&action
.sa_mask
);
2568 action
.sa_handler
= SIG_DFL
;
2570 sigaction(SIGTERM
, &action
, NULL
);
2571 sigaction(SIGCHLD
, &action
, NULL
);
2573 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2575 signal(SIGTERM
, SIG_DFL
);
2576 signal(SIGCHLD
, SIG_DFL
);
2577 #endif /* HAVE_SIGSET */
2581 * Execute the pipe program; if an error occurs, exit with status 1...
2584 execve(command
, argv
, envp
);
2591 * Error - can't fork!
2594 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
2604 * Fork successful - return the PID...
2607 AddCert(pid
, con
->username
);
2609 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
2618 #elif defined(HAVE_SIGACTION)
2619 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2620 #endif /* HAVE_SIGSET */
2627 * End of "$Id: client.c,v 1.91.2.21 2002/09/25 12:52:41 mike Exp $".