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

Last change on this file since 1914 was 1914, checked in by Sam Hocevar, 12 years ago
  • Always include <netinet/in.h> when present, to make header simpler.
  • Property svn:keywords set to Id
File size: 14.6 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 1914 2007-11-07 01:09:20Z sam $
8 *
9 *  This program is free software. It comes without any warranty, to
10 *  the extent permitted by applicable law. You can redistribute it
11 *  and/or modify it under the terms of the Do What The Fuck You Want
12 *  To Public License, Version 2, as published by Sam Hocevar. See
13 *  http://sam.zoy.org/wtfpl/COPYING for more details.
14 */
15
16#include "config.h"
17#include "common.h"
18
19#include <stdio.h>
20#include <string.h>
21#include <stdlib.h>
22#if defined(HAVE_ARPA_INET_H)
23#   include <arpa/inet.h>
24#elif defined(HAVE_WINSOCK2_H)
25#   include <winsock2.h>
26#   include <ws2tcpip.h>
27#   define USE_WINSOCK 1
28#endif
29#if defined(HAVE_NETINET_IN_H)
30#   include <netinet/in.h>
31#endif
32#if defined(HAVE_UNISTD_H)
33#   include <unistd.h>
34#endif
35#include <sys/types.h>
36#include <sys/socket.h>
37#include <fcntl.h>
38#include <signal.h>
39#include <errno.h>
40#include <stdarg.h>
41
42#ifndef USE_WINSOCK
43#   define USE_WINSOCK 0
44#endif
45
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    void *buffer;
116    unsigned long int buflen;
117
118    int client_count;
119    struct client *clients;
120
121    RETSIGTYPE (*sigpipe_handler)(int);
122};
123
124static void manage_connections(struct server *server);
125static int send_data(struct server *server, struct client *c);
126ssize_t nonblock_write(int fd, void *buf, size_t len);
127
128int main(void)
129{
130    int i, yes = 1, flags;
131    struct server *server;
132    char *tmp;
133
134#if USE_WINSOCK
135    WORD winsockVersion;
136    WSADATA wsaData;
137    winsockVersion = MAKEWORD(1, 1);
138
139    WSAStartup(winsockVersion, &wsaData);
140#endif
141    server = malloc(sizeof(struct server));
142
143    server->input = malloc(12);
144    server->read = 0;
145
146    server->client_count = 0;
147    server->clients = NULL;
148    server->port = 0xCACA; /* 51914 */
149
150    /* FIXME, handle >255 sizes */
151    memcpy(server->prefix, INIT_PREFIX, sizeof(INIT_PREFIX));
152    tmp = strstr(server->prefix, "____");
153    tmp[0] = (unsigned char) (server->width & 0xff00) >> 8;
154    tmp[1] = (unsigned char) server->width & 0xff;
155    tmp[2] = (unsigned char) (server->height & 0xff00) >> 8;
156    tmp[3] = (unsigned char) server->height & 0xff;
157
158    if((server->sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
159    {
160        perror("socket");
161        return -1;
162    }
163
164    if(setsockopt(server->sockfd, SOL_SOCKET,
165                  SO_REUSEADDR, &yes, sizeof(int)) == -1)
166    {
167        perror("setsockopt SO_REUSEADDR");
168        return -1;
169    }
170
171    server->my_addr.sin_family = AF_INET;
172    server-> my_addr.sin_port = htons(server->port);
173    server->my_addr.sin_addr.s_addr = INADDR_ANY;
174    memset(&(server->my_addr.sin_zero), '\0', 8);
175
176    if(bind(server->sockfd, (struct sockaddr *)&server->my_addr,
177             sizeof(struct sockaddr)) == -1)
178    {
179        perror("bind");
180        return -1;
181    }
182
183    /* Non blocking socket */
184    flags = fcntl(server->sockfd, F_GETFL, 0);
185    fcntl(server->sockfd, F_SETFL, flags | O_NONBLOCK);
186
187    if(listen(server->sockfd, BACKLOG) == -1)
188    {
189        perror("listen");
190        return -1;
191    }
192
193    server->canvas = cucul_create_canvas(0, 0);
194    server->buffer = NULL;
195
196    /* Ignore SIGPIPE */
197    server->sigpipe_handler = signal(SIGPIPE, SIG_IGN);
198
199    fprintf(stderr, "initialised network, listening on port %i\n",
200                    server->port);
201
202    /* Main loop */
203    for(;;)
204    {
205restart:
206        /* Manage new connections as this function will be called sometimes
207         * more often than display */
208        manage_connections(server);
209
210        /* Read data from stdin */
211        if(server->read < 12)
212        {
213            read(0, server->input + server->read, 12 - server->read);
214            server->read = 12;
215        }
216
217        while(cucul_import_memory(server->canvas, server->input,
218                                  server->read, "caca") < 0)
219        {
220            memmove(server->input, server->input + 1, server->read - 1);
221            read(0, server->input + server->read - 1, 1);
222        }
223
224        for(;;)
225        {
226            long int needed;
227            ssize_t wanted;
228
229            needed = cucul_import_memory(server->canvas, server->input,
230                                         server->read, "caca");
231            if(needed < 0)
232                goto restart;
233
234            if(needed > 0)
235            {
236                server->read -= needed;
237                memmove(server->input, server->input + needed, server->read);
238                break;
239            }
240
241            server->input = realloc(server->input, server->read + 128);
242            wanted = read(0, server->input + server->read, 128);
243            if(wanted < 0)
244                goto restart;
245            server->read += wanted;
246        }
247           
248        /* Free the previous export buffer, if any */
249        if(server->buffer)
250        {
251            free(server->buffer);
252            server->buffer = NULL;
253        }
254
255        /* Get ANSI representation of the image and skip the end-of buffer
256         * linefeed ("\r\n", 2 byte) */
257        server->buffer = cucul_export_memory(server->canvas, "utf8cr",
258                                             &server->buflen);
259        server->buflen -= 2;
260
261        for(i = 0; i < server->client_count; i++)
262        {
263            if(server->clients[i].fd == -1)
264                continue;
265
266            if(send_data(server, &server->clients[i]))
267            {
268                fprintf(stderr, "[%i] dropped connection\n",
269                                server->clients[i].fd);
270                close(server->clients[i].fd);
271                server->clients[i].fd = -1;
272            }
273        }
274    }
275
276    /* Kill all remaining clients */
277    for(i = 0; i < server->client_count; i++)
278    {
279        if(server->clients[i].fd == -1)
280            continue;
281
282        close(server->clients[i].fd);
283        server->clients[i].fd = -1;
284    }
285
286    if(server->buffer)
287        free(server->buffer);
288
289    cucul_free_canvas(server->canvas);
290
291    /* Restore SIGPIPE handler */
292    signal(SIGPIPE, server->sigpipe_handler);
293
294    free(server);
295
296#if USE_WINSOCK
297    WSACleanup();
298#endif
299    return 0;
300}
301
302/*
303 * XXX: The following functions are local
304 */
305
306static void manage_connections(struct server *server)
307{
308    int fd, flags;
309    struct sockaddr_in remote_addr;
310    socklen_t len = sizeof(struct sockaddr_in);
311
312    fd = accept(server->sockfd, (struct sockaddr *)&remote_addr, &len);
313    if(fd == -1)
314        return;
315
316    fprintf(stderr, "[%i] connected from %s\n",
317                    fd, inet_ntoa(remote_addr.sin_addr));
318
319    /* Non blocking socket */
320    flags = fcntl(fd, F_SETFL, 0);
321    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
322
323    if(server->clients == NULL)
324    {
325        server->clients = malloc(sizeof(struct client));
326        if(server->clients == NULL)
327            return;
328    }
329    else
330    {
331        server->clients = realloc(server->clients,
332                            (server->client_count+1) * sizeof(struct client));
333    }
334
335    server->clients[server->client_count].fd = fd;
336    server->clients[server->client_count].ready = 0;
337    server->clients[server->client_count].inbytes = 0;
338    server->clients[server->client_count].start = 0;
339    server->clients[server->client_count].stop = 0;
340
341    /* If we already have data to send, send it to the new client */
342    if(send_data(server, &server->clients[server->client_count]))
343    {
344        fprintf(stderr, "[%i] dropped connection\n", fd);
345        close(fd);
346        server->clients[server->client_count].fd = -1;
347        return;
348    }
349
350    server->client_count++;
351}
352
353static int send_data(struct server *server, struct client *c)
354{
355    ssize_t ret;
356
357    /* Not for us */
358    if(c->fd < 0)
359        return -1;
360
361    /* Listen to incoming data */
362    for(;;)
363    {
364        ret = read(c->fd, c->inbuf + c->inbytes, 1);
365        if(ret <= 0)
366            break;
367
368        c->inbytes++;
369
370        /* Check for telnet sequences */
371        if(c->inbuf[0] == 0xff)
372        {
373            if(c->inbytes == 1)
374            {
375                ;
376            }
377            else if(c->inbuf[1] == 0xfd || c->inbuf[1] == 0xfc)
378            {
379                if(c->inbytes == 3)
380                {
381                    fprintf(stderr, "[%i] said: %.02x %.02x %.02x (%s %s %s)\n",
382                            c->fd, c->inbuf[0], c->inbuf[1], c->inbuf[2],
383                            COMMAND_NAME(c->inbuf[0]), COMMAND_NAME(c->inbuf[1]), OPTION_NAME(c->inbuf[2]));
384                    /* Just ignore, lol */
385                    c->inbytes = 0;
386                }
387            }
388            else
389                c->inbytes = 0;
390        }
391        else if(c->inbytes == 1)
392        {
393            if(c->inbuf[0] == 0x03)
394            {
395                fprintf(stderr, "[%i] pressed C-c\n", c->fd);
396                return -1; /* User requested to quit */
397            }
398
399            c->inbytes = 0;
400        }
401    }
402
403    /* Send the telnet initialisation commands */
404    if(!c->ready)
405    {
406        ret = nonblock_write(c->fd, server->prefix, sizeof(INIT_PREFIX));
407        if(ret == -1)
408            return (errno == EAGAIN) ? 0 : -1;
409
410        if(ret < (ssize_t)sizeof(INIT_PREFIX))
411            return 0;
412
413        c->ready = 1;
414    }
415
416    /* No error, there's just nothing to send yet */
417    if(!server->buffer)
418        return 0;
419
420    /* If we have backlog, send the backlog */
421    if(c->stop)
422    {
423        ret = nonblock_write(c->fd, c->outbuf + c->start, c->stop - c->start);
424
425        if(ret == -1)
426        {
427            if(errno == EAGAIN)
428                ret = 0;
429            else
430            {
431                fprintf(stderr, "[%i] failed (%s)\n",
432                        c->fd, strerror(errno));
433                return -1;
434            }
435        }
436
437        if(ret == c->stop - c->start)
438        {
439            /* We got rid of the backlog! */
440            c->start = c->stop = 0;
441        }
442        else
443        {
444            c->start += ret;
445
446            if(c->stop - c->start + strlen(ANSI_PREFIX) + server->buflen
447                > OUTBUFFER)
448            {
449                /* Overflow! Empty buffer and start again */
450                memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
451                c->start = 0;
452                c->stop = strlen(ANSI_RESET);
453                return 0;
454            }
455
456            /* Need to move? */
457            if(c->stop + strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
458            {
459                memmove(c->outbuf, c->outbuf + c->start, c->stop - c->start);
460                c->stop -= c->start;
461                c->start = 0;
462            }
463
464            memcpy(c->outbuf + c->stop, ANSI_PREFIX, strlen(ANSI_PREFIX));
465            c->stop += strlen(ANSI_PREFIX);
466            memcpy(c->outbuf + c->stop, server->buffer, server->buflen);
467            c->stop += server->buflen;
468
469            return 0;
470        }
471    }
472
473    /* We no longer have backlog, send our new data */
474
475    /* Send ANSI prefix */
476    ret = nonblock_write(c->fd, ANSI_PREFIX, strlen(ANSI_PREFIX));
477    if(ret == -1)
478    {
479        if(errno == EAGAIN)
480            ret = 0;
481        else
482        {
483            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
484            return -1;
485        }
486    }
487
488    if(ret < (ssize_t)strlen(ANSI_PREFIX))
489    {
490        if(strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
491        {
492            /* Overflow! Empty buffer and start again */
493            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
494            c->start = 0;
495            c->stop = strlen(ANSI_RESET);
496            return 0;
497        }
498
499        memcpy(c->outbuf, ANSI_PREFIX, strlen(ANSI_PREFIX) - ret);
500        c->stop = strlen(ANSI_PREFIX) - ret;
501        memcpy(c->outbuf + c->stop, server->buffer, server->buflen);
502        c->stop += server->buflen;
503
504        return 0;
505    }
506
507    /* Send actual data */
508    ret = nonblock_write(c->fd, server->buffer, server->buflen);
509    if(ret == -1)
510    {
511        if(errno == EAGAIN)
512            ret = 0;
513        else
514        {
515            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
516            return -1;
517        }
518    }
519
520    if(ret < (int)server->buflen)
521    {
522        if(server->buflen > OUTBUFFER)
523        {
524            /* Overflow! Empty buffer and start again */
525            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
526            c->start = 0;
527            c->stop = strlen(ANSI_RESET);
528            return 0;
529        }
530
531        memcpy(c->outbuf, server->buffer, server->buflen - ret);
532        c->stop = server->buflen - ret;
533
534        return 0;
535    }
536
537    return 0;
538}
539
540ssize_t nonblock_write(int fd, void *buf, size_t len)
541{
542    size_t total = 0;
543    ssize_t ret;
544
545    while(total < len)
546    {
547        do
548        {
549            ret = write(fd, buf, len);
550        }
551        while(ret < 0 && errno == EINTR);
552
553        if(ret < 0)
554            return ret;
555        else if(ret == 0)
556            return total;
557
558        total += len;
559        buf = (void *)((uintptr_t)buf + len);
560    }
561
562    return total;
563}
564
Note: See TracBrowser for help on using the repository browser.