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

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