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

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