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

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