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

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