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

Last change on this file since 1300 was 1300, checked in by Sam Hocevar, 13 years ago
  • Do not link cacaserver with libcaca, it only uses libcucul.
  • 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 1300 2006-11-08 07:58:03Z 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    cucul_buffer_t *buffer;
109    unsigned long int buflen;
110    void *bufdata;
111
112    int client_count;
113    struct client *clients;
114
115    RETSIGTYPE (*sigpipe_handler)(int);
116};
117
118static void manage_connections(struct server *server);
119static int send_data(struct server *server, struct client *c);
120ssize_t nonblock_write(int fd, void *buf, size_t len);
121
122int main(void)
123{
124    int i, yes = 1, flags;
125    struct server *server;
126    char *tmp;
127
128#ifdef HAVE_WINDOWS_H
129        WORD winsockVersion;
130        WSADATA wsaData;
131        winsockVersion = MAKEWORD(1, 1);
132
133        WSAStartup(winsockVersion, &wsaData);
134#endif
135    server = malloc(sizeof(struct server));
136
137    server->input = malloc(12);
138    server->read = 0;
139
140    server->client_count = 0;
141    server->clients = NULL;
142    server->port = 0xCACA; /* 51914 */
143
144    /* FIXME, handle >255 sizes */
145    memcpy(server->prefix, INIT_PREFIX, sizeof(INIT_PREFIX));
146    tmp = strstr(server->prefix, "____");
147    tmp[0] = (unsigned char) (server->width & 0xff00) >> 8;
148    tmp[1] = (unsigned char) server->width & 0xff;
149    tmp[2] = (unsigned char) (server->height & 0xff00) >> 8;
150    tmp[3] = (unsigned char) server->height & 0xff;
151
152    if((server->sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
153    {
154        perror("socket");
155        return -1;
156    }
157
158    if(setsockopt(server->sockfd, SOL_SOCKET,
159                  SO_REUSEADDR, &yes, sizeof(int)) == -1)
160    {
161        perror("setsockopt SO_REUSEADDR");
162        return -1;
163    }
164
165    server->my_addr.sin_family = AF_INET;
166    server-> my_addr.sin_port = htons(server->port);
167    server->my_addr.sin_addr.s_addr = INADDR_ANY;
168    memset(&(server->my_addr.sin_zero), '\0', 8);
169
170    if(bind(server->sockfd, (struct sockaddr *)&server->my_addr,
171             sizeof(struct sockaddr)) == -1)
172    {
173        perror("bind");
174        return -1;
175    }
176
177    /* Non blocking socket */
178    flags = fcntl(server->sockfd, F_GETFL, 0);
179    fcntl(server->sockfd, F_SETFL, flags | O_NONBLOCK);
180
181    if(listen(server->sockfd, BACKLOG) == -1)
182    {
183        perror("listen");
184        return -1;
185    }
186
187    server->canvas = NULL;
188    server->buffer = NULL;
189
190    /* Ignore SIGPIPE */
191    server->sigpipe_handler = signal(SIGPIPE, SIG_IGN);
192
193    fprintf(stderr, "initialised network, listening on port %i\n",
194                    server->port);
195
196    /* Main loop */
197    for(;;)
198    {
199        cucul_buffer_t *b;
200        uint8_t *buf = server->input;
201        uint32_t control_size, data_size;
202        unsigned int size;
203
204        /* Manage new connections as this function will be called sometimes
205         * more often than display */
206        manage_connections(server);
207
208        /* Read data from stdin */
209        read(0, buf, 12);
210
211        while(buf[0] != 0xca || buf[1] != 0xca
212               || buf[2] != 'C' || buf[3] != 'V')
213        {
214            memmove(buf, buf + 1, 11);
215            read(0, buf + 11, 1);
216        }
217
218        control_size = ((uint32_t)buf[4] << 24) | ((uint32_t)buf[5] << 16)
219               | ((uint32_t)buf[6] << 8) | (uint32_t)buf[7];
220        data_size = ((uint32_t)buf[8] << 24) | ((uint32_t)buf[9] << 16)
221               | ((uint32_t)buf[10] << 8) | (uint32_t)buf[11];
222
223        size = 4 + control_size + data_size;
224        buf = server->input = realloc(server->input, size);
225        read(0, buf + 12, size - 12);
226
227        /* Free the previous canvas, if any */
228        if(server->canvas)
229            cucul_free_canvas(server->canvas);
230
231        b = cucul_load_memory(buf, size);
232        server->canvas = cucul_import_canvas(b, "caca");
233        cucul_free_buffer(b);
234
235        if(!server->canvas)
236            continue; /* Load error */
237
238        /* Free the previous export buffer, if any */
239        if(server->buffer)
240        {
241            cucul_free_buffer(server->buffer);
242            server->buffer = NULL;
243        }
244
245        /* Get ANSI representation of the image and skip the end-of buffer
246         * linefeed ("\r\n", 2 byte) */
247        server->buffer = cucul_export_canvas(server->canvas, "utf8cr");
248        server->bufdata = cucul_get_buffer_data(server->buffer);
249        server->buflen = cucul_get_buffer_size(server->buffer);
250        server->buflen -= 2;
251
252        for(i = 0; i < server->client_count; i++)
253        {
254            if(server->clients[i].fd == -1)
255                continue;
256
257            if(send_data(server, &server->clients[i]))
258            {
259                fprintf(stderr, "[%i] dropped connection\n",
260                                server->clients[i].fd);
261                close(server->clients[i].fd);
262                server->clients[i].fd = -1;
263            }
264        }
265    }
266
267    /* Kill all remaining clients */
268    for(i = 0; i < server->client_count; i++)
269    {
270        if(server->clients[i].fd == -1)
271            continue;
272
273        close(server->clients[i].fd);
274        server->clients[i].fd = -1;
275    }
276
277    if(server->buffer)
278        cucul_free_buffer(server->buffer);
279
280    /* Restore SIGPIPE handler */
281    signal(SIGPIPE, server->sigpipe_handler);
282
283    free(server);
284
285#ifdef HAVE_WINDOWS_H
286    WSACleanup();
287#endif
288    return 0;
289}
290
291/*
292 * XXX: The following functions are local
293 */
294
295static void manage_connections(struct server *server)
296{
297    int fd, flags;
298    struct sockaddr_in remote_addr;
299    socklen_t len = sizeof(struct sockaddr_in);
300
301    fd = accept(server->sockfd, (struct sockaddr *)&remote_addr, &len);
302    if(fd == -1)
303        return;
304
305    fprintf(stderr, "[%i] connected from %s\n",
306                    fd, inet_ntoa(remote_addr.sin_addr));
307
308    /* Non blocking socket */
309    flags = fcntl(fd, F_SETFL, 0);
310    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
311
312    if(server->clients == NULL)
313    {
314        server->clients = malloc(sizeof(struct client));
315        if(server->clients == NULL)
316            return;
317    }
318    else
319    {
320        server->clients = realloc(server->clients,
321                            (server->client_count+1) * sizeof(struct client));
322    }
323
324    server->clients[server->client_count].fd = fd;
325    server->clients[server->client_count].ready = 0;
326    server->clients[server->client_count].inbytes = 0;
327    server->clients[server->client_count].start = 0;
328    server->clients[server->client_count].stop = 0;
329
330    /* If we already have data to send, send it to the new client */
331    if(send_data(server, &server->clients[server->client_count]))
332    {
333        fprintf(stderr, "[%i] dropped connection\n", fd);
334        close(fd);
335        server->clients[server->client_count].fd = -1;
336        return;
337    }
338
339    server->client_count++;
340}
341
342static int send_data(struct server *server, struct client *c)
343{
344    ssize_t ret;
345
346    /* Not for us */
347    if(c->fd < 0)
348        return -1;
349
350    /* Listen to incoming data */
351    for(;;)
352    {
353        ret = read(c->fd, c->inbuf + c->inbytes, 1);
354        if(ret <= 0)
355            break;
356
357        c->inbytes++;
358
359        /* Check for telnet sequences */
360        if(c->inbuf[0] == 0xff)
361        {
362            if(c->inbytes == 1)
363            {
364                ;
365            }
366            else if(c->inbuf[1] == 0xfd || c->inbuf[1] == 0xfc)
367            {
368                if(c->inbytes == 3)
369                {
370                    fprintf(stderr, "[%i] said: %.02x %.02x %.02x (%s %s %s)\n",
371                            c->fd, c->inbuf[0], c->inbuf[1], c->inbuf[2],
372                            COMMAND_NAME(c->inbuf[0]), COMMAND_NAME(c->inbuf[1]), OPTION_NAME(c->inbuf[2]));
373                    /* Just ignore, lol */
374                    c->inbytes = 0;
375                }
376            }
377            else
378                c->inbytes = 0;
379        }
380        else if(c->inbytes == 1)
381        {
382            if(c->inbuf[0] == 0x03)
383            {
384                fprintf(stderr, "[%i] pressed C-c\n", c->fd);
385                return -1; /* User requested to quit */
386            }
387
388            c->inbytes = 0;
389        }
390    }
391
392    /* Send the telnet initialisation commands */
393    if(!c->ready)
394    {
395        ret = nonblock_write(c->fd, server->prefix, sizeof(INIT_PREFIX));
396        if(ret == -1)
397            return (errno == EAGAIN) ? 0 : -1;
398
399        if(ret < (ssize_t)sizeof(INIT_PREFIX))
400            return 0;
401
402        c->ready = 1;
403    }
404
405    /* No error, there's just nothing to send yet */
406    if(!server->buffer)
407        return 0;
408
409    /* If we have backlog, send the backlog */
410    if(c->stop)
411    {
412        ret = nonblock_write(c->fd, c->outbuf + c->start, c->stop - c->start);
413
414        if(ret == -1)
415        {
416            if(errno == EAGAIN)
417                ret = 0;
418            else
419            {
420                fprintf(stderr, "[%i] failed (%s)\n",
421                        c->fd, strerror(errno));
422                return -1;
423            }
424        }
425
426        if(ret == c->stop - c->start)
427        {
428            /* We got rid of the backlog! */
429            c->start = c->stop = 0;
430        }
431        else
432        {
433            c->start += ret;
434
435            if(c->stop - c->start + strlen(ANSI_PREFIX) + server->buflen
436                > OUTBUFFER)
437            {
438                /* Overflow! Empty buffer and start again */
439                memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
440                c->start = 0;
441                c->stop = strlen(ANSI_RESET);
442                return 0;
443            }
444
445            /* Need to move? */
446            if(c->stop + strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
447            {
448                memmove(c->outbuf, c->outbuf + c->start, c->stop - c->start);
449                c->stop -= c->start;
450                c->start = 0;
451            }
452
453            memcpy(c->outbuf + c->stop, ANSI_PREFIX, strlen(ANSI_PREFIX));
454            c->stop += strlen(ANSI_PREFIX);
455            memcpy(c->outbuf + c->stop, server->bufdata, server->buflen);
456            c->stop += server->buflen;
457
458            return 0;
459        }
460    }
461
462    /* We no longer have backlog, send our new data */
463
464    /* Send ANSI prefix */
465    ret = nonblock_write(c->fd, ANSI_PREFIX, strlen(ANSI_PREFIX));
466    if(ret == -1)
467    {
468        if(errno == EAGAIN)
469            ret = 0;
470        else
471        {
472            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
473            return -1;
474        }
475    }
476
477    if(ret < (ssize_t)strlen(ANSI_PREFIX))
478    {
479        if(strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
480        {
481            /* Overflow! Empty buffer and start again */
482            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
483            c->start = 0;
484            c->stop = strlen(ANSI_RESET);
485            return 0;
486        }
487
488        memcpy(c->outbuf, ANSI_PREFIX, strlen(ANSI_PREFIX) - ret);
489        c->stop = strlen(ANSI_PREFIX) - ret;
490        memcpy(c->outbuf + c->stop, server->bufdata, server->buflen);
491        c->stop += server->buflen;
492
493        return 0;
494    }
495
496    /* Send actual data */
497    ret = nonblock_write(c->fd, server->bufdata, server->buflen);
498    if(ret == -1)
499    {
500        if(errno == EAGAIN)
501            ret = 0;
502        else
503        {
504            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
505            return -1;
506        }
507    }
508
509    if(ret < (int)server->buflen)
510    {
511        if(server->buflen > OUTBUFFER)
512        {
513            /* Overflow! Empty buffer and start again */
514            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
515            c->start = 0;
516            c->stop = strlen(ANSI_RESET);
517            return 0;
518        }
519
520        memcpy(c->outbuf, server->bufdata, server->buflen - ret);
521        c->stop = server->buflen - ret;
522
523        return 0;
524    }
525
526    return 0;
527}
528
529ssize_t nonblock_write(int fd, void *buf, size_t len)
530{
531    size_t total = 0;
532    ssize_t ret;
533
534    while(total < len)
535    {
536        do
537        {
538            ret = write(fd, buf, len);
539        }
540        while(ret < 0 && errno == EINTR);
541
542        if(ret < 0)
543            return ret;
544        else if(ret == 0)
545            return total;
546
547        total += len;
548        buf = (void *)((uintptr_t)buf + len);
549    }
550
551    return total;
552}
553
Note: See TracBrowser for help on using the repository browser.