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

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