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

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