2 * "$Id: client.c,v 1.9 1999/04/16 20:47:47 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.
41 * sigpipe_handler() - Handle 'broken pipe' signals from lost network
46 * Include necessary headers...
56 static int check_if_modified(client_t
*con
, struct stat
*filestats
);
57 static void decode_basic_auth(client_t
*con
);
58 static char *get_file(client_t
*con
, struct stat
*filestats
);
59 static int pipe_command(client_t
*con
, int infile
, int *outfile
, char *command
, char *options
);
60 static void sigpipe_handler(int sig
);
64 * 'AcceptClient()' - Accept a new client.
68 AcceptClient(listener_t
*lis
) /* I - Listener socket */
70 int i
; /* Looping var */
71 int val
; /* Parameter value */
72 client_t
*con
; /* New client pointer */
73 unsigned address
;/* Address of client */
74 struct hostent
*host
; /* Host entry for address */
77 DEBUG_printf(("AcceptClient(%08x) %d NumClients = %d\n",
78 lis
, lis
->fd
, NumClients
));
81 * Get a pointer to the next available client...
84 con
= Clients
+ NumClients
;
86 memset(con
, 0, sizeof(client_t
));
87 con
->http
.activity
= time(NULL
);
90 * Accept the client and get the remote address...
93 val
= sizeof(struct sockaddr_in
);
95 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)&(con
->http
.hostaddr
), &val
)) < 0)
97 LogMessage(LOG_ERROR
, "accept() failed - %s.", strerror(errno
));
102 * Get the hostname or format the IP address as needed...
105 address
= ntohl(con
->http
.hostaddr
.sin_addr
.s_addr
);
108 host
= gethostbyaddr(&address
, sizeof(address
), AF_INET
);
113 sprintf(con
->http
.hostname
, "%d.%d.%d.%d", (address
>> 24) & 255,
114 (address
>> 16) & 255, (address
>> 8) & 255, address
& 255);
116 strncpy(con
->http
.hostname
, host
->h_name
, sizeof(con
->http
.hostname
) - 1);
118 LogMessage(LOG_INFO
, "accept() %d from %s.", con
->http
.fd
, con
->http
.hostname
);
121 * Add the socket to the select() input mask.
124 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
126 DEBUG_printf(("AcceptClient: Adding fd %d to InputSet...\n", con
->http
.fd
));
127 FD_SET(con
->http
.fd
, &InputSet
);
132 * Temporarily suspend accept()'s until we lose a client...
135 if (NumClients
== MAX_CLIENTS
)
136 for (i
= 0; i
< NumListeners
; i
++)
138 DEBUG_printf(("AcceptClient: Removing fd %d from InputSet...\n", Listeners
[i
].fd
));
139 FD_CLR(Listeners
[i
].fd
, &InputSet
);
145 * 'CloseAllClients()' - Close all remote clients immediately.
149 CloseAllClients(void)
151 while (NumClients
> 0)
152 CloseClient(Clients
);
157 * 'CloseClient()' - Close a remote client.
161 CloseClient(client_t
*con
) /* I - Client to close */
163 int i
; /* Looping var */
164 int status
; /* Exit status of pipe command */
167 LogMessage(LOG_INFO
, "CloseClient() %d", con
->http
.fd
);
170 * Close the socket and clear the file from the input set for select()...
173 #if defined(WIN32) || defined(__EMX__)
175 * Microsoft Windows and IBM OS/2 don't have a unified IO system...
178 closesocket(con
->http
.fd
);
185 #endif /* WIN32 || __EMX__ */
187 for (i
= 0; i
< NumListeners
; i
++)
189 DEBUG_printf(("CloseClient: Adding fd %d to InputSet...\n", Listeners
[i
].fd
));
190 FD_SET(Listeners
[i
].fd
, &InputSet
);
193 DEBUG_printf(("CloseClient: Removing fd %d from InputSet...\n", con
->http
.fd
));
194 FD_CLR(con
->http
.fd
, &InputSet
);
195 if (con
->pipe_pid
!= 0)
197 DEBUG_printf(("CloseClient: Removing fd %d from InputSet...\n", con
->file
));
198 FD_CLR(con
->file
, &InputSet
);
201 FD_CLR(con
->http
.fd
, &OutputSet
);
204 * If we have a data file open, close it...
211 kill(con
->pipe_pid
, SIGKILL
);
212 waitpid(con
->pipe_pid
, &status
, WNOHANG
);
220 * Compact the list of clients as necessary...
225 if (con
< (Clients
+ NumClients
))
226 memcpy(con
, con
+ 1, (Clients
+ NumClients
- con
) * sizeof(client_t
));
231 * 'ReadClient()' - Read data from a client.
234 int /* O - 1 on success, 0 on error */
235 ReadClient(client_t
*con
) /* I - Client to read from */
237 char line
[8192], /* Line from client... */
238 operation
[64], /* Operation code from socket */
239 version
[64]; /* HTTP version number string */
240 int major
, minor
; /* HTTP version numbers */
241 http_status_t status
; /* Transfer status */
242 int bytes
; /* Number of bytes to POST */
243 char *filename
; /* Name of file for GET/HEAD */
244 struct stat filestats
; /* File information */
245 mime_type_t
*type
; /* MIME type of file */
246 char command
[1024], /* Command to run */
247 *options
; /* Options/CGI data */
250 status
= HTTP_CONTINUE
;
252 switch (con
->http
.state
)
256 * See if we've received a request line...
259 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
266 * Ignore blank request lines...
273 * Clear other state variables...
276 httpClearFields(HTTP(con
));
278 con
->http
.activity
= time(NULL
);
279 con
->http
.version
= HTTP_1_0
;
280 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
281 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
282 con
->http
.data_remaining
= 0;
283 con
->operation
= HTTP_WAITING
;
287 con
->username
[0] = '\0';
288 con
->password
[0] = '\0';
291 if (con
->language
!= NULL
)
293 cupsLangFree(con
->language
);
294 con
->language
= NULL
;
298 * Grab the request line...
301 switch (sscanf(line
, "%63s%1023s%s", operation
, con
->uri
, version
))
304 SendError(con
, HTTP_BAD_REQUEST
);
308 con
->http
.version
= HTTP_0_9
;
311 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
313 SendError(con
, HTTP_BAD_REQUEST
);
320 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
321 if (con
->http
.version
== HTTP_1_1
)
322 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
324 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
328 SendError(con
, HTTP_NOT_SUPPORTED
);
336 * Process the request...
339 if (strcmp(operation
, "GET") == 0)
340 con
->http
.state
= HTTP_GET
;
341 else if (strcmp(operation
, "PUT") == 0)
342 con
->http
.state
= HTTP_PUT
;
343 else if (strcmp(operation
, "POST") == 0)
344 con
->http
.state
= HTTP_POST
;
345 else if (strcmp(operation
, "DELETE") == 0)
346 con
->http
.state
= HTTP_DELETE
;
347 else if (strcmp(operation
, "TRACE") == 0)
348 con
->http
.state
= HTTP_TRACE
;
349 else if (strcmp(operation
, "CLOSE") == 0)
350 con
->http
.state
= HTTP_CLOSE
;
351 else if (strcmp(operation
, "OPTIONS") == 0)
352 con
->http
.state
= HTTP_OPTIONS
;
353 else if (strcmp(operation
, "HEAD") == 0)
354 con
->http
.state
= HTTP_HEAD
;
357 SendError(con
, HTTP_BAD_REQUEST
);
362 con
->start
= time(NULL
);
363 con
->operation
= con
->http
.state
;
365 LogMessage(LOG_INFO
, "ReadClient() %d %s %s HTTP/%d.%d", con
->http
.fd
,
367 con
->http
.version
/ 100, con
->http
.version
% 100);
369 con
->http
.status
= HTTP_OK
;
380 * Parse incoming parameters until the status changes...
383 status
= httpUpdate(HTTP(con
));
385 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
387 SendError(con
, HTTP_BAD_REQUEST
);
395 * Handle new transfers...
398 if (status
== HTTP_OK
)
400 con
->language
= cupsLangGet(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
402 decode_basic_auth(con
);
404 if (con
->http
.fields
[HTTP_FIELD_HOST
][0] == '\0' &&
405 con
->http
.version
>= HTTP_1_0
)
407 if (!SendError(con
, HTTP_BAD_REQUEST
))
413 else if (strncmp(con
->uri
, "..", 2) == 0)
416 * Protect against malicious users!
419 if (!SendError(con
, HTTP_FORBIDDEN
))
425 else if (con
->uri
[0] != '/')
428 * Don't allow proxying (yet)...
431 if (!SendError(con
, HTTP_METHOD_NOT_ALLOWED
))
437 else if ((status
= IsAuthorized(con
)) != HTTP_OK
)
439 if (!SendError(con
, status
))
445 else switch (con
->http
.state
)
448 if (strncmp(con
->uri
, "/printers", 9) == 0 ||
449 strncmp(con
->uri
, "/classes", 8) == 0 ||
450 strncmp(con
->uri
, "/jobs", 5) == 0)
456 if (strncmp(con
->uri
, "/printers", 9) == 0)
458 sprintf(command
, "%s/cgi-bin/printers", ServerRoot
);
459 options
= con
->uri
+ 9;
461 else if (strncmp(con
->uri
, "/classes", 8) == 0)
463 sprintf(command
, "%s/cgi-bin/classes", ServerRoot
);
464 options
= con
->uri
+ 8;
468 sprintf(command
, "%s/cgi-bin/jobs", ServerRoot
);
469 options
= con
->uri
+ 5;
475 if (!SendCommand(con
, command
, options
))
477 if (!SendError(con
, HTTP_NOT_FOUND
))
484 LogRequest(con
, HTTP_OK
);
486 if (con
->http
.version
<= HTTP_1_0
)
487 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
495 if ((filename
= get_file(con
, &filestats
)) == NULL
)
497 if (!SendError(con
, HTTP_NOT_FOUND
))
503 else if (!check_if_modified(con
, &filestats
))
505 if (!SendError(con
, HTTP_NOT_MODIFIED
))
513 type
= mimeFileType(MimeDatabase
, filename
);
515 strcpy(line
, "text/plain");
517 sprintf(line
, "%s/%s", type
->super
, type
->type
);
519 if (!SendFile(con
, HTTP_OK
, filename
, line
, &filestats
))
528 case HTTP_POST_RECV
:
530 * See what kind of POST request this is; for IPP requests the
531 * content-type field will be "application/ipp"...
534 httpGetLength(&(con
->http
));
536 if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0)
537 con
->request
= ippNew();
538 else if (strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "application/ipp") == 0 &&
539 (strncmp(con
->uri
, "/printers", 9) == 0 ||
540 strncmp(con
->uri
, "/classes", 8) == 0 ||
541 strncmp(con
->uri
, "/jobs", 5) == 0))
547 if (strncmp(con
->uri
, "/printers", 9) == 0)
549 sprintf(command
, "%s/cgi-bin/printers", ServerRoot
);
550 options
= con
->uri
+ 9;
552 else if (strncmp(con
->uri
, "/classes", 8) == 0)
554 sprintf(command
, "%s/cgi-bin/classes", ServerRoot
);
555 options
= con
->uri
+ 8;
559 sprintf(command
, "%s/cgi-bin/jobs", ServerRoot
);
560 options
= con
->uri
+ 5;
566 if (!SendCommand(con
, command
, options
))
568 if (!SendError(con
, HTTP_NOT_FOUND
))
575 LogRequest(con
, HTTP_OK
);
577 if (con
->http
.version
<= HTTP_1_0
)
578 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
580 else if (!SendError(con
, HTTP_UNAUTHORIZED
))
590 SendError(con
, HTTP_NOT_IMPLEMENTED
);
597 if (strncmp(con
->uri
, "/printers/", 10) == 0 ||
598 strncmp(con
->uri
, "/classes/", 9) == 0 ||
599 strncmp(con
->uri
, "/jobs/", 6) == 0)
605 if (!SendHeader(con
, HTTP_OK
, "text/html"))
611 if (httpPrintf(HTTP(con
), "\r\n") < 0)
617 LogRequest(con
, HTTP_OK
);
619 else if ((filename
= get_file(con
, &filestats
)) == NULL
)
621 if (!SendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
627 LogRequest(con
, HTTP_NOT_FOUND
);
629 else if (!check_if_modified(con
, &filestats
))
631 if (!SendError(con
, HTTP_NOT_MODIFIED
))
637 LogRequest(con
, HTTP_NOT_MODIFIED
);
645 type
= mimeFileType(MimeDatabase
, filename
);
647 strcpy(line
, "text/plain");
649 sprintf(line
, "%s/%s", type
->super
, type
->type
);
651 if (!SendHeader(con
, HTTP_OK
, line
))
657 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
658 httpGetDateString(filestats
.st_mtime
)) < 0)
664 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
665 filestats
.st_size
) < 0)
671 LogRequest(con
, HTTP_OK
);
674 if (send(con
->http
.fd
, "\r\n", 2, 0) < 0)
680 con
->http
.state
= HTTP_WAITING
;
686 * Handle any incoming data...
689 switch (con
->http
.state
)
694 case HTTP_POST_RECV
:
695 LogMessage(LOG_DEBUG
, "ReadClient() %d con->data_encoding = %s con->data_remaining = %d",
697 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
698 con
->http
.data_remaining
);
699 DEBUG_printf(("ReadClient() %d con->data_encoding = %s con->data_remaining = %d\n",
701 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
? "chunked" : "length",
702 con
->http
.data_remaining
));
704 if (con
->request
!= NULL
)
707 * Grab any request data from the connection...
710 if (ippRead(&(con
->http
), con
->request
) != IPP_DATA
)
713 if (con
->file
== 0 && con
->http
.state
!= HTTP_POST_SEND
)
716 * Create a file as needed for the request data...
719 sprintf(con
->filename
, "%s/requests/XXXXXX", ServerRoot
);
720 con
->file
= mkstemp(con
->filename
);
721 /*fchmod(con->file, 0644);*/
723 LogMessage(LOG_INFO
, "ReadClient() %d REQUEST %s", con
->http
.fd
,
728 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
737 if (con
->http
.state
!= HTTP_POST_SEND
)
739 if ((bytes
= httpRead(HTTP(con
), line
, sizeof(line
))) < 0)
748 LogMessage(LOG_DEBUG
, "ReadClient() %d writing %d bytes", bytes
);
750 if (write(con
->file
, line
, bytes
) < bytes
)
754 unlink(con
->filename
);
756 if (!SendError(con
, HTTP_REQUEST_TOO_LARGE
))
765 if (con
->http
.state
== HTTP_POST_SEND
)
774 ProcessIPPRequest(con
);
779 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
790 * 'SendCommand()' - Send output from a command via HTTP.
794 SendCommand(client_t
*con
,
798 con
->pipe_pid
= pipe_command(con
, 0, &(con
->file
), command
, options
);
800 LogMessage(LOG_DEBUG
, "SendCommand() %d command=\"%s\" file=%d pipe_pid=%d",
801 con
->http
.fd
, command
, con
->file
, con
->pipe_pid
);
803 if (con
->pipe_pid
== 0)
806 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
808 DEBUG_printf(("SendCommand: Adding fd %d to InputSet...\n", con
->file
));
809 FD_SET(con
->file
, &InputSet
);
810 FD_SET(con
->http
.fd
, &OutputSet
);
812 if (!SendHeader(con
, HTTP_OK
, "text/html"))
815 if (con
->http
.version
== HTTP_1_1
)
817 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
819 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
823 if (httpPrintf(HTTP(con
), "\r\n") < 0)
831 * 'SendError()' - Send an error message via HTTP.
834 int /* O - 1 if successful, 0 otherwise */
835 SendError(client_t
*con
, /* I - Connection */
836 http_status_t code
) /* I - Error code */
838 char message
[1024]; /* Text version of error code */
842 * Put the request in the access_log file...
845 LogRequest(con
, code
);
848 * To work around bugs in some proxies, don't use Keep-Alive for some
852 if (code
>= HTTP_BAD_REQUEST
)
853 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
856 * Send an error message back to the client. If the error code is a
857 * 400 or 500 series, make sure the message contains some text, too!
860 if (!SendHeader(con
, code
, NULL
))
863 if (code
== HTTP_UNAUTHORIZED
)
865 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
869 if (con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
)
871 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
875 if (code
>= HTTP_BAD_REQUEST
)
878 * Send a human-readable error message.
881 sprintf(message
, "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>"
882 "<BODY><H1>%s</H1>%s</BODY></HTML>\n",
883 code
, httpStatus(code
), httpStatus(code
),
884 con
->language
? (char *)con
->language
->messages
[code
] : httpStatus(code
));
886 if (httpPrintf(HTTP(con
), "Content-Type: text/html\r\n") < 0)
888 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n", strlen(message
)) < 0)
890 if (httpPrintf(HTTP(con
), "\r\n") < 0)
892 if (send(con
->http
.fd
, message
, strlen(message
), 0) < 0)
895 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
898 con
->http
.state
= HTTP_WAITING
;
905 * 'SendFile()' - Send a file via HTTP.
909 SendFile(client_t
*con
,
913 struct stat
*filestats
)
915 con
->file
= open(filename
, O_RDONLY
);
917 LogMessage(LOG_DEBUG
, "SendFile() %d file=%d", con
->http
.fd
, con
->file
);
922 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
926 if (!SendHeader(con
, code
, type
))
929 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n", httpGetDateString(filestats
->st_mtime
)) < 0)
931 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n", filestats
->st_size
) < 0)
933 if (httpPrintf(HTTP(con
), "\r\n") < 0)
936 FD_SET(con
->http
.fd
, &OutputSet
);
943 * 'SendHeader()' - Send an HTTP request.
946 int /* O - 1 on success, 0 on failure */
947 SendHeader(client_t
*con
, /* I - Client to send to */
948 http_status_t code
, /* I - HTTP status code */
949 char *type
) /* I - MIME type of document */
951 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
952 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
954 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
956 if (httpPrintf(HTTP(con
), "Server: CUPS/1.0\r\n") < 0)
958 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
960 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
962 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n", KeepAliveTimeout
) < 0)
965 if (con
->language
!= NULL
)
967 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
968 con
->language
->language
) < 0)
972 if (httpPrintf(HTTP(con
), "Content-Type: %s; charset=%s\r\n", type
,
973 cupsLangEncoding(con
->language
)) < 0)
976 else if (type
!= NULL
)
977 if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
985 * 'StartListening()' - Create all listening sockets...
991 int i
, /* Looping var */
992 val
; /* Parameter value */
993 listener_t
*lis
; /* Current listening socket */
996 #if defined(WIN32) || defined(__EMX__)
998 * Initialize Windows sockets... This handles loading the DLL, etc. since
999 * Windows doesn't have built-in support for sockets like UNIX...
1002 WSADATA wsadata
; /* Socket data for application from DLL */
1003 static int initialized
= 0;/* Whether or not we've initialized things */
1010 if (WSAStartup(MAKEWORD(1,1), &wsadata
) != 0)
1015 * Setup a 'broken pipe' signal handler for lost clients.
1018 sigset(SIGPIPE
, sigpipe_handler
);
1022 * Setup socket listeners...
1025 for (i
= NumListeners
, lis
= Listeners
; i
> 0; i
--, lis
++)
1027 LogMessage(LOG_INFO
, "StartListening() address=%08x port=%d",
1028 ntohl(lis
->address
.sin_addr
.s_addr
),
1029 ntohs(lis
->address
.sin_port
));
1031 if ((lis
->fd
= socket(AF_INET
, SOCK_STREAM
, PF_UNSPEC
)) == -1)
1033 LogMessage(LOG_ERROR
, "StartListening() Unable to open listen socket - %s.",
1038 fcntl(lis
->fd
, F_SETFD
, fcntl(lis
->fd
, F_GETFD
) | FD_CLOEXEC
);
1041 * Set things up to reuse the local address for this port.
1045 setsockopt(lis
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
1048 * Bind to the port we found...
1051 if (bind(lis
->fd
, (struct sockaddr
*)&(lis
->address
), sizeof(lis
->address
)) < 0)
1053 LogMessage(LOG_ERROR
, "StartListening() Unable to bind socket - %s.", strerror(errno
));
1058 * Listen for new clients.
1061 if (listen(lis
->fd
, SOMAXCONN
) < 0)
1063 LogMessage(LOG_ERROR
, "StartListening() Unable to listen for clients - %s.",
1069 * Setup the select() input mask to contain the listening socket we have.
1072 DEBUG_printf(("StartListening: Adding fd %d to InputSet...\n", lis
->fd
));
1073 FD_SET(lis
->fd
, &InputSet
);
1076 LogMessage(LOG_INFO
, "StartListening() NumListeners=%d", NumListeners
);
1081 * 'StopListening()' - Close all listening sockets...
1087 int i
; /* Looping var */
1088 listener_t
*lis
; /* Current listening socket */
1091 for (i
= NumListeners
, lis
= Listeners
; i
> 0; i
--, lis
++)
1093 #if defined(WIN32) || defined(__EMX__)
1094 closesocket(lis
->fd
);
1097 #endif /* WIN32 || __EMX__ */
1099 DEBUG_printf(("StopListening: Removing fd %d from InputSet...\n", lis
->fd
));
1100 FD_CLR(lis
->fd
, &InputSet
);
1103 LogMessage(LOG_INFO
, "StopListening()");
1108 * 'WriteClient()' - Write data to a client as needed.
1112 WriteClient(client_t
*con
)
1116 char buf
[HTTP_MAX_BUFFER
];
1119 if (con
->http
.state
!= HTTP_GET_SEND
&&
1120 con
->http
.state
!= HTTP_POST_SEND
)
1123 if (con
->http
.fd
== 0)
1125 printf("ERROR - con = %08x (%d), NumClients = %d\n", con
, con
- Clients
,
1130 if (con
->response
!= NULL
)
1131 bytes
= ippWrite(&(con
->http
), con
->response
) != IPP_DATA
;
1132 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
))) > 0)
1134 if (httpWrite(HTTP(con
), buf
, bytes
) < 0)
1140 con
->bytes
+= bytes
;
1145 LogRequest(con
, HTTP_OK
);
1147 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
1149 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
1156 FD_CLR(con
->http
.fd
, &OutputSet
);
1160 DEBUG_printf(("WriteClient: Removing fd %d from InputSet...\n", con
->file
));
1161 FD_CLR(con
->file
, &InputSet
);
1165 kill(con
->pipe_pid
, SIGKILL
);
1166 waitpid(con
->pipe_pid
, &status
, WNOHANG
);
1173 if (!con
->http
.keep_alive
)
1179 con
->http
.state
= HTTP_WAITING
;
1183 if (con
->request
!= NULL
)
1185 ippDelete(con
->request
);
1186 con
->request
= NULL
;
1189 if (con
->response
!= NULL
)
1191 ippDelete(con
->response
);
1192 con
->response
= NULL
;
1196 LogMessage(LOG_DEBUG
, "WriteClient() %d %d bytes", con
->http
.fd
, bytes
);
1198 con
->http
.activity
= time(NULL
);
1205 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
1208 static int /* O - 1 if modified since */
1209 check_if_modified(client_t
*con
, /* I - Client connection */
1210 struct stat
*filestats
) /* I - File information */
1212 char *ptr
; /* Pointer into field */
1213 time_t date
; /* Time/date value */
1214 int size
; /* Size/length value */
1219 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
1224 LogMessage(LOG_DEBUG
, "check_if_modified() %d If-Modified-Since=\"%s\"",
1227 while (*ptr
!= '\0')
1229 while (isspace(*ptr
) || *ptr
== ';')
1232 if (strncasecmp(ptr
, "length=", 7) == 0)
1237 while (isdigit(*ptr
))
1240 else if (isalpha(*ptr
))
1242 date
= httpGetDateTime(ptr
);
1243 while (*ptr
!= '\0' && *ptr
!= ';')
1248 LogMessage(LOG_DEBUG
, "check_if_modified() %d sizes=%d,%d dates=%d,%d",
1249 con
->http
.fd
, size
, filestats
->st_size
, date
, filestats
->st_mtime
);
1251 return ((size
!= filestats
->st_size
&& size
!= 0) ||
1252 (date
< filestats
->st_mtime
&& date
!= 0) ||
1253 (size
== 0 && date
== 0));
1258 * 'decode_basic_auth()' - Decode a Basic authorization string.
1262 decode_basic_auth(client_t
*con
) /* I - Client to decode to */
1264 char value
[1024]; /* Value string */
1268 * Decode the string and pull the username and password out...
1271 httpDecode64(value
, con
->http
.fields
[HTTP_FIELD_AUTHORIZATION
]);
1273 LogMessage(LOG_DEBUG
, "decode_basic_auth() %d Authorization=\"%s\"",
1274 con
->http
.fd
, value
);
1276 sscanf(value
, "%[^:]:%[^\n]", con
->username
, con
->password
);
1281 * 'get_file()' - Get a filename and state info.
1284 static char * /* O - Real filename */
1285 get_file(client_t
*con
, /* I - Client connection */
1286 struct stat
*filestats
)/* O - File information */
1288 int status
; /* Status of filesystem calls */
1289 char *params
; /* Pointer to parameters in URI */
1290 static char filename
[1024]; /* Filename buffer */
1294 * Need to add DocumentRoot global...
1297 if (con
->language
!= NULL
)
1298 sprintf(filename
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
1301 sprintf(filename
, "%s%s", DocumentRoot
, con
->uri
);
1303 if ((params
= strchr(filename
, '?')) != NULL
)
1307 * Grab the status for this language; if there isn't a language-specific file
1308 * then fallback to the default one...
1311 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
1314 * Drop the language prefix and try the current directory...
1317 sprintf(filename
, "%s%s", DocumentRoot
, con
->uri
);
1319 status
= stat(filename
, filestats
);
1323 * If we're found a directory, get the index.html file instead...
1326 if (!status
&& S_ISDIR(filestats
->st_mode
))
1328 if (filename
[strlen(filename
) - 1] == '/')
1329 strcat(filename
, "index.html");
1331 strcat(filename
, "/index.html");
1333 status
= stat(filename
, filestats
);
1336 LogMessage(LOG_DEBUG
, "get_filename() %d filename=%s size=%d",
1337 con
->http
.fd
, filename
, filestats
->st_size
);
1347 * 'pipe_command()' - Pipe the output of a command to the remote client.
1350 static int /* O - Process ID */
1351 pipe_command(client_t
*con
, /* I - Client connection */
1352 int infile
, /* I - Standard input for command */
1353 int *outfile
, /* O - Standard output for command */
1354 char *command
, /* I - Command to run */
1355 char *options
) /* I - Options for command */
1357 int pid
; /* Process ID */
1358 char *commptr
; /* Command string pointer */
1359 int fds
[2]; /* Pipe FDs */
1360 int argc
; /* Number of arguments */
1361 char argbuf
[1024], /* Argument buffer */
1362 *argv
[100], /* Argument strings */
1363 *envp
[100]; /* Environment variables */
1364 static char lang
[1024]; /* LANG env variable */
1365 static char content_length
[1024]; /* CONTENT_LENGTH env variable */
1366 static char content_type
[1024]; /* CONTENT_TYPE env variable */
1367 static char server_port
[1024]; /* Default listen port */
1368 static char remote_host
[1024]; /* REMOTE_HOST env variable */
1369 static char remote_user
[1024]; /* REMOTE_HOST env variable */
1373 * Copy the command string...
1376 strncpy(argbuf
, options
, sizeof(argbuf
) - 1);
1377 argbuf
[sizeof(argbuf
) - 1] = '\0';
1380 * Parse the string; arguments can be separated by spaces or by ? or +...
1385 for (commptr
= argbuf
, argc
= 1; *commptr
!= '\0' && argc
< 99; commptr
++)
1386 if (*commptr
== ' ' || *commptr
== '?' || *commptr
== '+')
1390 while (*commptr
== ' ')
1393 if (*commptr
!= '\0')
1395 argv
[argc
] = commptr
;
1401 else if (*commptr
== '%')
1403 if (commptr
[1] >= '0' && commptr
[1] <= '9')
1404 *commptr
= (commptr
[1] - '0') << 4;
1406 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
1408 if (commptr
[2] >= '0' && commptr
[2] <= '9')
1409 *commptr
|= commptr
[2] - '0';
1411 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
1413 strcpy(commptr
+ 1, commptr
+ 3);
1418 if (argv
[0][0] == '\0')
1419 argv
[0] = strrchr(command
, '/') + 1;
1422 * Setup the environment variables as needed...
1425 sprintf(lang
, "LANG=%s", con
->language
? con
->language
->language
: "C");
1426 sprintf(server_port
, "SERVER_PORT=%d", ntohs(con
->http
.hostaddr
.sin_port
));
1427 sprintf(remote_host
, "REMOTE_HOST=%s", con
->http
.hostname
);
1428 sprintf(remote_user
, "REMOTE_USER=%s", con
->username
);
1430 envp
[0] = "PATH=/bin:/usr/bin";
1431 envp
[1] = "SERVER_SOFTWARE=CUPS/1.0";
1432 envp
[2] = "SERVER_NAME=localhost"; /* This isn't 100% correct... */
1433 envp
[3] = "GATEWAY_INTERFACE=CGI/1.1";
1434 envp
[4] = "SERVER_PROTOCOL=HTTP/1.1";
1435 envp
[5] = server_port
;
1436 envp
[6] = remote_host
;
1437 envp
[7] = remote_user
;
1441 if (con
->operation
== HTTP_GET
)
1443 envp
[10] = "REQUEST_METHOD=GET";
1448 sprintf(content_length
, "CONTENT_LENGTH=%d", con
->http
.data_remaining
);
1449 sprintf(content_type
, "CONTENT_TYPE=%s",
1450 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1452 envp
[10] = "REQUEST_METHOD=POST";
1453 envp
[11] = content_length
;
1454 envp
[12] = content_type
;
1459 * Create a pipe for the output...
1466 * Then execute the pipe command...
1469 if ((pid
= fork()) == 0)
1472 * Child comes here... Close stdin if necessary and dup the pipe to stdout.
1491 * Execute the pipe program; if an error occurs, exit with status 1...
1494 execve(command
, argv
, envp
);
1501 * Error - can't fork!
1511 * Fork successful - return the PID...
1523 * 'sigpipe_handler()' - Handle 'broken pipe' signals from lost network
1528 sigpipe_handler(int sig
) /* I - Signal number */
1536 * 'show_printer_status()' - Show the current printer status.
1540 show_printer_status(client_t
*con
)
1543 char buffer
[HTTP_MAX_BUFFER
];
1544 static char *states
[] =
1546 "", "", "", "Idle", "Processing", "Stopped"
1551 if (con
->uri
[10] != '\0')
1552 if ((p
= FindPrinter(con
->uri
+ 10)) == NULL
)
1555 if (!SendHeader(con
, HTTP_OK
, "text/html"))
1558 if (con
->http
.version
== HTTP_1_1
)
1560 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
1562 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
1566 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1572 * Send printer information...
1575 sprintf(buffer
, "<HTML>\n"
1577 "\t<TITLE>Printer Status for %s</TITLE>\n"
1578 "\t<META HTTP-EQUIV=\"Refresh\" CONTENT=\"10\">\n"
1580 "<BODY BGCOLOR=#ffffff>\n"
1581 "<TABLE WIDTH=100%%><TR>\n"
1582 "\t<TD ALIGN=LEFTV ALIGN=MIDDLE><IMG SRC=\"/images/cups-small.gif\"></TD>\n"
1583 "\t<TD ALIGN=CENTER VALIGN=MIDDLE><H1>Printer Status for %s</H1></TD>\n"
1584 "\t<TD ALIGN=RIGHT VALIGN=MIDDLE><IMG SRC=\"/images/vendor.gif\"></TD>\n"
1586 "<CENTER><TABLE BORDER=1 WIDTH=80%%>\n"
1587 "<TR><TH>Name</TH><TH>Value</TH></TR>\n"
1588 "<TR><TD>Info</TD><TD>%s</TD></TR>\n"
1589 "<TR><TD>MoreInfo</TD><TD>%s</TD></TR>\n"
1590 "<TR><TD>Location</TD><TD>%s</TD></TR>\n"
1591 "<TR><TD>Device URI</TD><TD>%s</TD></TR>\n"
1592 "<TR><TD>PPDFile</TD><TD>%s</TD></TR>\n",
1593 p
->name
, p
->name
, p
->info
, p
->more_info
,
1594 p
->location
, p
->device_uri
, p
->ppd
);
1596 con
->bytes
+= httpWrite(HTTP(con
), buffer
, strlen(buffer
));
1600 strcpy(buffer
, "<HTML>\n"
1602 "\t<TITLE>Available Printers</TITLE>\n"
1603 "\t<META HTTP-EQUIV=\"Refresh\" CONTENT=\"10\">\n"
1605 "<BODY BGCOLOR=#ffffff>\n"
1606 "<TABLE WIDTH=100%%><TR>\n"
1607 "\t<TD ALIGN=LEFT VALIGN=MIDDLE><IMG SRC=\"/images/cups-small.gif\"></TD>\n"
1608 "\t<TD ALIGN=CENTER VALIGN=MIDDLE><H1>Available Printers</H1></TD>\n"
1609 "\t<TD ALIGN=RIGHT VALIGN=MIDDLE><IMG SRC=\"/images/vendor.gif\"></TD>\n"
1611 "<CENTER><TABLE BORDER=1 WIDTH=80%%>\n"
1612 "<TR><TH>Name</TH><TH>State</TH><TH>Info</TH></TR>\n");
1614 con
->bytes
+= httpWrite(HTTP(con
), buffer
, strlen(buffer
));
1616 for (p
= Printers
; p
!= NULL
; p
= p
->next
)
1618 sprintf(buffer
, "<TR><TD><A HREF=/printers/%s>%s</A></TD><TD>%s</TD><TD>%s</TD></TR>\n",
1619 p
->name
, p
->name
, states
[p
->state
], p
->info
);
1620 con
->bytes
+= httpWrite(HTTP(con
), buffer
, strlen(buffer
));
1624 strcpy(buffer
, "</TABLE></CENTER>\n"
1626 "CUPS Copyright 1997-1999 by Easy Software Products, "
1627 "All Rights Reserved. CUPS and the CUPS logo are the "
1628 "trademark property of Easy Software Products.\n"
1631 con
->bytes
+= httpWrite(HTTP(con
), buffer
, strlen(buffer
));
1632 httpWrite(HTTP(con
), buffer
, 0);
1639 * End of "$Id: client.c,v 1.9 1999/04/16 20:47:47 mike Exp $".