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

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