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

Last change on this file since 4330 was 3495, checked in by Sam Hocevar, 10 years ago

Add caca_export_area_to_memory() to export only a selected part of the
current canvas. This is useful to export dirty rectangles. Accordingly,
add caca_import_area_from_memory() and caca_import_area_from_file().

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