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

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