source: libcaca/trunk/src/cacaserver.c @ 1308

Last change on this file since 1308 was 1308, checked in by Sam Hocevar, 14 years ago
  • Convert all programs and tests to the new import/export API.
  • Property svn:keywords set to Id
File size: 14.1 KB
Line 
1/*
2 *  cacaserver    Colour ASCII-Art library
3 *  Copyright (c) 2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
4 *                2006 Sam Hocevar <sam@zoy.org>
5 *                All Rights Reserved
6 *
7 *  $Id: cacaserver.c 1308 2006-11-08 17:26:57Z sam $
8 *
9 *  This program is free software; you can redistribute it and/or
10 *  modify it under the terms of the Do What The Fuck You Want To
11 *  Public License, Version 2, as published by Sam Hocevar. See
12 *  http://sam.zoy.org/wtfpl/COPYING for more details.
13 */
14
15#include "config.h"
16#include "common.h"
17
18#include <stdio.h>
19#include <string.h>
20#include <stdlib.h>
21#if defined(HAVE_ARPA_INET_H)
22#   include <arpa/inet.h>
23#elif defined(HAVE_NETINET_IN_H)
24#   include <netinet/in.h>
25#elif defined(HAVE_WINSOCK2_H)
26#   include <winsock2.h>
27#   include <ws2tcpip.h>
28#endif
29#if defined(HAVE_UNISTD_H)
30#   include <unistd.h>
31#endif
32#include <sys/types.h>
33#include <sys/socket.h>
34#include <fcntl.h>
35#include <signal.h>
36#include <errno.h>
37#include <stdarg.h>
38
39#include "cucul.h"
40
41#define BACKLOG 1337     /* Number of pending connections */
42#define INBUFFER 32      /* Size of per-client input buffer */
43#define OUTBUFFER 300000 /* Size of per-client output buffer */
44
45/* Following vars are static */
46#define INIT_PREFIX \
47    "\xff\xfb\x01"     /* WILL ECHO */ \
48    "\xff\xfb\x03"     /* WILL SUPPRESS GO AHEAD */ \
49    "\xff\xfd\x31"     /* DO NAWS */ \
50    "\xff\x1f\xfa____" /* SB NAWS */ \
51    "\xff\xf0"         /* SE */  \
52    "\x1b]2;caca for the network\x07" /* Change window title */ \
53    "\x1b[H\x1b[J" /* Clear screen */
54    /*"\x1b[?25l"*/ /* Hide cursor */
55
56#define ANSI_PREFIX \
57    "\x1b[1;1H" /* move(0,0) */ \
58    "\x1b[1;1H" /* move(0,0) again */
59
60#define ANSI_RESET \
61    "    " /* Garbage */ \
62    "\x1b[?1049h" /* Clear screen */ \
63    "\x1b[?1049h" /* Clear screen again */
64
65static char const telnet_commands[16][5] =
66{
67    "SE  ", "NOP ", "DM  ", "BRK ", "IP  ", "AO  ", "AYT ", "EC  ",
68    "EL  ", "GA  ", "SB  ", "WILL", "WONT", "DO  ", "DONT", "IAC "
69};
70
71static char const telnet_options[37][5] =
72{
73    "????", "ECHO", "????", "SUGH", "????", "STTS", "TIMK", "????",
74    "????", "????", "????", "????", "????", "????", "????", "????",
75    "????", "????", "????", "????", "????", "????", "????", "????",
76    "TTYP", "????", "????", "????", "????", "????", "????", "NAWS",
77    "TRSP", "RMFC", "LIMO", "????", "EVAR"
78};
79
80#define COMMAND_NAME(x) (x>=240)?telnet_commands[x-240]:"????"
81#define OPTION_NAME(x) (x<=36)?telnet_options[x]:"????"
82
83struct client
84{
85    int fd;
86    int ready;
87    uint8_t inbuf[INBUFFER];
88    int inbytes;
89    uint8_t outbuf[OUTBUFFER];
90    int start, stop;
91};
92
93struct server
94{
95    unsigned int width, height;
96    unsigned int port;
97    int sockfd;
98    struct sockaddr_in my_addr;
99    socklen_t sin_size;
100
101    /* Input buffer */
102    uint8_t *input;
103    unsigned int read;
104
105    char prefix[sizeof(INIT_PREFIX)];
106
107    cucul_canvas_t *canvas;
108    void *buffer;
109    unsigned long int buflen;
110
111    int client_count;
112    struct client *clients;
113
114    RETSIGTYPE (*sigpipe_handler)(int);
115};
116
117static void manage_connections(struct server *server);
118static int send_data(struct server *server, struct client *c);
119ssize_t nonblock_write(int fd, void *buf, size_t len);
120
121int main(void)
122{
123    int i, yes = 1, flags;
124    struct server *server;
125    char *tmp;
126
127#ifdef HAVE_WINDOWS_H
128        WORD winsockVersion;
129        WSADATA wsaData;
130        winsockVersion = MAKEWORD(1, 1);
131
132        WSAStartup(winsockVersion, &wsaData);
133#endif
134    server = malloc(sizeof(struct server));
135
136    server->input = malloc(12);
137    server->read = 0;
138
139    server->client_count = 0;
140    server->clients = NULL;
141    server->port = 0xCACA; /* 51914 */
142
143    /* FIXME, handle >255 sizes */
144    memcpy(server->prefix, INIT_PREFIX, sizeof(INIT_PREFIX));
145    tmp = strstr(server->prefix, "____");
146    tmp[0] = (unsigned char) (server->width & 0xff00) >> 8;
147    tmp[1] = (unsigned char) server->width & 0xff;
148    tmp[2] = (unsigned char) (server->height & 0xff00) >> 8;
149    tmp[3] = (unsigned char) server->height & 0xff;
150
151    if((server->sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
152    {
153        perror("socket");
154        return -1;
155    }
156
157    if(setsockopt(server->sockfd, SOL_SOCKET,
158                  SO_REUSEADDR, &yes, sizeof(int)) == -1)
159    {
160        perror("setsockopt SO_REUSEADDR");
161        return -1;
162    }
163
164    server->my_addr.sin_family = AF_INET;
165    server-> my_addr.sin_port = htons(server->port);
166    server->my_addr.sin_addr.s_addr = INADDR_ANY;
167    memset(&(server->my_addr.sin_zero), '\0', 8);
168
169    if(bind(server->sockfd, (struct sockaddr *)&server->my_addr,
170             sizeof(struct sockaddr)) == -1)
171    {
172        perror("bind");
173        return -1;
174    }
175
176    /* Non blocking socket */
177    flags = fcntl(server->sockfd, F_GETFL, 0);
178    fcntl(server->sockfd, F_SETFL, flags | O_NONBLOCK);
179
180    if(listen(server->sockfd, BACKLOG) == -1)
181    {
182        perror("listen");
183        return -1;
184    }
185
186    server->canvas = cucul_create_canvas(0, 0);
187    server->buffer = NULL;
188
189    /* Ignore SIGPIPE */
190    server->sigpipe_handler = signal(SIGPIPE, SIG_IGN);
191
192    fprintf(stderr, "initialised network, listening on port %i\n",
193                    server->port);
194
195    /* Main loop */
196    for(;;)
197    {
198        uint8_t *buf = server->input;
199        uint32_t control_size, data_size;
200        unsigned int size;
201
202        /* Manage new connections as this function will be called sometimes
203         * more often than display */
204        manage_connections(server);
205
206        /* Read data from stdin */
207        read(0, buf, 12);
208
209        while(buf[0] != 0xca || buf[1] != 0xca
210               || buf[2] != 'C' || buf[3] != 'V')
211        {
212            memmove(buf, buf + 1, 11);
213            read(0, buf + 11, 1);
214        }
215
216        control_size = ((uint32_t)buf[4] << 24) | ((uint32_t)buf[5] << 16)
217               | ((uint32_t)buf[6] << 8) | (uint32_t)buf[7];
218        data_size = ((uint32_t)buf[8] << 24) | ((uint32_t)buf[9] << 16)
219               | ((uint32_t)buf[10] << 8) | (uint32_t)buf[11];
220
221        size = 4 + control_size + data_size;
222        buf = server->input = realloc(server->input, size);
223        read(0, buf + 12, size - 12);
224
225        if(cucul_import_memory(server->canvas, buf, size, "caca") < 0)
226            continue; /* Load error */
227
228        /* Free the previous export buffer, if any */
229        if(server->buffer)
230        {
231            free(server->buffer);
232            server->buffer = NULL;
233        }
234
235        /* Get ANSI representation of the image and skip the end-of buffer
236         * linefeed ("\r\n", 2 byte) */
237        server->buffer = cucul_export_memory(server->canvas, "utf8cr",
238                                             &server->buflen);
239        server->buflen -= 2;
240
241        for(i = 0; i < server->client_count; i++)
242        {
243            if(server->clients[i].fd == -1)
244                continue;
245
246            if(send_data(server, &server->clients[i]))
247            {
248                fprintf(stderr, "[%i] dropped connection\n",
249                                server->clients[i].fd);
250                close(server->clients[i].fd);
251                server->clients[i].fd = -1;
252            }
253        }
254    }
255
256    /* Kill all remaining clients */
257    for(i = 0; i < server->client_count; i++)
258    {
259        if(server->clients[i].fd == -1)
260            continue;
261
262        close(server->clients[i].fd);
263        server->clients[i].fd = -1;
264    }
265
266    if(server->buffer)
267        free(server->buffer);
268
269    cucul_free_canvas(server->canvas);
270
271    /* Restore SIGPIPE handler */
272    signal(SIGPIPE, server->sigpipe_handler);
273
274    free(server);
275
276#ifdef HAVE_WINDOWS_H
277    WSACleanup();
278#endif
279    return 0;
280}
281
282/*
283 * XXX: The following functions are local
284 */
285
286static void manage_connections(struct server *server)
287{
288    int fd, flags;
289    struct sockaddr_in remote_addr;
290    socklen_t len = sizeof(struct sockaddr_in);
291
292    fd = accept(server->sockfd, (struct sockaddr *)&remote_addr, &len);
293    if(fd == -1)
294        return;
295
296    fprintf(stderr, "[%i] connected from %s\n",
297                    fd, inet_ntoa(remote_addr.sin_addr));
298
299    /* Non blocking socket */
300    flags = fcntl(fd, F_SETFL, 0);
301    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
302
303    if(server->clients == NULL)
304    {
305        server->clients = malloc(sizeof(struct client));
306        if(server->clients == NULL)
307            return;
308    }
309    else
310    {
311        server->clients = realloc(server->clients,
312                            (server->client_count+1) * sizeof(struct client));
313    }
314
315    server->clients[server->client_count].fd = fd;
316    server->clients[server->client_count].ready = 0;
317    server->clients[server->client_count].inbytes = 0;
318    server->clients[server->client_count].start = 0;
319    server->clients[server->client_count].stop = 0;
320
321    /* If we already have data to send, send it to the new client */
322    if(send_data(server, &server->clients[server->client_count]))
323    {
324        fprintf(stderr, "[%i] dropped connection\n", fd);
325        close(fd);
326        server->clients[server->client_count].fd = -1;
327        return;
328    }
329
330    server->client_count++;
331}
332
333static int send_data(struct server *server, struct client *c)
334{
335    ssize_t ret;
336
337    /* Not for us */
338    if(c->fd < 0)
339        return -1;
340
341    /* Listen to incoming data */
342    for(;;)
343    {
344        ret = read(c->fd, c->inbuf + c->inbytes, 1);
345        if(ret <= 0)
346            break;
347
348        c->inbytes++;
349
350        /* Check for telnet sequences */
351        if(c->inbuf[0] == 0xff)
352        {
353            if(c->inbytes == 1)
354            {
355                ;
356            }
357            else if(c->inbuf[1] == 0xfd || c->inbuf[1] == 0xfc)
358            {
359                if(c->inbytes == 3)
360                {
361                    fprintf(stderr, "[%i] said: %.02x %.02x %.02x (%s %s %s)\n",
362                            c->fd, c->inbuf[0], c->inbuf[1], c->inbuf[2],
363                            COMMAND_NAME(c->inbuf[0]), COMMAND_NAME(c->inbuf[1]), OPTION_NAME(c->inbuf[2]));
364                    /* Just ignore, lol */
365                    c->inbytes = 0;
366                }
367            }
368            else
369                c->inbytes = 0;
370        }
371        else if(c->inbytes == 1)
372        {
373            if(c->inbuf[0] == 0x03)
374            {
375                fprintf(stderr, "[%i] pressed C-c\n", c->fd);
376                return -1; /* User requested to quit */
377            }
378
379            c->inbytes = 0;
380        }
381    }
382
383    /* Send the telnet initialisation commands */
384    if(!c->ready)
385    {
386        ret = nonblock_write(c->fd, server->prefix, sizeof(INIT_PREFIX));
387        if(ret == -1)
388            return (errno == EAGAIN) ? 0 : -1;
389
390        if(ret < (ssize_t)sizeof(INIT_PREFIX))
391            return 0;
392
393        c->ready = 1;
394    }
395
396    /* No error, there's just nothing to send yet */
397    if(!server->buffer)
398        return 0;
399
400    /* If we have backlog, send the backlog */
401    if(c->stop)
402    {
403        ret = nonblock_write(c->fd, c->outbuf + c->start, c->stop - c->start);
404
405        if(ret == -1)
406        {
407            if(errno == EAGAIN)
408                ret = 0;
409            else
410            {
411                fprintf(stderr, "[%i] failed (%s)\n",
412                        c->fd, strerror(errno));
413                return -1;
414            }
415        }
416
417        if(ret == c->stop - c->start)
418        {
419            /* We got rid of the backlog! */
420            c->start = c->stop = 0;
421        }
422        else
423        {
424            c->start += ret;
425
426            if(c->stop - c->start + strlen(ANSI_PREFIX) + server->buflen
427                > OUTBUFFER)
428            {
429                /* Overflow! Empty buffer and start again */
430                memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
431                c->start = 0;
432                c->stop = strlen(ANSI_RESET);
433                return 0;
434            }
435
436            /* Need to move? */
437            if(c->stop + strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
438            {
439                memmove(c->outbuf, c->outbuf + c->start, c->stop - c->start);
440                c->stop -= c->start;
441                c->start = 0;
442            }
443
444            memcpy(c->outbuf + c->stop, ANSI_PREFIX, strlen(ANSI_PREFIX));
445            c->stop += strlen(ANSI_PREFIX);
446            memcpy(c->outbuf + c->stop, server->buffer, server->buflen);
447            c->stop += server->buflen;
448
449            return 0;
450        }
451    }
452
453    /* We no longer have backlog, send our new data */
454
455    /* Send ANSI prefix */
456    ret = nonblock_write(c->fd, ANSI_PREFIX, strlen(ANSI_PREFIX));
457    if(ret == -1)
458    {
459        if(errno == EAGAIN)
460            ret = 0;
461        else
462        {
463            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
464            return -1;
465        }
466    }
467
468    if(ret < (ssize_t)strlen(ANSI_PREFIX))
469    {
470        if(strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
471        {
472            /* Overflow! Empty buffer and start again */
473            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
474            c->start = 0;
475            c->stop = strlen(ANSI_RESET);
476            return 0;
477        }
478
479        memcpy(c->outbuf, ANSI_PREFIX, strlen(ANSI_PREFIX) - ret);
480        c->stop = strlen(ANSI_PREFIX) - ret;
481        memcpy(c->outbuf + c->stop, server->buffer, server->buflen);
482        c->stop += server->buflen;
483
484        return 0;
485    }
486
487    /* Send actual data */
488    ret = nonblock_write(c->fd, server->buffer, server->buflen);
489    if(ret == -1)
490    {
491        if(errno == EAGAIN)
492            ret = 0;
493        else
494        {
495            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
496            return -1;
497        }
498    }
499
500    if(ret < (int)server->buflen)
501    {
502        if(server->buflen > OUTBUFFER)
503        {
504            /* Overflow! Empty buffer and start again */
505            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
506            c->start = 0;
507            c->stop = strlen(ANSI_RESET);
508            return 0;
509        }
510
511        memcpy(c->outbuf, server->buffer, server->buflen - ret);
512        c->stop = server->buflen - ret;
513
514        return 0;
515    }
516
517    return 0;
518}
519
520ssize_t nonblock_write(int fd, void *buf, size_t len)
521{
522    size_t total = 0;
523    ssize_t ret;
524
525    while(total < len)
526    {
527        do
528        {
529            ret = write(fd, buf, len);
530        }
531        while(ret < 0 && errno == EINTR);
532
533        if(ret < 0)
534            return ret;
535        else if(ret == 0)
536            return total;
537
538        total += len;
539        buf = (void *)((uintptr_t)buf + len);
540    }
541
542    return total;
543}
544
Note: See TracBrowser for help on using the repository browser.