2 * "$Id: client.c,v 1.13 1999/04/22 13:53:05 mike Exp $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-1999 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 * 44145 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 * ReadClient() - Read data from a client.
30 * SendCommand() - Send output from a command via HTTP.
31 * SendError() - Send an error message via HTTP.
32 * SendFile() - Send a file via HTTP.
33 * SendHeader() - Send an HTTP request.
34 * StartListening() - Create all listening sockets...
35 * StopListening() - Close all listening sockets...
36 * WriteClient() - Write data to a client as needed.
37 * check_if_modified() - Decode an "If-Modified-Since" line.
38 * decode_basic_auth() - Decode a Basic authorization string.
39 * get_file() - Get a filename and state info.
40 * pipe_command() - Pipe the output of a command to the remote client.
44 * Include necessary headers...
54 static int check_if_modified(client_t
*con
, struct stat
*filestats
);
55 static void decode_basic_auth(client_t
*con
);
56 static char *get_file(client_t
*con
, struct stat
*filestats
);
57 static int pipe_command(client_t
*con
, int infile
, int *outfile
, char *command
, char *options
);
61 * 'AcceptClient()' - Accept a new client.
65 AcceptClient(listener_t
*lis
) /* I - Listener socket */
67 int i
; /* Looping var */
68 int val
; /* Parameter value */
69 client_t
*con
; /* New client pointer */
70 unsigned address
;/* Address of client */
71 struct hostent
*host
; /* Host entry for address */
74 DEBUG_printf(("AcceptClient(%08x) %d NumClients = %d\n",
75 lis
, lis
->fd
, NumClients
));
78 * Get a pointer to the next available client...
81 con
= Clients
+ NumClients
;
83 memset(con
, 0, sizeof(client_t
));
84 con
->http
.activity
= time(NULL
);
87 * Accept the client and get the remote address...
90 val
= sizeof(struct sockaddr_in
);
92 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
), &val
)) < 0)
94 LogMessage(LOG_ERROR
, "accept() failed - %s.", strerror(errno
));
99 * Get the hostname or format the IP address as needed...
102 address
= ntohl(con
->http
.hostaddr
.sin_addr
.s_addr
);
106 host
= gethostbyaddr((char *)&address
, sizeof(address
), AF_INET
);
108 host
= gethostbyaddr(&address
, sizeof(address
), AF_INET
);
114 sprintf(con
->http
.hostname
, "%d.%d.%d.%d", (address
>> 24) & 255,
115 (address
>> 16) & 255, (address
>> 8) & 255, address
& 255);
117 strncpy(con
->http
.hostname
, host
->h_name
, sizeof(con
->http
.hostname
) - 1);
119 LogMessage(LOG_INFO
, "accept() %d from %s.", con
->http
.fd
, con
->http
.hostname
);
122 * Add the socket to the select() input mask.
125 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
127 DEBUG_printf(("AcceptClient: Adding fd %d to InputSet...\n", con
->http
.fd
));
128 FD_SET(con
->http
.fd
, &InputSet
);
133 * Temporarily suspend accept()'s until we lose a client...
136 if (NumClients
== MAX_CLIENTS
)
137 for (i
= 0; i
< NumListeners
; i
++)
139 DEBUG_printf(("AcceptClient: Removing fd %d from InputSet...\n", Listeners
[i
].fd
));
140 FD_CLR(Listeners
[i
].fd
, &InputSet
);
146 * 'CloseAllClients()' - Close all remote clients immediately.
150 CloseAllClients(void)
152 while (NumClients
> 0)
153 CloseClient(Clients
);
158 * 'CloseClient()' - Close a remote client.
162 CloseClient(client_t
*con
) /* I - Client to close */
164 int i
; /* Looping var */
165 int status
; /* Exit status of pipe command */
168 LogMessage(LOG_INFO
, "CloseClient() %d", con
->http
.fd
);
171 * Close the socket and clear the file from the input set for select()...
174 #if defined(WIN32) || defined(__EMX__)
176 * Microsoft Windows and IBM OS/2 don't have a unified IO system...
179 closesocket(con
->http
.fd
);
186 #endif /* WIN32 || __EMX__ */
188 for (i
= 0; i
< NumListeners
; i
++)
190 DEBUG_printf(("CloseClient: Adding fd %d to InputSet...\n", Listeners
[i
].fd
));
191 FD_SET(Listeners
[i
].fd
, &InputSet
);
194 DEBUG_printf(("CloseClient: Removing fd %d from InputSet...\n", con
->http
.fd
));
195 FD_CLR(con
->http
.fd
, &InputSet
);
196 if (con
->pipe_pid
!= 0)
198 DEBUG_printf(("CloseClient: Removing fd %d from InputSet...\n", con
->file
));
199 FD_CLR(con
->file
, &InputSet
);
202 FD_CLR(con
->http
.fd
, &OutputSet
);
205 * If we have a data file open, close it...
212 kill(con
->pipe_pid
, SIGKILL
);
213 waitpid(con
->pipe_pid
, &status
, WNOHANG
);
221 * Compact the list of clients as necessary...
226 if (con
< (Clients
+ NumClients
))
227 memcpy(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
232 * 'ReadClient()' - Read data from a client.
235 int /* O - 1 on success, 0 on error */
236 ReadClient(client_t
*con
) /* I - Client to read from */
238 char line
[8192], /* Line from client... */
239 operation
[64], /* Operation code from socket */
240 version
[64]; /* HTTP version number string */
241 int major
, minor
; /* HTTP version numbers */
242 http_status_t status
; /* Transfer status */
243 int bytes
; /* Number of bytes to POST */
244 char *filename
; /* Name of file for GET/HEAD */
245 struct stat filestats
; /* File information */
246 mime_type_t
*type
; /* MIME type of file */
247 char command
[1024], /* Command to run */
248 *options
; /* Options/CGI data */
251 status
= HTTP_CONTINUE
;
253 switch (con
->http
.state
)
257 * See if we've received a request line...
260 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
267 * Ignore blank request lines...
274 * Clear other state variables...
277 httpClearFields(HTTP(con
));
279 con
->http
.activity
= time(NULL
);
280 con
->http
.version
= HTTP_1_0
;
281 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
282 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
283 con
->http
.data_remaining
= 0;
284 con
->operation
= HTTP_WAITING
;
288 con
->username
[0] = '\0';
289 con
->password
[0] = '\0';
292 if (con
->language
!= NULL
)
294 cupsLangFree(con
->language
);
295 con
->language
= NULL
;
299 * Grab the request line...
302 switch (sscanf(line
, "%63s%1023s%s", operation
, con
->uri
, version
))
305 SendError(con
, HTTP_BAD_REQUEST
);
309 con
->http
.version
= HTTP_0_9
;
312 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
314 SendError(con
, HTTP_BAD_REQUEST
);
321 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
322 if (con
->http
.version
== HTTP_1_1
)
323 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
325 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
329 SendError(con
, HTTP_NOT_SUPPORTED
);
337 * Process the request...
340 if (strcmp(operation
, "GET") == 0)
341 con
->http
.state
= HTTP_GET
;
342 else if (strcmp(operation
, "PUT") == 0)
343 con
->http
.state
= HTTP_PUT
;
344 else if (strcmp(operation
, "POST") == 0)
345 con
->http
.state
= HTTP_POST
;
346 else if (strcmp(operation
, "DELETE") == 0)
347 con
->http
.state
= HTTP_DELETE
;
348 else if (strcmp(operation
, "TRACE") == 0)
349 con
->http
.state
= HTTP_TRACE
;
350 else if (strcmp(operation
, "CLOSE") == 0)
351 con
->http
.state
= HTTP_CLOSE
;
352 else if (strcmp(operation
, "OPTIONS") == 0)
353 con
->http
.state
= HTTP_OPTIONS
;
354 else if (strcmp(operation
, "HEAD") == 0)
355 con
->http
.state
= HTTP_HEAD
;
358 SendError(con
, HTTP_BAD_REQUEST
);
363 con
->start
= time(NULL
);
364 con
->operation
= con
->http
.state
;
366 LogMessage(LOG_INFO
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
368 con
->http
.version
/ 100, con
->http
.version
% 100);
370 con
->http
.status
= HTTP_OK
;
381 * Parse incoming parameters until the status changes...
384 status
= httpUpdate(HTTP(con
));
386 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
388 SendError(con
, HTTP_BAD_REQUEST
);
396 * Handle new transfers...
399 if (status
== HTTP_OK
)
401 con
->language
= cupsLangGet(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
403 decode_basic_auth(con
);
405 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
406 con
->http
.version
>= HTTP_1_0
)
408 if (!SendError(con
, HTTP_BAD_REQUEST
))
414 else if (strncmp(con
->uri
, "..", 2) == 0)
417 * Protect against malicious users!
420 if (!SendError(con
, HTTP_FORBIDDEN
))
426 else if (con
->uri
[0] != '/')
429 * Don't allow proxying (yet)...
432 if (!SendError(con
, HTTP_METHOD_NOT_ALLOWED
))
438 else if ((status
= IsAuthorized(con
)) != HTTP_OK
)
440 if (!SendError(con
, status
))
446 else switch (con
->http
.state
)
449 if (strncmp(con
->uri
, "/printers", 9) == 0 &&
450 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
456 sprintf(command
, "/ppd/%s", con
->uri
+ 10);
457 strcpy(con
->uri
, command
);
460 if (strncmp(con
->uri
, "/printers", 9) == 0 ||
461 strncmp(con
->uri
, "/classes", 8) == 0 ||
462 strncmp(con
->uri
, "/jobs", 5) == 0)
468 if (strncmp(con
->uri
, "/printers", 9) == 0)
470 sprintf(command
, "%s/cgi-bin/printers.cgi", ServerRoot
);
471 options
= con
->uri
+ 9;
473 else if (strncmp(con
->uri
, "/classes", 8) == 0)
475 sprintf(command
, "%s/cgi-bin/classes.cgi", ServerRoot
);
476 options
= con
->uri
+ 8;
480 sprintf(command
, "%s/cgi-bin/jobs.cgi", ServerRoot
);
481 options
= con
->uri
+ 5;
487 if (!SendCommand(con
, command
, options
))
489 if (!SendError(con
, HTTP_NOT_FOUND
))
496 LogRequest(con
, HTTP_OK
);
498 if (con
->http
.version
<= HTTP_1_0
)
499 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
507 if ((filename
= get_file(con
, &filestats
)) == NULL
)
509 if (!SendError(con
, HTTP_NOT_FOUND
))
515 else if (!check_if_modified(con
, &filestats
))
517 if (!SendError(con
, HTTP_NOT_MODIFIED
))
525 type
= mimeFileType(MimeDatabase
, filename
);
527 strcpy(line
, "text/plain");
529 sprintf(line
, "%s/%s", type
->super
, type
->type
);
531 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
540 case HTTP_POST_RECV
:
542 * See what kind of POST request this is; for IPP requests the
543 * content-type field will be "application/ipp"...
546 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
547 con
->request
= ippNew();
548 else if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/x-www-form-urlencoded") == 0 &&
549 (strncmp(con
->uri
, "/printers", 9) == 0 ||
550 strncmp(con
->uri
, "/classes", 8) == 0 ||
551 strncmp(con
->uri
, "/jobs", 5) == 0))
557 if (strncmp(con
->uri
, "/printers", 9) == 0)
559 sprintf(command
, "%s/cgi-bin/printers", ServerRoot
);
560 options
= con
->uri
+ 9;
562 else if (strncmp(con
->uri
, "/classes", 8) == 0)
564 sprintf(command
, "%s/cgi-bin/classes", ServerRoot
);
565 options
= con
->uri
+ 8;
569 sprintf(command
, "%s/cgi-bin/jobs", ServerRoot
);
570 options
= con
->uri
+ 5;
576 if (!SendCommand(con
, command
, options
))
578 if (!SendError(con
, HTTP_NOT_FOUND
))
585 LogRequest(con
, HTTP_OK
);
587 if (con
->http
.version
<= HTTP_1_0
)
588 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
590 else if (!SendError(con
, HTTP_UNAUTHORIZED
))
600 SendError(con
, HTTP_NOT_IMPLEMENTED
);
607 if (strncmp(con
->uri
, "/printers", 9) == 0 &&
608 strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd") == 0)
614 sprintf(command
, "/ppd/%s", con
->uri
+ 10);
615 strcpy(con
->uri
, command
);
618 if (strncmp(con
->uri
, "/printers/", 10) == 0 ||
619 strncmp(con
->uri
, "/classes/", 9) == 0 ||
620 strncmp(con
->uri
, "/jobs/", 6) == 0)
626 if (!SendHeader(con
, HTTP_OK
, "text/html"))
632 if (httpPrintf(HTTP(con
), "\r\n") < 0)
638 LogRequest(con
, HTTP_OK
);
640 else if ((filename
= get_file(con
, &filestats
)) == NULL
)
642 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
648 LogRequest(con
, HTTP_NOT_FOUND
);
650 else if (!check_if_modified(con
, &filestats
))
652 if (!SendError(con
, HTTP_NOT_MODIFIED
))
658 LogRequest(con
, HTTP_NOT_MODIFIED
);
666 type
= mimeFileType(MimeDatabase
, filename
);
668 strcpy(line
, "text/plain");
670 sprintf(line
, "%s/%s", type
->super
, type
->type
);
672 if (!SendHeader(con
, HTTP_OK
, line
))
678 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
679 httpGetDateString(filestats
.st_mtime
)) < 0)
685 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
686 filestats
.st_size
) < 0)
692 LogRequest(con
, HTTP_OK
);
695 if (send(con
->http
.fd
, "\r\n", 2, 0) < 0)
701 con
->http
.state
= HTTP_WAITING
;
707 * Handle any incoming data...
710 switch (con
->http
.state
)
715 case HTTP_POST_RECV
:
716 LogMessage(LOG_DEBUG
, "ReadClient() %d con->data_encoding = %s con->data_remaining = %d",
718 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
719 con
->http
.data_remaining
);
720 DEBUG_printf(("ReadClient() %d con->data_encoding = %s con->data_remaining = %d\n",
722 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
723 con
->http
.data_remaining
));
725 if (con
->request
!= NULL
)
728 * Grab any request data from the connection...
731 if (ippRead(&(con
->http
), con
->request
) != IPP_DATA
)
734 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
737 * Create a file as needed for the request data...
740 sprintf(con
->filename
, "%s/requests/XXXXXX", ServerRoot
);
741 con
->file
= mkstemp(con
->filename
);
742 /*fchmod(con->file, 0644);*/
744 LogMessage(LOG_INFO
, "ReadClient() %d REQUEST %s", con
->http
.fd
,
749 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
758 if (con
->http
.state
!= HTTP_POST_SEND
)
760 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
769 LogMessage(LOG_DEBUG
, "ReadClient() %d writing %d bytes", bytes
);
771 if (write(con
->file
, line
, bytes
) < bytes
)
775 unlink(con
->filename
);
777 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
786 if (con
->http
.state
== HTTP_POST_SEND
)
795 ProcessIPPRequest(con
);
800 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
811 * 'SendCommand()' - Send output from a command via HTTP.
815 SendCommand(client_t
*con
,
819 con
->pipe_pid
= pipe_command(con
, 0, &(con
->file
), command
, options
);
821 LogMessage(LOG_DEBUG
, "SendCommand() %d command=\"%s\" file=%d pipe_pid=%d",
822 con
->http
.fd
, command
, con
->file
, con
->pipe_pid
);
824 if (con
->pipe_pid
== 0)
827 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
829 DEBUG_printf(("SendCommand: Adding fd %d to InputSet...\n", con
->file
));
830 FD_SET(con
->file
, &InputSet
);
831 FD_SET(con
->http
.fd
, &OutputSet
);
833 if (!SendHeader(con
, HTTP_OK
, NULL
))
836 if (con
->http
.version
== HTTP_1_1
)
838 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
840 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
849 * 'SendError()' - Send an error message via HTTP.
852 int /* O - 1 if successful, 0 otherwise */
853 SendError(client_t
*con
, /* I - Connection */
854 http_status_t code
) /* I - Error code */
856 char message
[1024]; /* Text version of error code */
860 * Put the request in the access_log file...
863 LogRequest(con
, code
);
866 * To work around bugs in some proxies, don't use Keep-Alive for some
870 if (code
>= HTTP_BAD_REQUEST
)
871 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
874 * Send an error message back to the client. If the error code is a
875 * 400 or 500 series, make sure the message contains some text, too!
878 if (!SendHeader(con
, code
, NULL
))
881 if (code
== HTTP_UNAUTHORIZED
)
883 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
887 if (con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
)
889 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
893 if (code
>= HTTP_BAD_REQUEST
)
896 * Send a human-readable error message.
899 sprintf(message
, "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
900 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
901 code
, httpStatus(code
), httpStatus(code
),
902 con
->language
? con
->language
->messages
[code
] : httpStatus(code
));
904 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
906 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n", strlen(message
)) < 0)
908 if (httpPrintf(HTTP(con
), "\r\n") < 0)
910 if (send(con
->http
.fd
, message
, strlen(message
), 0) < 0)
913 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
916 con
->http
.state
= HTTP_WAITING
;
923 * 'SendFile()' - Send a file via HTTP.
927 SendFile(client_t
*con
,
931 struct stat
*filestats
)
933 con
->file
= open(filename
, O_RDONLY
);
935 LogMessage(LOG_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
940 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
944 if (!SendHeader(con
, code
, type
))
947 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
949 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n", filestats
->st_size
) < 0)
951 if (httpPrintf(HTTP(con
), "\r\n") < 0)
954 FD_SET(con
->http
.fd
, &OutputSet
);
961 * 'SendHeader()' - Send an HTTP request.
964 int /* O - 1 on success, 0 on failure */
965 SendHeader(client_t
*con
, /* I - Client to send to */
966 http_status_t code
, /* I - HTTP status code */
967 char *type
) /* I - MIME type of document */
969 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
970 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
972 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
974 if (httpPrintf(HTTP(con
), "Server: CUPS/1.0\r\n") < 0)
976 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
978 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
980 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
983 if (con
->language
!= NULL
)
985 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
986 con
->language
->language
) < 0)
990 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
991 cupsLangEncoding(con
->language
)) < 0)
994 else if (type
!= NULL
)
995 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
1003 * 'StartListening()' - Create all listening sockets...
1007 StartListening(void)
1009 int i
, /* Looping var */
1010 val
; /* Parameter value */
1011 listener_t
*lis
; /* Current listening socket */
1014 #if defined(WIN32) || defined(__EMX__)
1016 * Initialize Windows sockets... This handles loading the DLL, etc. since
1017 * Windows doesn't have built-in support for sockets like UNIX...
1020 WSADATA wsadata
; /* Socket data for application from DLL */
1021 static int initialized
= 0;/* Whether or not we've initialized things */
1028 if (WSAStartup(MAKEWORD(1,1), &wsadata
) != 0)
1033 * Setup a 'broken pipe' signal handler for lost clients.
1036 sigset(SIGPIPE
, SIG_IGN
);
1040 * Setup socket listeners...
1043 for (i
= NumListeners
, lis
= Listeners
; i
> 0; i
--, lis
++)
1045 LogMessage(LOG_INFO
, "StartListening() address=%08x port=%d",
1046 ntohl(lis
->address
.sin_addr
.s_addr
),
1047 ntohs(lis
->address
.sin_port
));
1049 if ((lis
->fd
= socket(AF_INET
, SOCK_STREAM
, PF_UNSPEC
)) == -1)
1051 LogMessage(LOG_ERROR
, "StartListening() Unable to open listen socket - %s.",
1056 fcntl(lis
->fd
, F_SETFD
, fcntl(lis
->fd
, F_GETFD
) | FD_CLOEXEC
);
1059 * Set things up to reuse the local address for this port.
1064 setsockopt(lis
->fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&val
, sizeof(val
));
1066 setsockopt(lis
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
1070 * Bind to the port we found...
1073 if (bind(lis
->fd
, (struct sockaddr
*)&(lis
->address
), sizeof(lis
->address
)) < 0)
1075 LogMessage(LOG_ERROR
, "StartListening() Unable to bind socket - %s.", strerror(errno
));
1080 * Listen for new clients.
1083 if (listen(lis
->fd
, SOMAXCONN
) < 0)
1085 LogMessage(LOG_ERROR
, "StartListening() Unable to listen for clients - %s.",
1091 * Setup the select() input mask to contain the listening socket we have.
1094 DEBUG_printf(("StartListening: Adding fd %d to InputSet...\n", lis
->fd
));
1095 FD_SET(lis
->fd
, &InputSet
);
1098 LogMessage(LOG_INFO
, "StartListening() NumListeners=%d", NumListeners
);
1103 * 'StopListening()' - Close all listening sockets...
1109 int i
; /* Looping var */
1110 listener_t
*lis
; /* Current listening socket */
1113 for (i
= NumListeners
, lis
= Listeners
; i
> 0; i
--, lis
++)
1115 #if defined(WIN32) || defined(__EMX__)
1116 closesocket(lis
->fd
);
1119 #endif /* WIN32 || __EMX__ */
1121 DEBUG_printf(("StopListening: Removing fd %d from InputSet...\n", lis
->fd
));
1122 FD_CLR(lis
->fd
, &InputSet
);
1125 LogMessage(LOG_INFO
, "StopListening()");
1130 * 'WriteClient()' - Write data to a client as needed.
1134 WriteClient(client_t
*con
)
1138 char buf
[HTTP_MAX_BUFFER
];
1141 if (con
->http
.state
!= HTTP_GET_SEND
&&
1142 con
->http
.state
!= HTTP_POST_SEND
)
1145 if (con
->http
.fd
== 0)
1147 printf("ERROR - con = %08x (%d), NumClients = %d\n", con
, con
- Clients
,
1152 if (con
->response
!= NULL
)
1153 bytes
= ippWrite(&(con
->http
), con
->response
) != IPP_DATA
;
1154 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
))) > 0)
1156 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
1162 con
->bytes
+= bytes
;
1167 LogRequest(con
, HTTP_OK
);
1169 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
1171 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
1178 con
->http
.state
= HTTP_WAITING
;
1180 FD_CLR(con
->http
.fd
, &OutputSet
);
1184 DEBUG_printf(("WriteClient: Removing fd %d from InputSet...\n", con
->file
));
1185 FD_CLR(con
->file
, &InputSet
);
1188 kill(con
->pipe_pid
, SIGTERM
);
1195 if (con
->request
!= NULL
)
1197 ippDelete(con
->request
);
1198 con
->request
= NULL
;
1201 if (con
->response
!= NULL
)
1203 ippDelete(con
->response
);
1204 con
->response
= NULL
;
1207 if (!con
->http
.keep_alive
)
1214 LogMessage(LOG_DEBUG
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
1216 con
->http
.activity
= time(NULL
);
1223 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
1226 static int /* O - 1 if modified since */
1227 check_if_modified(client_t
*con
, /* I - Client connection */
1228 struct stat
*filestats
) /* I - File information */
1230 char *ptr
; /* Pointer into field */
1231 time_t date
; /* Time/date value */
1232 int size
; /* Size/length value */
1237 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
1242 LogMessage(LOG_DEBUG
, "check_if_modified() %d If-Modified-Since=\"%s\"",
1245 while (*ptr
!= '\0')
1247 while (isspace(*ptr
) || *ptr
== ';')
1250 if (strncasecmp(ptr
, "length=", 7) == 0)
1255 while (isdigit(*ptr
))
1258 else if (isalpha(*ptr
))
1260 date
= httpGetDateTime(ptr
);
1261 while (*ptr
!= '\0' && *ptr
!= ';')
1266 LogMessage(LOG_DEBUG
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
1267 con
->http
.fd
, size
, filestats
->st_size
, date
, filestats
->st_mtime
);
1269 return ((size
!= filestats
->st_size
&& size
!= 0) ||
1270 (date
< filestats
->st_mtime
&& date
!= 0) ||
1271 (size
== 0 && date
== 0));
1276 * 'decode_basic_auth()' - Decode a Basic authorization string.
1280 decode_basic_auth(client_t
*con
) /* I - Client to decode to */
1282 char *s
, /* Authorization string */
1283 value
[1024]; /* Value string */
1287 * Decode the string and pull the username and password out...
1290 s
= con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
];
1291 if (strncmp(s
, "Basic", 5) != 0)
1298 httpDecode64(value
, s
);
1300 LogMessage(LOG_DEBUG
, "decode_basic_auth() %d Authorization=\"%s\"",
1301 con
->http
.fd
, value
);
1303 sscanf(value
, "%[^:]:%[^\n]", con
->username
, con
->password
);
1308 * 'get_file()' - Get a filename and state info.
1311 static char * /* O - Real filename */
1312 get_file(client_t
*con
, /* I - Client connection */
1313 struct stat
*filestats
)/* O - File information */
1315 int status
; /* Status of filesystem calls */
1316 char *params
; /* Pointer to parameters in URI */
1317 static char filename
[1024]; /* Filename buffer */
1321 * Need to add DocumentRoot global...
1324 if (strncmp(con
->uri
, "/ppd/", 5) == 0)
1325 sprintf(filename
, "%s%s", ServerRoot
, con
->uri
);
1326 else if (con
->language
!= NULL
)
1327 sprintf(filename
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
1330 sprintf(filename
, "%s%s", DocumentRoot
, con
->uri
);
1332 if ((params
= strchr(filename
, '?')) != NULL
)
1336 * Grab the status for this language; if there isn't a language-specific file
1337 * then fallback to the default one...
1340 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
1343 * Drop the language prefix and try the current directory...
1346 if (strncmp(con
->uri
, "/ppd/", 5) != 0)
1348 sprintf(filename
, "%s%s", DocumentRoot
, con
->uri
);
1350 status
= stat(filename
, filestats
);
1355 * If we're found a directory, get the index.html file instead...
1358 if (!status
&& S_ISDIR(filestats
->st_mode
))
1360 if (filename
[strlen(filename
) - 1] == '/')
1361 strcat(filename
, "index.html");
1363 strcat(filename
, "/index.html");
1365 status
= stat(filename
, filestats
);
1368 LogMessage(LOG_DEBUG
, "get_filename() %d filename=%s size=%d",
1369 con
->http
.fd
, filename
, filestats
->st_size
);
1379 * 'pipe_command()' - Pipe the output of a command to the remote client.
1382 static int /* O - Process ID */
1383 pipe_command(client_t
*con
, /* I - Client connection */
1384 int infile
, /* I - Standard input for command */
1385 int *outfile
, /* O - Standard output for command */
1386 char *command
, /* I - Command to run */
1387 char *options
) /* I - Options for command */
1389 int pid
; /* Process ID */
1390 char *commptr
; /* Command string pointer */
1391 int fds
[2]; /* Pipe FDs */
1392 int argc
; /* Number of arguments */
1393 char argbuf
[1024], /* Argument buffer */
1394 *argv
[100], /* Argument strings */
1395 *envp
[100]; /* Environment variables */
1396 char hostname
[1024]; /* Hostname string */
1397 static char lang
[1024]; /* LANG env variable */
1398 static char content_length
[1024]; /* CONTENT_LENGTH env variable */
1399 static char content_type
[1024]; /* CONTENT_TYPE env variable */
1400 static char server_port
[1024]; /* Default listen port */
1401 static char server_name
[1024]; /* Default listen hostname */
1402 static char remote_host
[1024]; /* REMOTE_HOST env variable */
1403 static char remote_user
[1024]; /* REMOTE_HOST env variable */
1407 * Copy the command string...
1410 strncpy(argbuf
, options
, sizeof(argbuf
) - 1);
1411 argbuf
[sizeof(argbuf
) - 1] = '\0';
1414 * Parse the string; arguments can be separated by spaces or by ? or +...
1419 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
1420 if (*commptr
== ' ' || *commptr
== '?' || *commptr
== '+')
1424 while (*commptr
== ' ')
1427 if (*commptr
!= '\0')
1429 argv
[argc
] = commptr
;
1435 else if (*commptr
== '%')
1437 if (commptr
[1] >= '0' && commptr
[1] <= '9')
1438 *commptr
= (commptr
[1] - '0') << 4;
1440 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
1442 if (commptr
[2] >= '0' && commptr
[2] <= '9')
1443 *commptr
|= commptr
[2] - '0';
1445 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
1447 strcpy(commptr
+ 1, commptr
+ 3);
1452 if (argv
[0][0] == '\0')
1453 argv
[0] = strrchr(command
, '/') + 1;
1456 * Setup the environment variables as needed...
1459 gethostname(hostname
, sizeof(hostname
) - 1);
1461 sprintf(lang
, "LANG=%s", con
->language
? con
->language
->language
: "C");
1462 sprintf(server_port
, "SERVER_PORT=%d", ntohs(con
->http
.hostaddr
.sin_port
));
1463 sprintf(server_name
, "SERVER_NAME=%s", hostname
);
1464 sprintf(remote_host
, "REMOTE_HOST=%s", con
->http
.hostname
);
1465 sprintf(remote_user
, "REMOTE_USER=%s", con
->username
);
1467 envp
[0] = "PATH=/bin:/usr/bin";
1468 envp
[1] = "SERVER_SOFTWARE=CUPS/1.0";
1469 envp
[2] = "GATEWAY_INTERFACE=CGI/1.1";
1470 envp
[3] = "SERVER_PROTOCOL=HTTP/1.1";
1471 envp
[4] = server_name
;
1472 envp
[5] = server_port
;
1473 envp
[6] = remote_host
;
1474 envp
[7] = remote_user
;
1478 if (con
->operation
== HTTP_GET
)
1480 envp
[10] = "REQUEST_METHOD=GET";
1485 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->http
.data_remaining
);
1486 sprintf(content_type
, "CONTENT_TYPE=%s",
1487 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1489 envp
[10] = "REQUEST_METHOD=POST";
1490 envp
[11] = content_length
;
1491 envp
[12] = content_type
;
1496 * Create a pipe for the output...
1503 * Then execute the pipe command...
1506 if ((pid
= fork()) == 0)
1509 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
1528 * Execute the pipe program; if an error occurs, exit with status 1...
1531 execve(command
, argv
, envp
);
1532 perror("execve failed");
1539 * Error - can't fork!
1549 * Fork successful - return the PID...
1561 * End of "$Id: client.c,v 1.13 1999/04/22 13:53:05 mike Exp $".