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

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