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

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