summaryrefslogtreecommitdiffstats
path: root/libksirtet/lib/socket.cpp
blob: 9ef3ba3c37c3d51edceceb2640013724b7b63083 (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
#include "socket.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <sys/types.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#include <ctype.h>
#include <netdb.h>
#include <sys/utsname.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/ioctl.h>
#ifdef HAVE_SYS_FILIO_H
#include <sys/filio.h> // for FIONREAD
#endif

Socket::Socket(KExtendedSocket *s, bool createNotifier,
               QObject *parent, const char *name)
: _socket(s), _notifier(0)
{
    Q_ASSERT(s);
	if (createNotifier) {
		_notifier = new QSocketNotifier(s->fd(), QSocketNotifier::Read,
                                        parent, name);
		_notifier->setEnabled(FALSE);
	}
}

Socket::~Socket()
{
	delete _notifier;
    delete _socket;
}

bool Socket::write(const QByteArray &a)
{
	return ( _socket->writeBlock(a.data(), a.size())==(int)a.size() );
}

bool Socket::write()
{
	bool res = write(writing.buffer());
	writing.clear();
	return res;
}

int Socket::pendingData() const
{
	int size = 0;
	if ( ioctl(_socket->fd(), FIONREAD, (char *)&size)<0 ) return -1;
	return size;
}

int Socket::read()
{
	reading.clearRead();

	int size = pendingData();
	if ( size==-1 ) return -1;

	reading.device()->close();
	int dec = reading.size();
	reading.buffer().resize(dec + size);
	size = _socket->readBlock(reading.buffer().data() + dec, size);
	if ( size==-1 ) reading.buffer().resize(dec);
	reading.device()->open(IO_ReadOnly);

	return size;
}

int Socket::accept(KExtendedSocket *&s)
{
    return _socket->accept(s);
}