aboutsummaryrefslogtreecommitdiff
path: root/netclient.c
blob: 3a024cdaa7118b47de97cfdbcf0f2905d4ee4da3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/* --------------------------  netclient  ------------------------------------- */
/*                                                                              */
/* Extended 'netsend', connects to 'netserver'.                                 */
/* Uses child thread to connect to server. Thus needs pd0.35-test17 or later.   */
/* Written by Olaf Matthes (olaf.matthes@gmx.de)                                */
/* Get source at                                                                */
/* http://pure-data.svn.sourceforge.net/viewvc/pure-data/trunk/externals/maxlib/src/netclient.c */
/* March 26 2010                                                                */
/* Additional fixes and improvements by Ivica Ico Bukvic <ico@bukvic.net>       */
/* for the purpose of L2Ork http://l2ork.music.vt.edu                           */
/* This program is free software; you can redistribute it and/or                */
/* modify it under the terms of the GNU General Public License                  */
/* as published by the Free Software Foundation; either version 2               */
/* of the License, or (at your option) any later version.                       */
/*                                                                              */
/* This program is distributed in the hope that it will be useful,              */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of               */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                */
/* GNU General Public License for more details.                                 */
/*                                                                              */
/* You should have received a copy of the GNU General Public License            */
/* along with this program; if not, write to the Free Software                  */
/* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.  */
/*                                                                              */
/* Based on PureData by Miller Puckette and others.                             */
/*                                                                              */
/* ---------------------------------------------------------------------------- */
/* Changes: use circular message buffer for receive */
/*          using pollfunction instead of clock (suggested by HCS) */

#include "m_pd.h"
#include "s_stuff.h"
#include "m_imp.h"

#include <sys/types.h>
#include <string.h>
#include <pthread.h>
#ifdef WIN32
#include <winsock.h>
#else
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#define SOCKET_ERROR -1
#endif

#define INBUFSIZE 4096	/* maximum numbers of characters to read */

static char *version = "netclient v0.3.1, written by Olaf Matthes <olaf.matthes@gmx.de>";

static t_class *netclient_class;
static t_binbuf *inbinbuf;
static int netclient_instance_count;

typedef struct _netclient
{
    t_object x_obj;
	t_clock *x_clock;
	t_outlet *x_outdata;
	t_outlet *x_outconnect;
    int x_fd;
	char *x_hostname;
	int x_connectstate;
	int x_port;
    int x_protocol;
	char x_inbuf[INBUFSIZE];	/* circular message buffer for received data */
	int x_intail;
	int x_inhead;
		/* multithread stuff */
	pthread_t x_threadid;            /* id of child thread */
	pthread_attr_t x_threadattr;     /* attributes of child thread */
} t_netclient;

	/* one lonely prototype */
static void netclient_rcv(t_netclient *x);


	/* gets called when connection status has changed */
static void netclient_tick(t_netclient *x)
{
    outlet_float(x->x_outconnect, x->x_connectstate);
    /* add pollfunction for checking for input */
	if (x->x_connectstate == 1)
    {
        sys_addpollfn(x->x_fd, (t_fdpollfn)netclient_rcv, x);
    }
}

static void *netclient_child_connect(void *w)
{
	t_netclient *x = (t_netclient*) w;
    struct sockaddr_in server;
    struct hostent *hp;
    int sockfd;
    int portno = x->x_port;
    if (x->x_fd >= 0)
    {
    	error("netclient_connect: already connected");
    	return (x);
    }

    	/* create a socket */
    sockfd = socket(AF_INET, x->x_protocol, 0);
#if 0
    fprintf(stderr, "send socket %d\n", sockfd);
#endif
    if (sockfd < 0)
    {
    	sys_sockerror("socket");
    	return (x);
    }
		/* connect socket using hostname provided in command line */
    server.sin_family = AF_INET;
    hp = gethostbyname(x->x_hostname);
    if (hp == 0)
    {
		post("bad host?\n");
		return (x);
    }
    memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);

		/* assign client port number */
    server.sin_port = htons((u_short)portno);

    post("connecting to port %d", portno);
		/* try to connect */
    if (connect(sockfd, (struct sockaddr *) &server, sizeof (server)) < 0)
    {
    	sys_sockerror("connecting stream socket");
    	sys_closesocket(sockfd);
    	return (x);
    }
    x->x_fd = sockfd;
		/* outlet_float is not threadsafe ! */
    // outlet_float(x->x_obj.ob_outlet, 1);
	x->x_connectstate = 1;
		/* use callback instead to set outlet */
	clock_delay(x->x_clock, 0);
	return (x);
}

static void netclient_connect(t_netclient *x, t_symbol *hostname,
    t_floatarg fportno)
{
		/* we get hostname and port and pass them on
		to the child thread that establishes the connection */
	x->x_hostname = hostname->s_name;
	x->x_port = fportno;
	x->x_connectstate = 0;
		/* start child thread */
	if(pthread_create( &x->x_threadid, &x->x_threadattr, netclient_child_connect, x) < 0)
		post("netclient: could not create new thread");
}

static void netclient_disconnect(t_netclient *x)
{
    if (x->x_fd >= 0)
    {
        sys_rmpollfn(x->x_fd);
        sys_closesocket(x->x_fd);
        x->x_fd = -1;
        x->x_connectstate = 0;
        //outlet_float(x->x_outconnect, 0);
        clock_delay(x->x_clock, 0); /* output connect state later */
   }
}

static void netclient_send(t_netclient *x, t_symbol *s, int argc, t_atom *argv)
{
    if (x->x_fd >= 0)
    {
	t_binbuf *b = binbuf_new();
	char *buf, *bp;
	int length, sent;
	t_atom at;
	binbuf_add(b, argc, argv);
	SETSEMI(&at);
	binbuf_add(b, 1, &at);
	binbuf_gettext(b, &buf, &length);
	for (bp = buf, sent = 0; sent < length;)
	{
	    static double lastwarntime;
	    static double pleasewarn;
	    double timebefore = sys_getrealtime();
    	    int res = send(x->x_fd, buf, length-sent, 0);
    	    double timeafter = sys_getrealtime();
    	    int late = (timeafter - timebefore > 0.005);
    	    if (late || pleasewarn)
    	    {
    	    	if (timeafter > lastwarntime + 2)
    	    	{
    	    	     post("netclient blocked %d msec",
    	    	     	(int)(1000 * ((timeafter - timebefore) + pleasewarn)));
    	    	     pleasewarn = 0;
    	    	     lastwarntime = timeafter;
    	    	}
    	    	else if (late) pleasewarn += timeafter - timebefore;
    	    }
    	    if (res <= 0)
    	    {
    		sys_sockerror("netclient");
    		netclient_disconnect(x);
    		break;
    	    }
    	    else
    	    {
    		sent += res;
    		bp += res;
    	    }
	}
	t_freebytes(buf, length);
	binbuf_free(b);
    }
    else error("netclient: not connected");
}

    /* this is in a separately called subroutine so that the buffer isn't
    sitting on the stack while the messages are getting passed. */
static int netclient_doread(t_netclient *x)
{
    char messbuf[INBUFSIZE], *bp = messbuf;
    int indx;
    int inhead = x->x_inhead;
    int intail = x->x_intail;
    char *inbuf = x->x_inbuf;
    if (intail == inhead) return (0);
    for (indx = intail; indx != inhead; indx = (indx+1)&(INBUFSIZE-1))
    {
    	char c = *bp++ = inbuf[indx];
    	if (c == ';' && (!indx || inbuf[indx-1] != '\\'))
    	{
    	    intail = (indx+1)&(INBUFSIZE-1);
    	    binbuf_text(inbinbuf, messbuf, bp - messbuf);
    	    x->x_inhead = inhead;
    	    x->x_intail = intail;
    	    return (1);
    	}
    }
    return (0);
}

static void netclient_rcv(t_netclient *x)
{
	int fd = x->x_fd;
	int ret;
	fd_set readset;
	fd_set exceptset;
    struct timeval ztout;
		/* output data */
    int msg, natom;
    t_atom *at;
	
	if(x->x_connectstate)
	{
			/* check if we can read/write from/to the socket */
		FD_ZERO(&readset);
		FD_ZERO(&exceptset);
		FD_SET(fd, &readset );
		FD_SET(fd, &exceptset );

		ztout.tv_sec = 0;
		ztout.tv_usec = 0;
		ret = select(fd+1, &readset, NULL, &exceptset, &ztout);
		if(ret < 0)
		{
			error("netclient: can not read from socket");
            //sys_closesocket(fd);
            netclient_disconnect(x);
			return;
		}
		if(FD_ISSET(fd, &readset) || FD_ISSET(fd, &exceptset))
		{
			int readto = (x->x_inhead >= x->x_intail ? INBUFSIZE : x->x_intail-1);

			ret = recv(fd, x->x_inbuf + x->x_inhead, readto - x->x_inhead, 0);
			if (ret < 0)
			{
				sys_sockerror("recv");
                //sys_rmpollfn(fd);
                //sys_closesocket(fd);
                netclient_disconnect(x);
			}
			else if (ret == 0)
			{
	    		post("netclient: connection closed on socket %d", fd);
				//sys_rmpollfn(fd);
	    		//sys_closesocket(fd);
                netclient_disconnect(x);
			}
			else
			{
    			x->x_inhead += ret;
    			if (x->x_inhead >= INBUFSIZE) x->x_inhead = 0;
    			while (netclient_doread(x))
				{
					/* output binbuf */
					natom = binbuf_getnatom(inbinbuf);	/* get number of atoms */
					at = binbuf_getvec(inbinbuf);	/* get the atoms */
						/* now split it into several parts at every A_SEMI because
						   we probably received more than one message at a time     */
					for (msg = 0; msg < natom;)
					{
    					int emsg;
						for (emsg = msg; emsg < natom && at[emsg].a_type != A_COMMA
							&& at[emsg].a_type != A_SEMI; emsg++);

						if (emsg > msg)
						{
							int ii;
							for (ii = msg; ii < emsg; ii++)
	    						if (at[ii].a_type == A_DOLLAR || at[ii].a_type == A_DOLLSYM)
								{
	    							pd_error(x, "netserver: -- got dollar sign in message");
									goto nodice;
								}
							if (at[msg].a_type == A_FLOAT)
							{
	    						if (emsg > msg + 1)
									outlet_list(x->x_outdata, 0, emsg-msg, at + msg);
								else outlet_float(x->x_outdata, at[msg].a_w.w_float);
							}
							else if (at[msg].a_type == A_SYMBOL)
	    						outlet_anything(x->x_outdata, at[msg].a_w.w_symbol,
								emsg-msg-1, at + msg + 1);
						}
						nodice:
    						msg = emsg + 1;
					}
 	    		}
			}
		}
	}
	else post("netclient: not connected");
}

static void *netclient_new(t_floatarg udpflag)
{
    t_netclient *x = (t_netclient *)pd_new(netclient_class);
    x->x_outdata = outlet_new(&x->x_obj, &s_anything);	/* received data */
    x->x_outconnect = outlet_new(&x->x_obj, &s_float);	/* connection state */
    x->x_clock = clock_new(x, (t_method)netclient_tick);
    if(netclient_instance_count == 0)
        inbinbuf = binbuf_new();
    x->x_fd = -1;
    x->x_protocol = (udpflag != 0 ? SOCK_DGRAM : SOCK_STREAM);
		/* prepare child thread */
    if(pthread_attr_init(&x->x_threadattr) < 0)
       post("netclient: warning: could not prepare child thread" );
    if(pthread_attr_setdetachstate(&x->x_threadattr, PTHREAD_CREATE_DETACHED) < 0)
       post("netclient: warning: could not prepare child thread" );
	netclient_instance_count++;
    return (x);
}

static void netclient_free(t_netclient *x)
{
    netclient_disconnect(x);
    clock_free(x->x_clock);
	netclient_instance_count--;
    if(netclient_instance_count == 0)
        binbuf_free(inbinbuf);
}

#ifndef MAXLIB
void netclient_setup(void)
{
    netclient_class = class_new(gensym("netclient"), (t_newmethod)netclient_new,
    	(t_method)netclient_free,
    	sizeof(t_netclient), 0, A_DEFFLOAT, 0);
    class_addmethod(netclient_class, (t_method)netclient_connect, gensym("connect"), A_SYMBOL, A_FLOAT, 0);
    class_addmethod(netclient_class, (t_method)netclient_disconnect, gensym("disconnect"), 0);
    class_addmethod(netclient_class, (t_method)netclient_send, gensym("send"), A_GIMME, 0);
	class_addmethod(netclient_class, (t_method)netclient_rcv, gensym("receive"), 0);
	class_addmethod(netclient_class, (t_method)netclient_rcv, gensym("rcv"), 0);
    
	post(version);
}
#else
void maxlib_netclient_setup(void)
{
    netclient_class = class_new(gensym("maxlib_netclient"), (t_newmethod)netclient_new,
    	(t_method)netclient_free,
    	sizeof(t_netclient), 0, A_DEFFLOAT, 0);
	class_addcreator((t_newmethod)netclient_new, gensym("netclient"), A_DEFFLOAT, 0);
    class_addmethod(netclient_class, (t_method)netclient_connect, gensym("connect"), A_SYMBOL, A_FLOAT, 0);
    class_addmethod(netclient_class, (t_method)netclient_disconnect, gensym("disconnect"), 0);
    class_addmethod(netclient_class, (t_method)netclient_send, gensym("send"), A_GIMME, 0);
	class_addmethod(netclient_class, (t_method)netclient_rcv, gensym("receive"), 0);
	class_addmethod(netclient_class, (t_method)netclient_rcv, gensym("rcv"), 0);
    class_sethelpsymbol(netclient_class, gensym("maxlib/netclient-help.pd"));
}
#endif