source: libcaca/trunk/caca/driver_network.c @ 611

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