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

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