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

Last change on this file since 1283 was 1283, checked in by Sam Hocevar, 13 years ago
  • Updated the caca export format so that it supports multiple frames.
  • Updated the caca importer to reflect that; only one frame is read at the moment.
  • Added an "utf8cr" export format for UTF-8 + CRLF exports.
  • Updated cacaserver to reflect file format changes.
  • Property svn:keywords set to Id
File size: 14.5 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 1283 2006-11-05 22:20:51Z 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(12);
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        cucul_buffer_t *b;
208        uint8_t *buf = server->input;
209        uint32_t control_size, data_size;
210        unsigned int size;
211
212        /* Manage new connections as this function will be called sometimes
213         * more often than display */
214        manage_connections(server);
215
216        /* Read data from stdin */
217        read(0, buf, 12);
218
219        while(buf[0] != 0xca || buf[1] != 0xca
220               || buf[2] != 'C' || buf[3] != 'V')
221        {
222            memmove(buf, buf + 1, 11);
223            read(0, buf + 11, 1);
224        }
225
226        control_size = ((uint32_t)buf[4] << 24) | ((uint32_t)buf[5] << 16)
227               | ((uint32_t)buf[6] << 8) | (uint32_t)buf[7];
228        data_size = ((uint32_t)buf[8] << 24) | ((uint32_t)buf[9] << 16)
229               | ((uint32_t)buf[10] << 8) | (uint32_t)buf[11];
230
231        size = 4 + control_size + data_size;
232        buf = server->input = realloc(server->input, size);
233        read(0, buf + 12, size - 12);
234
235        /* Free the previous canvas, if any */
236        if(server->canvas)
237            cucul_free_canvas(server->canvas);
238
239        b = cucul_load_memory(buf, size);
240        server->canvas = cucul_import_canvas(b, "caca");
241        cucul_free_buffer(b);
242
243        if(!server->canvas)
244            continue; /* Load error */
245
246        /* Free the previous export buffer, if any */
247        if(server->buffer)
248        {
249            cucul_free_buffer(server->buffer);
250            server->buffer = NULL;
251        }
252
253        /* Get ANSI representation of the image and skip the end-of buffer
254         * linefeed ("\r\n", 2 byte) */
255        server->buffer = cucul_export_canvas(server->canvas, "utf8cr");
256        server->bufdata = cucul_get_buffer_data(server->buffer);
257        server->buflen = cucul_get_buffer_size(server->buffer);
258        server->buflen -= 2;
259
260        for(i = 0; i < server->client_count; i++)
261        {
262            if(server->clients[i].fd == -1)
263                continue;
264
265            if(send_data(server, &server->clients[i]))
266            {
267                fprintf(stderr, "[%i] dropped connection\n",
268                                server->clients[i].fd);
269                close(server->clients[i].fd);
270                server->clients[i].fd = -1;
271            }
272        }
273    }
274
275    /* Kill all remaining clients */
276    for(i = 0; i < server->client_count; i++)
277    {
278        if(server->clients[i].fd == -1)
279            continue;
280
281        close(server->clients[i].fd);
282        server->clients[i].fd = -1;
283    }
284
285    if(server->buffer)
286        cucul_free_buffer(server->buffer);
287
288    /* Restore SIGPIPE handler */
289    signal(SIGPIPE, server->sigpipe_handler);
290
291    free(server);
292
293#ifdef HAVE_WINDOWS_H
294    WSACleanup();
295#endif
296    return 0;
297}
298
299/*
300 * XXX: The following functions are local
301 */
302
303static void manage_connections(struct server *server)
304{
305    int fd, flags;
306    struct sockaddr_in remote_addr;
307    socklen_t len = sizeof(struct sockaddr_in);
308
309    fd = accept(server->sockfd, (struct sockaddr *)&remote_addr, &len);
310    if(fd == -1)
311        return;
312
313    fprintf(stderr, "[%i] connected from %s\n",
314                    fd, inet_ntoa(remote_addr.sin_addr));
315
316    /* Non blocking socket */
317    flags = fcntl(fd, F_SETFL, 0);
318    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
319
320    if(server->clients == NULL)
321    {
322        server->clients = malloc(sizeof(struct client));
323        if(server->clients == NULL)
324            return;
325    }
326    else
327    {
328        server->clients = realloc(server->clients,
329                            (server->client_count+1) * sizeof(struct client));
330    }
331
332    server->clients[server->client_count].fd = fd;
333    server->clients[server->client_count].ready = 0;
334    server->clients[server->client_count].inbytes = 0;
335    server->clients[server->client_count].start = 0;
336    server->clients[server->client_count].stop = 0;
337
338    /* If we already have data to send, send it to the new client */
339    if(send_data(server, &server->clients[server->client_count]))
340    {
341        fprintf(stderr, "[%i] dropped connection\n", fd);
342        close(fd);
343        server->clients[server->client_count].fd = -1;
344        return;
345    }
346
347    server->client_count++;
348}
349
350static int send_data(struct server *server, struct client *c)
351{
352    ssize_t ret;
353
354    /* Not for us */
355    if(c->fd < 0)
356        return -1;
357
358    /* Listen to incoming data */
359    for(;;)
360    {
361        ret = read(c->fd, c->inbuf + c->inbytes, 1);
362        if(ret <= 0)
363            break;
364
365        c->inbytes++;
366
367        /* Check for telnet sequences */
368        if(c->inbuf[0] == 0xff)
369        {
370            if(c->inbytes == 1)
371            {
372                ;
373            }
374            else if(c->inbuf[1] == 0xfd || c->inbuf[1] == 0xfc)
375            {
376                if(c->inbytes == 3)
377                {
378                    fprintf(stderr, "[%i] said: %.02x %.02x %.02x (%s %s %s)\n",
379                            c->fd, c->inbuf[0], c->inbuf[1], c->inbuf[2],
380                            COMMAND_NAME(c->inbuf[0]), COMMAND_NAME(c->inbuf[1]), OPTION_NAME(c->inbuf[2]));
381                    /* Just ignore, lol */
382                    c->inbytes = 0;
383                }
384            }
385            else
386                c->inbytes = 0;
387        }
388        else if(c->inbytes == 1)
389        {
390            if(c->inbuf[0] == 0x03)
391            {
392                fprintf(stderr, "[%i] pressed C-c\n", c->fd);
393                return -1; /* User requested to quit */
394            }
395
396            c->inbytes = 0;
397        }
398    }
399
400    /* Send the telnet initialisation commands */
401    if(!c->ready)
402    {
403        ret = nonblock_write(c->fd, server->prefix, sizeof(INIT_PREFIX));
404        if(ret == -1)
405            return (errno == EAGAIN) ? 0 : -1;
406
407        if(ret < (ssize_t)sizeof(INIT_PREFIX))
408            return 0;
409
410        c->ready = 1;
411    }
412
413    /* No error, there's just nothing to send yet */
414    if(!server->buffer)
415        return 0;
416
417    /* If we have backlog, send the backlog */
418    if(c->stop)
419    {
420        ret = nonblock_write(c->fd, c->outbuf + c->start, c->stop - c->start);
421
422        if(ret == -1)
423        {
424            if(errno == EAGAIN)
425                ret = 0;
426            else
427            {
428                fprintf(stderr, "[%i] failed (%s)\n",
429                        c->fd, strerror(errno));
430                return -1;
431            }
432        }
433
434        if(ret == c->stop - c->start)
435        {
436            /* We got rid of the backlog! */
437            c->start = c->stop = 0;
438        }
439        else
440        {
441            c->start += ret;
442
443            if(c->stop - c->start + strlen(ANSI_PREFIX) + server->buflen
444                > OUTBUFFER)
445            {
446                /* Overflow! Empty buffer and start again */
447                memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
448                c->start = 0;
449                c->stop = strlen(ANSI_RESET);
450                return 0;
451            }
452
453            /* Need to move? */
454            if(c->stop + strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
455            {
456                memmove(c->outbuf, c->outbuf + c->start, c->stop - c->start);
457                c->stop -= c->start;
458                c->start = 0;
459            }
460
461            memcpy(c->outbuf + c->stop, ANSI_PREFIX, strlen(ANSI_PREFIX));
462            c->stop += strlen(ANSI_PREFIX);
463            memcpy(c->outbuf + c->stop, server->bufdata, server->buflen);
464            c->stop += server->buflen;
465
466            return 0;
467        }
468    }
469
470    /* We no longer have backlog, send our new data */
471
472    /* Send ANSI prefix */
473    ret = nonblock_write(c->fd, ANSI_PREFIX, strlen(ANSI_PREFIX));
474    if(ret == -1)
475    {
476        if(errno == EAGAIN)
477            ret = 0;
478        else
479        {
480            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
481            return -1;
482        }
483    }
484
485    if(ret < (ssize_t)strlen(ANSI_PREFIX))
486    {
487        if(strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
488        {
489            /* Overflow! Empty buffer and start again */
490            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
491            c->start = 0;
492            c->stop = strlen(ANSI_RESET);
493            return 0;
494        }
495
496        memcpy(c->outbuf, ANSI_PREFIX, strlen(ANSI_PREFIX) - ret);
497        c->stop = strlen(ANSI_PREFIX) - ret;
498        memcpy(c->outbuf + c->stop, server->bufdata, server->buflen);
499        c->stop += server->buflen;
500
501        return 0;
502    }
503
504    /* Send actual data */
505    ret = nonblock_write(c->fd, server->bufdata, server->buflen);
506    if(ret == -1)
507    {
508        if(errno == EAGAIN)
509            ret = 0;
510        else
511        {
512            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
513            return -1;
514        }
515    }
516
517    if(ret < (int)server->buflen)
518    {
519        if(server->buflen > OUTBUFFER)
520        {
521            /* Overflow! Empty buffer and start again */
522            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
523            c->start = 0;
524            c->stop = strlen(ANSI_RESET);
525            return 0;
526        }
527
528        memcpy(c->outbuf, server->bufdata, server->buflen - ret);
529        c->stop = server->buflen - ret;
530
531        return 0;
532    }
533
534    return 0;
535}
536
537ssize_t nonblock_write(int fd, void *buf, size_t len)
538{
539    size_t total = 0;
540    ssize_t ret;
541
542    while(total < len)
543    {
544        do
545        {
546            ret = write(fd, buf, len);
547        }
548        while(ret < 0 && errno == EINTR);
549
550        if(ret < 0)
551            return ret;
552        else if(ret == 0)
553            return total;
554
555        total += len;
556        buf = (void *)((uintptr_t)buf + len);
557    }
558
559    return total;
560}
561
Note: See TracBrowser for help on using the repository browser.