2 * "$Id: client.c,v 1.91.2.32 2003/01/13 18:41:42 mike Exp $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2003 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 count
; /* Count of connections on a host */
81 int val
; /* Parameter value */
82 client_t
*con
; /* New client pointer */
83 const struct hostent
*host
; /* Host entry for address */
84 char *hostname
;/* Hostname for address */
85 http_addr_t temp
; /* Temporary address variable */
86 static time_t last_dos
= 0;
87 /* Time of last DoS attack */
90 LogMessage(L_DEBUG2
, "AcceptClient(%p) %d NumClients = %d",
91 lis
, lis
->fd
, NumClients
);
94 * Make sure we don't have a full set of clients already...
97 if (NumClients
== MaxClients
)
101 * Get a pointer to the next available client...
104 con
= Clients
+ NumClients
;
106 memset(con
, 0, sizeof(client_t
));
107 con
->http
.activity
= time(NULL
);
110 * Accept the client and get the remote address...
113 val
= sizeof(struct sockaddr_in
);
115 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
),
118 LogMessage(L_ERROR
, "Unable to accept client connection - %s.",
124 if (lis
->address
.addr
.sa_family
== AF_INET6
)
125 con
->http
.hostaddr
.ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
127 #endif /* AF_INET6 */
128 con
->http
.hostaddr
.ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
131 * Check the number of clients on the same address...
134 for (i
= 0, count
= 0; i
< NumClients
; i
++)
135 if (memcmp(&(Clients
[i
].http
.hostaddr
), &(con
->http
.hostaddr
),
136 sizeof(con
->http
.hostaddr
)) == 0)
139 if (count
>= MaxClientsPerHost
)
143 if (count
>= MaxClientsPerHost
)
145 if ((time(NULL
) - last_dos
) >= 60)
147 last_dos
= time(NULL
);
148 LogMessage(L_WARN
, "Possible DoS attack - more than %d clients connecting from %s!",
149 MaxClientsPerHost
, Clients
[i
].http
.hostname
);
153 closesocket(con
->http
.fd
);
162 * Get the hostname or format the IP address as needed...
166 hostname
= httpAddrLookup(&(con
->http
.hostaddr
), con
->http
.hostname
,
167 sizeof(con
->http
.hostname
));
171 httpAddrString(&(con
->http
.hostaddr
), con
->http
.hostname
,
172 sizeof(con
->http
.hostname
));
175 if (httpAddrLocalhost(&(con
->http
.hostaddr
)))
178 * Map accesses from the loopback interface to "localhost"...
181 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
183 else if (httpAddrEqual(&(con
->http
.hostaddr
), &ServerAddr
))
186 * Map accesses from the same host to the server name.
189 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
192 if (hostname
== NULL
&& HostNameLookups
== 2)
195 * Can't have an unresolved IP address with double-lookups enabled...
198 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
202 closesocket(con
->http
.fd
);
207 LogMessage(L_WARN
, "Name lookup failed - connection from %s closed!",
212 if (HostNameLookups
== 2)
215 * Do double lookups as needed...
218 if ((host
= httpGetHostByName(con
->http
.hostname
)) != NULL
)
221 * See if the hostname maps to the same IP address...
224 if (host
->h_addrtype
!= con
->http
.hostaddr
.addr
.sa_family
)
227 * Not the right type of address...
235 * Compare all of the addresses against this one...
238 for (i
= 0; host
->h_addr_list
[i
]; i
++)
240 httpAddrLoad(host
, 0, i
, &temp
);
242 if (httpAddrEqual(&(con
->http
.hostaddr
), &temp
))
246 if (!host
->h_addr_list
[i
])
254 * Can't have a hostname that doesn't resolve to the same IP address
255 * with double-lookups enabled...
258 LogMessage(L_DEBUG2
, "AcceptClient: Closing connection %d...",
262 closesocket(con
->http
.fd
);
267 LogMessage(L_WARN
, "IP lookup failed - connection from %s closed!",
274 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
275 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
276 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
278 #endif /* AF_INET6 */
279 LogMessage(L_DEBUG
, "AcceptClient: %d from %s:%d.", con
->http
.fd
,
280 con
->http
.hostname
, ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
283 * Using TCP_NODELAY improves responsiveness, especially on systems
284 * with a slow loopback interface... Since we write large buffers
285 * when sending print files and requests, there shouldn't be any
286 * performance penalty for this...
290 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
293 * Add the socket to the select() input mask.
296 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
298 LogMessage(L_DEBUG2
, "AcceptClient: Adding fd %d to InputSet...",
300 FD_SET(con
->http
.fd
, &InputSet
);
305 * Temporarily suspend accept()'s until we lose a client...
308 if (NumClients
== MaxClients
)
313 * See if we are connecting on a secure port...
316 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
319 * https connection; go secure...
322 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
326 #endif /* HAVE_LIBSSL */
331 * 'CloseAllClients()' - Close all remote clients immediately.
335 CloseAllClients(void)
337 while (NumClients
> 0)
338 CloseClient(Clients
);
343 * 'CloseClient()' - Close a remote client.
347 CloseClient(client_t
*con
) /* I - Client to close */
349 int status
; /* Exit status of pipe command */
351 SSL_CTX
*context
; /* Context for encryption */
352 SSL
*conn
; /* Connection for encryption */
353 unsigned long error
; /* Error code */
354 #endif /* HAVE_LIBSSL */
357 LogMessage(L_DEBUG
, "CloseClient() %d", con
->http
.fd
);
361 * Shutdown encryption as needed...
366 conn
= (SSL
*)(con
->http
.tls
);
367 context
= SSL_get_SSL_CTX(conn
);
369 switch (SSL_shutdown(conn
))
372 LogMessage(L_INFO
, "CloseClient: SSL shutdown successful!");
375 LogMessage(L_ERROR
, "CloseClient: Fatal error during SSL shutdown!");
377 while ((error
= ERR_get_error()) != 0)
378 LogMessage(L_ERROR
, "CloseClient: %s", ERR_error_string(error
, NULL
));
382 SSL_CTX_free(context
);
385 con
->http
.tls
= NULL
;
387 #endif /* HAVE_LIBSSL */
390 * Close the socket and clear the file from the input set for select()...
393 if (con
->http
.fd
>= 0)
395 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet and OutputSet...",
398 FD_CLR(con
->http
.fd
, &InputSet
);
399 FD_CLR(con
->http
.fd
, &OutputSet
);
403 if (con
->pipe_pid
!= 0)
405 LogMessage(L_DEBUG2
, "CloseClient: Removing fd %d from InputSet...",
407 FD_CLR(con
->file
, &InputSet
);
413 * Close the open data file...
418 kill(con
->pipe_pid
, SIGKILL
);
419 waitpid(con
->pipe_pid
, &status
, WNOHANG
);
422 LogMessage(L_DEBUG2
, "CloseClient() %d Closing data file %d.",
423 con
->http
.fd
, con
->file
);
424 LogMessage(L_DEBUG2
, "CloseClient() %d Removing fd %d from InputSet.",
425 con
->http
.fd
, con
->file
);
427 FD_CLR(con
->file
, &InputSet
);
434 ippDelete(con
->request
);
440 ippDelete(con
->response
);
441 con
->response
= NULL
;
446 cupsLangFree(con
->language
);
447 con
->language
= NULL
;
451 * Re-enable new client connections if we are going back under the
455 if (NumClients
== MaxClients
)
459 * Compact the list of clients as necessary...
464 if (con
< (Clients
+ NumClients
))
465 memcpy(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
470 * 'EncryptClient()' - Enable encryption for the client...
473 int /* O - 1 on success, 0 on error */
474 EncryptClient(client_t
*con
) /* I - Client to encrypt */
477 SSL_CTX
*context
; /* Context for encryption */
478 SSL
*conn
; /* Connection for encryption */
479 unsigned long error
; /* Error code */
483 * Create the SSL context and accept the connection...
486 context
= SSL_CTX_new(SSLv23_method());
487 conn
= SSL_new(context
);
489 SSL_use_PrivateKey_file(conn
, ServerKey
, SSL_FILETYPE_PEM
);
490 SSL_use_certificate_file(conn
, ServerCertificate
, SSL_FILETYPE_PEM
);
492 SSL_set_fd(conn
, con
->http
.fd
);
493 if (SSL_accept(conn
) != 1)
495 while ((error
= ERR_get_error()) != 0)
496 LogMessage(L_ERROR
, "EncryptClient: %s", ERR_error_string(error
, NULL
));
498 SSL_CTX_free(context
);
503 con
->http
.tls
= conn
;
507 #endif /* HAVE_LIBSSL */
512 * 'ReadClient()' - Read data from a client.
515 int /* O - 1 on success, 0 on error */
516 ReadClient(client_t
*con
) /* I - Client to read from */
518 char line
[32768], /* Line from client... */
519 operation
[64], /* Operation code from socket */
520 version
[64]; /* HTTP version number string */
521 int major
, minor
; /* HTTP version numbers */
522 http_status_t status
; /* Transfer status */
523 ipp_state_t ipp_state
; /* State of IPP transfer */
524 int bytes
; /* Number of bytes to POST */
525 char *filename
; /* Name of file for GET/HEAD */
526 struct stat filestats
; /* File information */
527 mime_type_t
*type
; /* MIME type of file */
528 printer_t
*p
; /* Printer */
529 location_t
*best
; /* Best match for authentication */
530 static unsigned request_id
= 0;/* Request ID for temp files */
533 status
= HTTP_CONTINUE
;
535 LogMessage(L_DEBUG2
, "ReadClient() %d, used=%d", con
->http
.fd
,
544 switch (con
->http
.state
)
548 * See if we've received a request line...
551 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
558 * Ignore blank request lines...
565 * Clear other state variables...
568 httpClearFields(HTTP(con
));
570 con
->http
.activity
= time(NULL
);
571 con
->http
.version
= HTTP_1_0
;
572 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
573 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
574 con
->http
.data_remaining
= 0;
575 con
->operation
= HTTP_WAITING
;
579 con
->command
[0] = '\0';
580 con
->username
[0] = '\0';
581 con
->password
[0] = '\0';
584 if (con
->language
!= NULL
)
586 cupsLangFree(con
->language
);
587 con
->language
= NULL
;
591 * Grab the request line...
594 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
597 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
598 SendError(con
, HTTP_BAD_REQUEST
);
602 con
->http
.version
= HTTP_0_9
;
605 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
607 LogMessage(L_ERROR
, "Bad request line \"%s\"!", line
);
608 SendError(con
, HTTP_BAD_REQUEST
);
615 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
616 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
617 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
619 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
623 SendError(con
, HTTP_NOT_SUPPORTED
);
631 * Process the request...
634 if (strcmp(operation
, "GET") == 0)
635 con
->http
.state
= HTTP_GET
;
636 else if (strcmp(operation
, "PUT") == 0)
637 con
->http
.state
= HTTP_PUT
;
638 else if (strcmp(operation
, "POST") == 0)
639 con
->http
.state
= HTTP_POST
;
640 else if (strcmp(operation
, "DELETE") == 0)
641 con
->http
.state
= HTTP_DELETE
;
642 else if (strcmp(operation
, "TRACE") == 0)
643 con
->http
.state
= HTTP_TRACE
;
644 else if (strcmp(operation
, "OPTIONS") == 0)
645 con
->http
.state
= HTTP_OPTIONS
;
646 else if (strcmp(operation
, "HEAD") == 0)
647 con
->http
.state
= HTTP_HEAD
;
650 LogMessage(L_ERROR
, "Bad operation \"%s\"!", operation
);
651 SendError(con
, HTTP_BAD_REQUEST
);
656 con
->start
= time(NULL
);
657 con
->operation
= con
->http
.state
;
659 LogMessage(L_DEBUG
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
661 con
->http
.version
/ 100, con
->http
.version
% 100);
663 con
->http
.status
= HTTP_OK
;
673 * Parse incoming parameters until the status changes...
676 status
= httpUpdate(HTTP(con
));
678 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
680 SendError(con
, HTTP_BAD_REQUEST
);
687 break; /* Anti-compiler-warning-code */
691 * Handle new transfers...
694 if (status
== HTTP_OK
)
696 con
->language
= cupsLangGet(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
700 if (strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) == 0 &&
702 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
704 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
705 con
->http
.version
>= HTTP_1_1
)
708 * HTTP/1.1 and higher require the "Host:" field...
711 if (!SendError(con
, HTTP_BAD_REQUEST
))
717 else if (con
->operation
== HTTP_OPTIONS
)
720 * Do OPTIONS command...
723 if ((best
= FindBest(con
->uri
, con
->http
.state
)) != NULL
&&
724 best
->type
!= AUTH_NONE
)
726 if (!SendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
733 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
734 con
->http
.tls
== NULL
)
738 * Do encryption stuff...
741 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
747 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
748 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
749 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
750 httpPrintf(HTTP(con
), "\r\n");
754 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
759 #endif /* HAVE_LIBSSL */
762 if (!SendHeader(con
, HTTP_OK
, NULL
))
768 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
769 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
770 httpPrintf(HTTP(con
), "\r\n");
772 else if (strstr(con
->uri
, "..") != NULL
)
775 * Protect against malicious users!
778 if (!SendError(con
, HTTP_FORBIDDEN
))
784 else if (con
->uri
[0] != '/')
787 * Don't allow proxying (yet)...
790 if (!SendError(con
, HTTP_METHOD_NOT_ALLOWED
))
798 if (strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") == 0 &&
799 con
->http
.tls
== NULL
)
803 * Do encryption stuff...
806 if (!SendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
812 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
813 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
814 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
815 httpPrintf(HTTP(con
), "\r\n");
819 status
= IsAuthorized(con
);
821 if (!SendError(con
, HTTP_NOT_IMPLEMENTED
))
826 #endif /* HAVE_LIBSSL */
829 if (status
!= HTTP_OK
)
831 LogMessage(L_DEBUG2
, "ReadClient: Unauthorized request for %s...\n",
833 SendError(con
, status
);
838 switch (con
->http
.state
)
841 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
842 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
845 * Send PPD file - get the real printer name since printer
846 * names are not case sensitive but filenames can be...
849 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
851 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
852 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
855 if (!SendError(con
, HTTP_NOT_FOUND
))
865 if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
866 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
867 strncmp(con
->uri
, "/printers", 9) == 0 ||
868 strncmp(con
->uri
, "/classes", 8) == 0 ||
869 strncmp(con
->uri
, "/jobs", 5) == 0)
875 if (strncmp(con
->uri
, "/admin", 6) == 0)
877 snprintf(con
->command
, sizeof(con
->command
),
878 "%s/cgi-bin/admin.cgi", ServerBin
);
879 con
->options
= con
->uri
+ 6;
881 else if (strncmp(con
->uri
, "/printers", 9) == 0)
883 snprintf(con
->command
, sizeof(con
->command
),
884 "%s/cgi-bin/printers.cgi", ServerBin
);
885 con
->options
= con
->uri
+ 9;
887 else if (strncmp(con
->uri
, "/classes", 8) == 0)
889 snprintf(con
->command
, sizeof(con
->command
),
890 "%s/cgi-bin/classes.cgi", ServerBin
);
891 con
->options
= con
->uri
+ 8;
895 snprintf(con
->command
, sizeof(con
->command
),
896 "%s/cgi-bin/jobs.cgi", ServerBin
);
897 con
->options
= con
->uri
+ 5;
900 if (con
->options
[0] == '/')
903 if (!SendCommand(con
, con
->command
, con
->options
))
905 if (!SendError(con
, HTTP_NOT_FOUND
))
912 LogRequest(con
, HTTP_OK
);
914 if (con
->http
.version
<= HTTP_1_0
)
915 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
917 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
918 (strchr(con
->uri
+ 12, '/') != NULL
||
919 strlen(con
->uri
) == 12))
922 * GET can only be done to configuration files under
926 if (!SendError(con
, HTTP_FORBIDDEN
))
940 if ((filename
= get_file(con
, &filestats
)) == NULL
)
942 if (!SendError(con
, HTTP_NOT_FOUND
))
948 else if (!check_if_modified(con
, &filestats
))
950 if (!SendError(con
, HTTP_NOT_MODIFIED
))
958 type
= mimeFileType(MimeDatabase
, filename
);
960 strcpy(line
, "text/plain");
962 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
964 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
973 case HTTP_POST_RECV
:
975 * See if the POST request includes a Content-Length field, and if
976 * so check the length against any limits that are set...
979 LogMessage(L_DEBUG2
, "POST %s", con
->uri
);
980 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
982 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
983 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
987 * Request too large...
990 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
998 else if (atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) < 0)
1001 * Negative content lengths are invalid!
1004 if (!SendError(con
, HTTP_BAD_REQUEST
))
1014 * See what kind of POST request this is; for IPP requests the
1015 * content-type field will be "application/ipp"...
1018 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
1019 con
->request
= ippNew();
1020 else if ((strncmp(con
->uri
, "/admin", 6) == 0 &&
1021 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1022 strncmp(con
->uri
, "/printers", 9) == 0 ||
1023 strncmp(con
->uri
, "/classes", 8) == 0 ||
1024 strncmp(con
->uri
, "/jobs", 5) == 0)
1030 if (strncmp(con
->uri
, "/admin", 6) == 0)
1032 snprintf(con
->command
, sizeof(con
->command
),
1033 "%s/cgi-bin/admin.cgi", ServerBin
);
1034 con
->options
= con
->uri
+ 6;
1036 else if (strncmp(con
->uri
, "/printers", 9) == 0)
1038 snprintf(con
->command
, sizeof(con
->command
),
1039 "%s/cgi-bin/printers.cgi", ServerBin
);
1040 con
->options
= con
->uri
+ 9;
1042 else if (strncmp(con
->uri
, "/classes", 8) == 0)
1044 snprintf(con
->command
, sizeof(con
->command
),
1045 "%s/cgi-bin/classes.cgi", ServerBin
);
1046 con
->options
= con
->uri
+ 8;
1050 snprintf(con
->command
, sizeof(con
->command
),
1051 "%s/cgi-bin/jobs.cgi", ServerBin
);
1052 con
->options
= con
->uri
+ 5;
1055 if (con
->options
[0] == '/')
1058 LogMessage(L_DEBUG2
, "ReadClient() %d command=\"%s\", options = \"%s\"",
1059 con
->http
.fd
, con
->command
, con
->options
);
1061 if (con
->http
.version
<= HTTP_1_0
)
1062 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1064 else if (!SendError(con
, HTTP_UNAUTHORIZED
))
1071 case HTTP_PUT_RECV
:
1073 * Validate the resource name...
1076 if (strncmp(con
->uri
, "/admin/conf/", 12) != 0 ||
1077 strchr(con
->uri
+ 12, '/') != NULL
||
1078 strlen(con
->uri
) == 12)
1081 * PUT can only be done to configuration files under
1085 if (!SendError(con
, HTTP_FORBIDDEN
))
1095 * See if the PUT request includes a Content-Length field, and if
1096 * so check the length against any limits that are set...
1099 LogMessage(L_DEBUG2
, "PUT %s", con
->uri
);
1100 LogMessage(L_DEBUG2
, "CONTENT_TYPE = %s", con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1102 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1103 atoi(con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
]) > MaxRequestSize
&&
1107 * Request too large...
1110 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1120 * Open a temporary file to hold the request...
1123 snprintf(con
->filename
, sizeof(con
->filename
), "%s/%08x",
1124 RequestRoot
, request_id
++);
1125 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1126 fchmod(con
->file
, 0640);
1127 fchown(con
->file
, User
, Group
);
1129 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1130 con
->filename
, con
->file
);
1134 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1144 SendError(con
, HTTP_NOT_IMPLEMENTED
);
1145 ShutdownClient(con
);
1149 if (strncmp(con
->uri
, "/printers/", 10) == 0 &&
1150 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
1153 * Send PPD file - get the real printer name since printer
1154 * names are not case sensitive but filenames can be...
1157 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1159 if ((p
= FindPrinter(con
->uri
+ 10)) != NULL
)
1160 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1163 if (!SendError(con
, HTTP_NOT_FOUND
))
1173 if ((strncmp(con
->uri
, "/admin/", 7) == 0 &&
1174 strncmp(con
->uri
, "/admin/conf/", 12) != 0) ||
1175 strncmp(con
->uri
, "/printers/", 10) == 0 ||
1176 strncmp(con
->uri
, "/classes/", 9) == 0 ||
1177 strncmp(con
->uri
, "/jobs/", 6) == 0)
1183 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1189 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1195 LogRequest(con
, HTTP_OK
);
1197 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0 &&
1198 (strchr(con
->uri
+ 12, '/') != NULL
||
1199 strlen(con
->uri
) == 12))
1202 * HEAD can only be done to configuration files under
1206 if (!SendError(con
, HTTP_FORBIDDEN
))
1214 else if ((filename
= get_file(con
, &filestats
)) == NULL
)
1216 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1222 LogRequest(con
, HTTP_NOT_FOUND
);
1224 else if (!check_if_modified(con
, &filestats
))
1226 if (!SendError(con
, HTTP_NOT_MODIFIED
))
1232 LogRequest(con
, HTTP_NOT_MODIFIED
);
1240 type
= mimeFileType(MimeDatabase
, filename
);
1242 strcpy(line
, "text/plain");
1244 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1246 if (!SendHeader(con
, HTTP_OK
, line
))
1252 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1253 httpGetDateString(filestats
.st_mtime
)) < 0)
1259 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1260 (unsigned long)filestats
.st_size
) < 0)
1266 LogRequest(con
, HTTP_OK
);
1269 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1275 con
->http
.state
= HTTP_WAITING
;
1279 break; /* Anti-compiler-warning-code */
1285 * Handle any incoming data...
1288 switch (con
->http
.state
)
1290 case HTTP_PUT_RECV
:
1291 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1293 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1294 con
->http
.data_remaining
, con
->file
);
1296 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1303 con
->bytes
+= bytes
;
1305 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1306 con
->http
.fd
, bytes
, con
->file
);
1308 if (write(con
->file
, line
, bytes
) < bytes
)
1310 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1311 bytes
, con
->filename
, strerror(errno
));
1313 LogMessage(L_DEBUG2
, "ReadClient: Closing data file %d...",
1318 unlink(con
->filename
);
1319 con
->filename
[0] = '\0';
1321 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1329 if (con
->http
.state
== HTTP_WAITING
)
1332 * End of file, see how big it is...
1335 fstat(con
->file
, &filestats
);
1337 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1338 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1343 if (filestats
.st_size
> MaxRequestSize
&&
1347 * Request is too big; remove it and send an error...
1350 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1351 con
->http
.fd
, con
->filename
);
1352 unlink(con
->filename
);
1353 con
->filename
[0] = '\0';
1355 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1363 * Install the configuration file...
1366 status
= install_conf_file(con
);
1369 * Return the status to the client...
1372 if (!SendError(con
, status
))
1380 case HTTP_POST_RECV
:
1381 LogMessage(L_DEBUG2
, "ReadClient() %d con->data_encoding = %s, con->data_remaining = %d, con->file = %d",
1383 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
1384 con
->http
.data_remaining
, con
->file
);
1386 if (con
->request
!= NULL
)
1389 * Grab any request data from the connection...
1392 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1394 LogMessage(L_ERROR
, "ReadClient() %d IPP Read Error!",
1399 else if (ipp_state
!= IPP_DATA
)
1402 con
->bytes
+= ippLength(con
->request
);
1405 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
1408 * Create a file as needed for the request data...
1411 snprintf(con
->filename
, sizeof(con
->filename
), "%s/%08x",
1412 RequestRoot
, request_id
++);
1413 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1414 fchmod(con
->file
, 0640);
1415 fchown(con
->file
, User
, Group
);
1417 LogMessage(L_DEBUG2
, "ReadClient() %d REQUEST %s=%d", con
->http
.fd
,
1418 con
->filename
, con
->file
);
1422 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1430 if (con
->http
.state
!= HTTP_POST_SEND
)
1432 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
1439 con
->bytes
+= bytes
;
1441 LogMessage(L_DEBUG2
, "ReadClient() %d writing %d bytes to %d",
1442 con
->http
.fd
, bytes
, con
->file
);
1444 if (write(con
->file
, line
, bytes
) < bytes
)
1446 LogMessage(L_ERROR
, "ReadClient: Unable to write %d bytes to %s: %s",
1447 bytes
, con
->filename
, strerror(errno
));
1449 LogMessage(L_DEBUG2
, "ReadClient: Closing file %d...",
1454 unlink(con
->filename
);
1455 con
->filename
[0] = '\0';
1457 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1464 else if (con
->http
.state
!= HTTP_POST_SEND
)
1471 if (con
->http
.state
== HTTP_POST_SEND
)
1475 fstat(con
->file
, &filestats
);
1477 LogMessage(L_DEBUG2
, "ReadClient() %d Closing data file %d, size = %d.",
1478 con
->http
.fd
, con
->file
, (int)filestats
.st_size
);
1483 if (filestats
.st_size
> MaxRequestSize
&&
1487 * Request is too big; remove it and send an error...
1490 LogMessage(L_DEBUG2
, "ReadClient() %d Removing temp file %s",
1491 con
->http
.fd
, con
->filename
);
1492 unlink(con
->filename
);
1493 con
->filename
[0] = '\0';
1498 * Delete any IPP request data...
1501 ippDelete(con
->request
);
1502 con
->request
= NULL
;
1505 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
1512 if (con
->command
[0])
1514 if (!SendCommand(con
, con
->command
, con
->options
))
1516 if (!SendError(con
, HTTP_NOT_FOUND
))
1523 LogRequest(con
, HTTP_OK
);
1528 return (ProcessIPPRequest(con
));
1533 break; /* Anti-compiler-warning-code */
1536 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1547 * 'SendCommand()' - Send output from a command via HTTP.
1551 SendCommand(client_t
*con
,
1558 if (con
->filename
[0])
1559 fd
= open(con
->filename
, O_RDONLY
);
1561 fd
= open("/dev/null", O_RDONLY
);
1563 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
);
1567 LogMessage(L_INFO
, "Started \"%s\" (pid=%d)", command
, con
->pipe_pid
);
1569 LogMessage(L_DEBUG
, "SendCommand() %d file=%d", con
->http
.fd
, con
->file
);
1571 if (con
->pipe_pid
== 0)
1574 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1576 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to InputSet...", con
->file
);
1577 LogMessage(L_DEBUG2
, "SendCommand: Adding fd %d to OutputSet...",
1580 FD_SET(con
->file
, &InputSet
);
1581 FD_SET(con
->http
.fd
, &OutputSet
);
1583 if (!SendHeader(con
, HTTP_OK
, NULL
))
1586 if (con
->http
.version
== HTTP_1_1
)
1588 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
1590 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
1594 con
->got_fields
= 0;
1602 * 'SendError()' - Send an error message via HTTP.
1605 int /* O - 1 if successful, 0 otherwise */
1606 SendError(client_t
*con
, /* I - Connection */
1607 http_status_t code
) /* I - Error code */
1609 char message
[1024]; /* Message for user */
1613 * Put the request in the access_log file...
1616 if (con
->operation
> HTTP_WAITING
)
1617 LogRequest(con
, code
);
1619 LogMessage(L_DEBUG
, "SendError() %d code=%d", con
->http
.fd
, code
);
1622 * To work around bugs in some proxies, don't use Keep-Alive for some
1626 if (code
>= HTTP_BAD_REQUEST
)
1627 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1630 * Send an error message back to the client. If the error code is a
1631 * 400 or 500 series, make sure the message contains some text, too!
1634 if (!SendHeader(con
, code
, NULL
))
1638 if (code
== HTTP_UPGRADE_REQUIRED
)
1639 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
1642 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
1644 #endif /* HAVE_LIBSSL */
1646 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
1647 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
1649 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
1653 if (code
>= HTTP_BAD_REQUEST
)
1656 * Send a human-readable error message.
1659 snprintf(message
, sizeof(message
),
1660 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
1661 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
1662 code
, httpStatus(code
), httpStatus(code
),
1663 con
->language
? con
->language
->messages
[code
] :
1666 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
1668 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
1669 (int)strlen(message
)) < 0)
1671 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1673 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
1676 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
1679 con
->http
.state
= HTTP_WAITING
;
1686 * 'SendFile()' - Send a file via HTTP.
1690 SendFile(client_t
*con
,
1694 struct stat
*filestats
)
1696 con
->file
= open(filename
, O_RDONLY
);
1698 LogMessage(L_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
1703 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1707 if (!SendHeader(con
, code
, type
))
1710 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
1712 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1713 (unsigned long)filestats
->st_size
) < 0)
1715 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1718 LogMessage(L_DEBUG2
, "SendFile: Adding fd %d to OutputSet...", con
->http
.fd
);
1720 FD_SET(con
->http
.fd
, &OutputSet
);
1727 * 'SendHeader()' - Send an HTTP request.
1730 int /* O - 1 on success, 0 on failure */
1731 SendHeader(client_t
*con
, /* I - Client to send to */
1732 http_status_t code
, /* I - HTTP status code */
1733 char *type
) /* I - MIME type of document */
1735 location_t
*loc
; /* Authentication location */
1738 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
1739 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
1741 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
1743 if (httpPrintf(HTTP(con
), "Server: CUPS/1.1\r\n") < 0)
1745 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
1747 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
1749 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
1752 if (code
== HTTP_METHOD_NOT_ALLOWED
)
1753 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
1756 if (code
== HTTP_UNAUTHORIZED
)
1759 * This already succeeded in IsAuthorized...
1762 loc
= FindBest(con
->uri
, con
->http
.state
);
1764 if (loc
->type
!= AUTH_DIGEST
)
1766 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
1771 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Digest realm=\"CUPS\" "
1772 "nonce=\"%s\"\r\n", con
->http
.hostname
) < 0)
1776 if (con
->language
!= NULL
)
1778 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
1779 con
->language
->language
) < 0)
1783 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
1784 cupsLangEncoding(con
->language
)) < 0)
1787 else if (type
!= NULL
)
1788 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
1796 * 'ShutdownClient()' - Shutdown the receiving end of a connection.
1800 ShutdownClient(client_t
*con
) /* I - Client connection */
1803 * Shutdown the receiving end of the socket, since the client
1804 * still needs to read the error message...
1807 shutdown(con
->http
.fd
, 0);
1810 LogMessage(L_DEBUG2
, "ShutdownClient: Removing fd %d from InputSet...",
1813 FD_CLR(con
->http
.fd
, &InputSet
);
1818 * 'WriteClient()' - Write data to a client as needed.
1821 int /* O - 1 if success, 0 if fail */
1822 WriteClient(client_t
*con
) /* I - Client connection */
1824 int bytes
; /* Number of bytes written */
1825 char buf
[HTTP_MAX_BUFFER
+ 1];/* Data buffer */
1826 char *bufptr
; /* Pointer into buffer */
1827 ipp_state_t ipp_state
; /* IPP state value */
1830 if (con
->http
.state
!= HTTP_GET_SEND
&&
1831 con
->http
.state
!= HTTP_POST_SEND
)
1834 if (con
->response
!= NULL
)
1836 ipp_state
= ippWrite(&(con
->http
), con
->response
);
1837 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
1839 else if ((bytes
= read(con
->file
, buf
, HTTP_MAX_BUFFER
)) > 0)
1841 if (con
->pipe_pid
&& !con
->got_fields
)
1844 * Inspect the data for Content-Type and other fields.
1849 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
1850 if (*bufptr
== '\n')
1853 * Send line to client...
1856 if (bufptr
> buf
&& bufptr
[-1] == '\r')
1860 httpPrintf(HTTP(con
), "%s\r\n", buf
);
1861 LogMessage(L_DEBUG2
, "WriteClient() %d %s", con
->http
.fd
, buf
);
1867 bytes
-= (bufptr
- buf
);
1868 memcpy(buf
, bufptr
, bytes
+ 1);
1872 * See if the line was empty...
1875 if (con
->field_col
== 0)
1876 con
->got_fields
= 1;
1880 else if (*bufptr
!= '\r')
1883 if (bytes
> 0 && !con
->got_fields
)
1886 * Remaining text needs to go out...
1889 httpPrintf(HTTP(con
), "%s", buf
);
1891 con
->http
.activity
= time(NULL
);
1894 else if (bytes
== 0)
1896 con
->http
.activity
= time(NULL
);
1901 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
1907 con
->bytes
+= bytes
;
1912 LogRequest(con
, HTTP_OK
);
1914 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
1916 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
1923 con
->http
.state
= HTTP_WAITING
;
1925 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from OutputSet...",
1928 FD_CLR(con
->http
.fd
, &OutputSet
);
1932 LogMessage(L_DEBUG2
, "WriteClient() Removing fd %d from InputSet...",
1934 FD_CLR(con
->file
, &InputSet
);
1937 kill(con
->pipe_pid
, SIGTERM
);
1939 LogMessage(L_DEBUG2
, "WriteClient() %d Closing data file %d.",
1940 con
->http
.fd
, con
->file
);
1947 if (con
->filename
[0])
1949 LogMessage(L_DEBUG2
, "WriteClient() %d Removing temp file %s",
1950 con
->http
.fd
, con
->filename
);
1951 unlink(con
->filename
);
1952 con
->filename
[0] = '\0';
1955 if (con
->request
!= NULL
)
1957 ippDelete(con
->request
);
1958 con
->request
= NULL
;
1961 if (con
->response
!= NULL
)
1963 ippDelete(con
->response
);
1964 con
->response
= NULL
;
1967 if (!con
->http
.keep_alive
)
1975 LogMessage(L_DEBUG2
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
1977 con
->http
.activity
= time(NULL
);
1984 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
1987 static int /* O - 1 if modified since */
1988 check_if_modified(client_t
*con
, /* I - Client connection */
1989 struct stat
*filestats
) /* I - File information */
1991 char *ptr
; /* Pointer into field */
1992 time_t date
; /* Time/date value */
1993 int size
; /* Size/length value */
1998 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2003 LogMessage(L_DEBUG2
, "check_if_modified() %d If-Modified-Since=\"%s\"",
2006 while (*ptr
!= '\0')
2008 while (isspace(*ptr
) || *ptr
== ';')
2011 if (strncasecmp(ptr
, "length=", 7) == 0)
2016 while (isdigit(*ptr
))
2019 else if (isalpha(*ptr
))
2021 date
= httpGetDateTime(ptr
);
2022 while (*ptr
!= '\0' && *ptr
!= ';')
2027 LogMessage(L_DEBUG2
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
2028 con
->http
.fd
, size
, (int)filestats
->st_size
, (int)date
,
2029 (int)filestats
->st_mtime
);
2031 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2032 (date
< filestats
->st_mtime
&& date
!= 0) ||
2033 (size
== 0 && date
== 0));
2038 * 'decode_auth()' - Decode an authorization string.
2042 decode_auth(client_t
*con
) /* I - Client to decode to */
2044 char *s
, /* Authorization string */
2045 value
[1024]; /* Value string */
2046 const char *username
; /* Certificate username */
2050 * Decode the string...
2053 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
2055 LogMessage(L_DEBUG2
, "decode_auth(%p): Authorization string = \"%s\"",
2058 if (strncmp(s
, "Basic", 5) == 0)
2064 httpDecode64(value
, s
);
2067 * Pull the username and password out...
2070 if ((s
= strchr(value
, ':')) == NULL
)
2072 LogMessage(L_DEBUG
, "decode_auth() %d no colon in auth string \"%s\"",
2073 con
->http
.fd
, value
);
2079 strlcpy(con
->username
, value
, sizeof(con
->username
));
2080 strlcpy(con
->password
, s
, sizeof(con
->password
));
2082 else if (strncmp(s
, "Local", 5) == 0)
2088 if ((username
= FindCert(s
)) != NULL
)
2089 strlcpy(con
->username
, username
, sizeof(con
->username
));
2091 else if (strncmp(s
, "Digest", 5) == 0)
2094 * Get the username and password from the Digest attributes...
2097 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "username",
2099 strlcpy(con
->username
, value
, sizeof(con
->username
));
2101 if (httpGetSubField(&(con
->http
), HTTP_FIELD_WWW_AUTHENTICATE
, "response",
2103 strlcpy(con
->password
, value
, sizeof(con
->password
) - 1);
2106 LogMessage(L_DEBUG2
, "decode_auth() %d username=\"%s\"",
2107 con
->http
.fd
, con
->username
);
2112 * 'get_file()' - Get a filename and state info.
2115 static char * /* O - Real filename */
2116 get_file(client_t
*con
, /* I - Client connection */
2117 struct stat
*filestats
)/* O - File information */
2119 int status
; /* Status of filesystem calls */
2120 char *params
; /* Pointer to parameters in URI */
2121 static char filename
[1024]; /* Filename buffer */
2125 * Need to add DocumentRoot global...
2128 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
2129 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
);
2130 else if (strncmp(con
->uri
, "/admin/conf/", 12) == 0)
2131 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
+ 11);
2132 else if (con
->language
!= NULL
)
2133 snprintf(filename
, sizeof(filename
), "%s/%s%s", DocumentRoot
, con
->language
->language
,
2136 snprintf(filename
, sizeof(filename
), "%s%s", DocumentRoot
, con
->uri
);
2138 if ((params
= strchr(filename
, '?')) != NULL
)
2142 * Grab the status for this language; if there isn't a language-specific file
2143 * then fallback to the default one...
2146 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2149 * Drop the language prefix and try the current directory...
2152 if (strncmp(con
->uri
, "/ppd/", 5) != 0 &&
2153 strncmp(con
->uri
, "/admin/conf/", 12) != 0)
2155 snprintf(filename
, sizeof(filename
), "%s%s", DocumentRoot
, con
->uri
);
2157 status
= stat(filename
, filestats
);
2162 * If we're found a directory, get the index.html file instead...
2165 if (!status
&& S_ISDIR(filestats
->st_mode
))
2167 if (filename
[strlen(filename
) - 1] == '/')
2168 strlcat(filename
, "index.html", sizeof(filename
));
2170 strlcat(filename
, "/index.html", sizeof(filename
));
2172 status
= stat(filename
, filestats
);
2175 LogMessage(L_DEBUG2
, "get_file() %d filename=%s size=%d",
2176 con
->http
.fd
, filename
, status
? -1 : (int)filestats
->st_size
);
2186 * 'install_conf_file()' - Install a configuration file.
2189 static http_status_t
/* O - Status */
2190 install_conf_file(client_t
*con
) /* I - Connection */
2192 FILE *in
, /* Input file */
2193 *out
; /* Output file */
2194 char buffer
[1024]; /* Copy buffer */
2195 int bytes
; /* Number of bytes */
2196 char conffile
[1024], /* Configuration filename */
2197 newfile
[1024], /* New config filename */
2198 oldfile
[1024]; /* Old config filename */
2199 struct stat confinfo
; /* Config file info */
2203 * First construct the filenames...
2206 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2207 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2208 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2210 LogMessage(L_INFO
, "Installing config file \"%s\"...", conffile
);
2213 * Get the owner, group, and permissions of the configuration file.
2214 * If it doesn't exist, assign it to the User and Group in the
2215 * cupsd.conf file with mode 0640 permissions.
2218 if (stat(conffile
, &confinfo
))
2220 confinfo
.st_uid
= User
;
2221 confinfo
.st_gid
= Group
;
2222 confinfo
.st_mode
= 0640;
2226 * Open the request file and new config file...
2229 if ((in
= fopen(con
->filename
, "rb")) == NULL
)
2231 LogMessage(L_ERROR
, "Unable to open request file \"%s\" - %s",
2232 con
->filename
, strerror(errno
));
2233 return (HTTP_SERVER_ERROR
);
2236 if ((out
= fopen(newfile
, "wb")) == NULL
)
2239 LogMessage(L_ERROR
, "Unable to open config file \"%s\" - %s",
2240 newfile
, strerror(errno
));
2241 return (HTTP_SERVER_ERROR
);
2244 fchmod(fileno(out
), confinfo
.st_mode
);
2245 fchown(fileno(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2248 * Copy from the request to the new config file...
2251 while ((bytes
= fread(buffer
, 1, sizeof(buffer
), in
)) > 0)
2252 if (fwrite(buffer
, 1, bytes
, out
) < bytes
)
2254 LogMessage(L_ERROR
, "Unable to copy to config file \"%s\" - %s",
2255 newfile
, strerror(errno
));
2261 return (HTTP_SERVER_ERROR
);
2265 * Close the files...
2271 LogMessage(L_ERROR
, "Error file closing config file \"%s\" - %s",
2272 newfile
, strerror(errno
));
2276 return (HTTP_SERVER_ERROR
);
2280 * Remove the request file...
2283 unlink(con
->filename
);
2284 con
->filename
[0] = '\0';
2287 * Unlink the old backup, rename the current config file to the backup
2288 * filename, and rename the new config file to the config file name...
2291 if (unlink(oldfile
))
2292 if (errno
!= ENOENT
)
2294 LogMessage(L_ERROR
, "Unable to remove backup config file \"%s\" - %s",
2295 oldfile
, strerror(errno
));
2299 return (HTTP_SERVER_ERROR
);
2302 if (rename(conffile
, oldfile
))
2303 if (errno
!= ENOENT
)
2305 LogMessage(L_ERROR
, "Unable to rename old config file \"%s\" - %s",
2306 conffile
, strerror(errno
));
2310 return (HTTP_SERVER_ERROR
);
2313 if (rename(newfile
, conffile
))
2315 LogMessage(L_ERROR
, "Unable to rename new config file \"%s\" - %s",
2316 newfile
, strerror(errno
));
2318 rename(oldfile
, conffile
);
2321 return (HTTP_SERVER_ERROR
);
2325 * If the cupsd.conf file was updated, set the NeedReload flag...
2328 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf") == 0)
2332 * Return that the file was created successfully...
2335 return (HTTP_CREATED
);
2340 * 'pipe_command()' - Pipe the output of a command to the remote client.
2343 static int /* O - Process ID */
2344 pipe_command(client_t
*con
, /* I - Client connection */
2345 int infile
, /* I - Standard input for command */
2346 int *outfile
, /* O - Standard output for command */
2347 char *command
, /* I - Command to run */
2348 char *options
) /* I - Options for command */
2350 int pid
; /* Process ID */
2351 char *commptr
; /* Command string pointer */
2352 int fd
; /* Looping var */
2353 int fds
[2]; /* Pipe FDs */
2354 int argc
; /* Number of arguments */
2355 int envc
; /* Number of environment variables */
2356 char argbuf
[10240], /* Argument buffer */
2357 *argv
[100], /* Argument strings */
2358 *envp
[100]; /* Environment variables */
2359 char lang
[1024], /* LANG env variable */
2360 content_length
[1024], /* CONTENT_LENGTH env variable */
2361 content_type
[1024], /* CONTENT_TYPE env variable */
2362 ipp_port
[1024], /* Default listen port */
2363 server_port
[1024], /* Default server port */
2364 server_name
[1024], /* Default listen hostname */
2365 remote_host
[1024], /* REMOTE_HOST env variable */
2366 remote_user
[1024], /* REMOTE_USER env variable */
2367 tmpdir
[1024], /* TMPDIR environment variable */
2368 ldpath
[1024], /* LD_LIBRARY_PATH environment variable */
2369 nlspath
[1024], /* NLSPATH environment variable */
2370 datadir
[1024], /* CUPS_DATADIR environment variable */
2371 root
[1024], /* CUPS_SERVERROOT environment variable */
2372 query_string
[10240]; /* QUERY_STRING env variable */
2373 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
2374 sigset_t oldmask
, /* POSIX signal masks */
2376 struct sigaction action
; /* POSIX signal handler */
2377 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
2381 * Copy the command string...
2384 strlcpy(argbuf
, options
, sizeof(argbuf
));
2387 * Parse the string; arguments can be separated by + and are terminated
2393 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
2394 if (*commptr
== ' ' || *commptr
== '+')
2398 while (*commptr
== ' ')
2401 if (*commptr
!= '\0')
2403 argv
[argc
] = commptr
;
2409 else if (*commptr
== '%')
2411 if (commptr
[1] >= '0' && commptr
[1] <= '9')
2412 *commptr
= (commptr
[1] - '0') << 4;
2414 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
2416 if (commptr
[2] >= '0' && commptr
[2] <= '9')
2417 *commptr
|= commptr
[2] - '0';
2419 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
2421 strcpy(commptr
+ 1, commptr
+ 3);
2423 else if (*commptr
== '?')
2428 if (argv
[0][0] == '\0')
2429 argv
[0] = strrchr(command
, '/') + 1;
2432 * Setup the environment variables as needed...
2435 snprintf(lang
, sizeof(lang
), "LANG=%s",
2436 con
->language
? con
->language
->language
: "C");
2438 if (con
->http
.hostaddr
.addr
.sa_family
== AF_INET6
)
2440 sprintf(ipp_port
, "IPP_PORT=%d", ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
2441 sprintf(server_port
, "SERVER_PORT=%d",
2442 ntohs(con
->http
.hostaddr
.ipv6
.sin6_port
));
2445 #endif /* AF_INET6 */
2447 sprintf(ipp_port
, "IPP_PORT=%d", ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
2448 sprintf(server_port
, "SERVER_PORT=%d",
2449 ntohs(con
->http
.hostaddr
.ipv4
.sin_port
));
2452 if (strcmp(con
->http
.hostname
, "localhost") == 0)
2453 strlcpy(server_name
, "SERVER_NAME=localhost", sizeof(server_name
));
2455 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s", ServerName
);
2456 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s", con
->http
.hostname
);
2457 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
2458 snprintf(tmpdir
, sizeof(tmpdir
), "TMPDIR=%s", TempDir
);
2459 snprintf(datadir
, sizeof(datadir
), "CUPS_DATADIR=%s", DataDir
);
2460 snprintf(root
, sizeof(root
), "CUPS_SERVERROOT=%s", ServerRoot
);
2462 if (getenv("LD_LIBRARY_PATH") != NULL
)
2463 snprintf(ldpath
, sizeof(ldpath
), "LD_LIBRARY_PATH=%s",
2464 getenv("LD_LIBRARY_PATH"));
2465 else if (getenv("DYLD_LIBRARY_PATH") != NULL
)
2466 snprintf(ldpath
, sizeof(ldpath
), "DYLD_LIBRARY_PATH=%s",
2467 getenv("DYLD_LIBRARY_PATH"));
2468 else if (getenv("SHLIB_PATH") != NULL
)
2469 snprintf(ldpath
, sizeof(ldpath
), "SHLIB_PATH=%s",
2470 getenv("SHLIB_PATH"));
2474 if (getenv("NLSPATH") != NULL
)
2475 snprintf(nlspath
, sizeof(nlspath
), "NLSPATH=%s", getenv("NLSPATH"));
2479 envp
[0] = "PATH=/bin:/usr/bin";
2480 envp
[1] = "SERVER_SOFTWARE=CUPS/1.2";
2481 envp
[2] = "GATEWAY_INTERFACE=CGI/1.1";
2482 envp
[3] = "SERVER_PROTOCOL=HTTP/1.1";
2484 envp
[5] = server_name
;
2485 envp
[6] = server_port
;
2486 envp
[7] = remote_host
;
2487 envp
[8] = remote_user
;
2497 envp
[envc
++] = ldpath
;
2500 envp
[envc
++] = nlspath
;
2502 if (con
->operation
== HTTP_GET
)
2504 envp
[envc
++] = "REQUEST_METHOD=GET";
2509 * Add GET form variables after ?...
2514 snprintf(query_string
, sizeof(query_string
), "QUERY_STRING=%s", commptr
);
2515 envp
[envc
++] = query_string
;
2520 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->bytes
);
2521 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
2522 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
2524 envp
[envc
++] = "REQUEST_METHOD=POST";
2525 envp
[envc
++] = content_length
;
2526 envp
[envc
++] = content_type
;
2530 * Tell the CGI if we are using encryption...
2533 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
2535 envp
[envc
++] = "HTTPS=ON";
2536 envp
[envc
++] = "CUPS_ENCRYPTION=Always";
2542 * Create a pipe for the output...
2547 LogMessage(L_ERROR
, "Unable to create pipes for CGI %s - %s",
2548 argv
[0], strerror(errno
));
2553 * Block signals before forking...
2559 #elif defined(HAVE_SIGACTION)
2560 sigemptyset(&newmask
);
2561 sigaddset(&newmask
, SIGTERM
);
2562 sigaddset(&newmask
, SIGCHLD
);
2563 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
2564 #endif /* HAVE_SIGSET */
2567 * Then execute the command...
2570 if ((pid
= fork()) == 0)
2573 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
2579 * Running as root, so change to a non-priviledged user...
2590 * Reset group membership to just the main one we belong to.
2596 * Update stdin/stdout/stderr...
2602 if (dup(infile
) < 0)
2607 if (dup(fds
[1]) < 0)
2611 open("/dev/null", O_WRONLY
);
2614 * Close extra file descriptors...
2617 for (fd
= 3; fd
< MaxFDs
; fd
++)
2621 * Change umask to restrict permissions on created files...
2627 * Unblock signals before doing the exec...
2631 sigset(SIGTERM
, SIG_DFL
);
2632 sigset(SIGCHLD
, SIG_DFL
);
2636 #elif defined(HAVE_SIGACTION)
2637 memset(&action
, 0, sizeof(action
));
2639 sigemptyset(&action
.sa_mask
);
2640 action
.sa_handler
= SIG_DFL
;
2642 sigaction(SIGTERM
, &action
, NULL
);
2643 sigaction(SIGCHLD
, &action
, NULL
);
2645 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2647 signal(SIGTERM
, SIG_DFL
);
2648 signal(SIGCHLD
, SIG_DFL
);
2649 #endif /* HAVE_SIGSET */
2653 * Execute the pipe program; if an error occurs, exit with status 1...
2656 execve(command
, argv
, envp
);
2663 * Error - can't fork!
2666 LogMessage(L_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
2676 * Fork successful - return the PID...
2679 AddCert(pid
, con
->username
);
2681 LogMessage(L_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
2690 #elif defined(HAVE_SIGACTION)
2691 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2692 #endif /* HAVE_SIGSET */
2699 * End of "$Id: client.c,v 1.91.2.32 2003/01/13 18:41:42 mike Exp $".