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

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