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

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