Git Product home page Git Product logo

pysctp's People

Contributors

domi007 avatar henryzhaoh avatar p1-bmu avatar p1-mmr avatar p1-ra avatar philpraxis avatar power47 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pysctp's Issues

InitChunk mod

Hello!

I would like to be able to modify some parameters of the InitChunk message

Is it possible to do this from the script? If not... can you tell me where this is defined in the source?

Thanks

SCTP keeps trying to socket-connect with a dummy IP for hours before it times out.

I am trying to use SCTP to transfer data between two parties, however, whenever my IPs are incorrect, it stuck. So I don't know if the protocol keeps listening till it finds the IP on the network and it will never time out.

OR when it gets stuck, that means there is a problem with the socket implementation approach or the protocol itself.

Looking forward to hearing your insights.

set_sndbuf doesn't work as expected

I'm at the very first stage of setting up an sctp connection between my application and a third party system. I'm getting ABORT with Invalid mandatory parameter cause in response to my INIT. At the same time, i have a working system and when comparing the pcaps the only differences in INIT phase are,

  1. Advertised receiver window credit / a_rwnd (mine is 106496 and the working one is 8192)
  2. ECN parameter (which is not present in working version)

I thought let's start from the simple one and set the a_rwnd which i believe should be the sndbuf, I tried setting it, like the following snippet code:

tcp = sctpsocket(socket.AF_INET, socket.SOCK_STREAM, None)
saddr = (server, tcpport)
 
print("TCP %r ----------------------------------------------" % (saddr, )) 

tcp.initparams.max_instreams = 17
tcp.initparams.num_ostreams = 17

tcp.events.clear()
tcp.events.data_io = 1
tcp.set_sndbuf(16384)

size = tcp.get_sndbuf()
print("Buffer size: %d" % size)

After getting the sndbuf, i can see its set to the same 16384 value (i believe based on comments it should be devised by 2) but anyhow the problem is in the pcap the value for a_rwnd is still 106496 and doesn't change.

So can anyone first help me understand if sndbuf would set the a_rwnd in the actual INIT or I'm completely wrong here, and if it is why after calling set_sndbuf the value in the INIT still showing the old value?

ppid field changed from 32 bits to 128 bits

When I set like this below
sctp_send(msg=data, ppid=60)
When I use wireshark parse the package
ppid will become 10^30

image

After that I go directly to the file _sctp.c and set ppid to 0x3c(60)

Py_BEGIN_ALLOW_THREADS
ppid = 0x3c;
size_sent = sctp_sendmsg(fd, msg, msg_len, (struct sockaddr*) psto, sto_len, ppid, 
			flags, stream, ttl, context);

Parsing the package with a wireshark will become like this

image image

ppid should be 32 bits, but it looks like 128 bits

Please help me to solve this problem
Thanks

Memory Leak?

Hello.
I have a program that sends data to SCTP, but there is one problem:
If I set into program tcp.settimeout (0.1) or tcp.setblocking (0), and when trying to read,
I get the error [Errno 11] Resource temporarily unavailable and formed Memory Leak?
But connection doesn't closed. Otherwise tcp.sctp_recv (2048) blocks the program
until it receives a packet.

Cannot install on ubuntu , _sctp.c:8:20: fatal error: Python.h: No such file or directory

here is the screenshot of the install:
sudo python setup.py install
[sudo] password for kahmed:
running install
running build
running build_py
creating build
creating build/lib.linux-i686-2.7
copying sctp.py -> build/lib.linux-i686-2.7
running build_ext
building '_sctp' extension
creating build/temp.linux-i686-2.7
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I. -I/usr/include -I/usr/include/python2.7 -c _sctp.c -o build/temp.linux-i686-2.7/_sctp.o
_sctp.c:8:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1

after i install :
sudo apt-get install libsctp-dev
and Change Makefile to reflect current Python version, i still get the same error:

Python version is 2.7.2

pysctp needs libsctp-dev

On Ubuntu 10.04. While running sudo python setup.py install I got an error message:

_sctp.c:11:26: error: netinet/sctp.h: No such file or directory

The problem is that the libsctp-dev package was not installed. Installing it fixed the problem.

sudo apt-get install libsctp-dev

Byte-ordering is incorrect when trying to use ppid attribute of sctp_send

When trying to use the ppid attribute, the integer value is sent over the wire with the byte order swapped from the correct value for the specified number.

For example, if I were to specify a PPID of 46 (the ppid of Diameter which in hex is 0x0000002e) in Python, the ppid that is sent over the wire is instead 771751936 (which in hex is 0x2e000000).

If I instead specified a ppid of 0x2e000000, the ppid sent over the wire is 46 (0x0000002e). This seems to indicate that a byte-ordering error is occurring between when the integer is specified in python and when it is sent over the wire.

ProcessLookupError: [Errno 3] No such process

Hi. Thank you for the project.

I am using pysctp in a project implementing a 5GC traffic generator. The library works fine, however when I increase the number of UEs hence the data rate I start getting the error below.

Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/ubuntu/core-tg/src/NGAPSim.py", line 261, in _ngap_to_ue_thread_function
    self.sctp.send(ngap_pdu.to_aper())
  File "/home/ubuntu/core-tg/src/SCTP.py", line 71, in send
    self.__socket.sctp_send(data, ppid=socket.htonl(60))
  File "/home/ubuntu/core-tg/.venv/lib/python3.8/site-packages/sctp.py", line 1178, in sctp_send
    return _sctp.sctp_send_msg(self._sk.fileno(), msg, to, ppid, flags, stream, timetolive, context)
ProcessLookupError: [Errno 3] No such process

I don't know where to start debugging. I also don't know if this is a limitation or bug with the package or with my implementation. I would appreciate any pointers. The SCTP.py is as below, you can find the project here

import socket
import logging
import sctp

logger = logging.getLogger('__SCTPClient__')

class SCTPClient():
    """ This class is a base class for all SCTP client contexts. """
    def __init__(self, server_config):
        try:
            self.__socket = self._load_socket()
        except:
            logger.exception("Failed to create socket")
            raise
            
        self.server_config = server_config['amfConfigs'][0]
        self.connect()

    def connect(self) -> None:
        logger.info("Connecting to 5G Core")
        logger.info("Server config: {}".format(self.server_config))
        self.__socket.connect((self.server_config['address'], self.server_config['port']))

    def disconnect(self) -> None:
        logger.info("Disconnecting from 5G Core")
        self.__socket.close()

    def _load_socket(self):
        # Create SCTP socket
        return sctp.sctpsocket_tcp(socket.AF_INET)

    def send(self, data: bytes):
        self.__socket.sctp_send(data, ppid=socket.htonl(60))

    def recv(self) -> bytes:
        if self.__socket._closed:
            return None
        sctp_data = self.__socket.recv(4096)
        if not sctp_data:
            logger.info('SCTP disconnection')
            return None
        return sctp_data

Thank you in advance

unable to run the code

the following error occur while running the client code:

:~/pysctp$ python client_1.py
Traceback (most recent call last):
File "client_1.py", line 2, in
import sctp
File "/home/prathamesh/pysctp/sctp.py", line 70, in
import _sctp
ImportError: No module named _sctp

following is the code:

import socket
import sctp

sk = sctp.sctpsocket_tcp (socket.AF_INET)
sk.connect (("127.0.0.1", 38412))

print ("Sending Message")

sk.sctp_send (msg = 'hello world')
sk.shutdown (0)

sk.close ()

send_failed() notification causes an AttributeError exception

The error occurs when the following conditions apply:

  • subscribing to SCTP_SEND_FAILED notifications
  • attempting to send a message to a peer that has become unavailable, e.g. due to a crash

The offending code is in line 392 of sctp.py, in the init method of the send_failed class:

del values._info

which should read

del self._info

SCTP payload protocol ID argument issue

I found a small bug in your program. The problem is sctp_sendmsg used in the sctp_send_msg() method in the _sctp.c file. You directly pass ppid through sctp to cause the value of ppid to be wrong. You should use htonl(ppid), so there is no problem.

Source address and add new address

Hello, who can tell me how to set a new source address, and how to add new addresses to the created association so that they can be seen by the remote party? Thank you in advance

The Makefile must be manually edited with the current python version number

The Makefile has a variable, PYTHON_VERSION, which must be edited to be the version number of python on this system. It should be documented in the README that you have to do that before you can install pysctp.

This is a consequence of python's "scorched earth" policy concerning backwards compatibility.

IOError: [Errno 11] Resource temporarily unavailable

my system: ubuntu16.04; PyCharm; python2.7.12; virtualenv;
when test sctp connect, this error occurred to me:

Traceback (most recent call last):
File "/home/test/Downloads/pycharm-community-2017.1.1/helpers/pydev/pydevd.py", line 1578, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/home/test/Downloads/pycharm-community-2017.1.1/helpers/pydev/pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/home/test/PycharmProjects/sctp_socket/server.py", line 215, in <module>
someone access:  ('127.0.0.1', 50750)
    fromaddr, flags, msg, notif = conn_sock.sctp_recv(BUFSIZE)
  File "/home/test/sctp_env/local/lib/python2.7/site-packages/sctp.py", line 1206, in sctp_recv
    (fromaddr, flags, msg, _notif) = _sctp.sctp_recv_msg(self._sk.fileno(), maxlen)
IOError: [Errno 11] Resource temporarily unavailable

but it's OK in terminal:

(sctp_env) test@ubuntu:~/PycharmProjects/sctp_socket$ python server.py

my server code:

import sctp

HOST = ''
PORT = 3868
BUFSIZE = 2048
ADDR = (HOST, PORT)

socket_serv = sctp.sctpsocket_tcp(socket.AF_INET)  # , sctp.IPPROTO_SCTP

socket_serv.initparams.max_instreams = 3
socket_serv.initparams.num_ostreams = 3

socket_serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_serv.bindx([ADDR])
socket_serv.listen(5)
socket_serv.setblocking(1)
socket_serv.events.data_io = 1
socket_serv.events.clear()

while True:
    conn_sock, addr = socket_serv.accept()
    print 'someone access:  ', addr
    msg = ''
    while True:
        fromaddr, flags, msg, notif = conn_sock.sctp_recv(BUFSIZE)
        if not msg:
            print 'msg == 0!!'
            break
        print 'recv: %s' % msg
        
    conn_sock.close()
socket_serv.close()

client.py:

import sctp
from sctp import *

server = "localhost"
tcpport = 3868

if _sctp.getconstant("IPPROTO_SCTP") != 132:
    raise "getconstant failed"
client_sock = sctpsocket(socket.AF_INET, socket.SOCK_STREAM, None)
saddr = (server, tcpport)
client_sock.initparams.max_instreams = 3
client_sock.initparams.num_ostreams = 3
client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client_sock.setblocking(0)
client_sock.events.clear()
client_sock.events.data_io = 1
client_sock.connect(saddr)

while 1:
    while True:
        data = raw_input('INPUT: ')
        if not data:
            break
        client_sock.sctp_send(data)
        fromaddr, flags, msg, notif = client_sock.sctp_recv(1024)
        print "%s____" % msg
    break
client_sock.close()

Error occurred in line: fromaddr, flags, msg, notif = conn_sock.sctp_recv(BUFSIZE)
please tell me why does this Error come out...THX

undefined symbol: PyString_FromStringAndSize

version:
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux

import sctp
Traceback (most recent call last):
File "", line 1, in
File "/home/labuser/framework/my_env/lib/python3.5/site-packages/sctp.py", line 55, in
import _sctp
ImportError: /home/labuser/framework/my_env/lib/python3.5/site-packages/_sctp.cpython-35m-x86_64-linux-gnu.so: undefined symbol: PyString_FromStringAndSize

getting this error inspite of installing the dependencies

The sent packet cannot be parsed by wireshark

The sent packet cannot be parsed by wireshark, indicating that the length of the data in the data chunk in sctp is incorrect.
I use sctp to send a package of ngap protocol that can be parsed by the server, but cannot be resolved by wireshark. After checking the normal package and the error package, I found that the sent packet was not the correct length and could not be parsed. I look at the sctp source code, it is necessary to set the length of the packet when sending the packet. But I didn't find a place to set the parameters in your sctp_send() method.
client:
`python
import _sctp
from sctp import *
from ngap import *

import binascii

server = '127.0.0.1'
sctpport = 2904

if _sctp.getconstant("IPPROTO_SCTP") != 132:
raise ("getconstant failed")
client_sock = sctpsocket(socket.AF_INET, socket.SOCK_STREAM, None)
client_sock.set_sndbuf(10000)
saddr = (server, sctpport)

print("SCTP", saddr, "------------------------------------------")

client_sock.initparams.max_instreams = 3
client_sock.initparams.num_ostreams = 3

client = server
cport = 2901

caddr = (client, cport)
client_sock.bindx([caddr])
client_sock.events.clear()
client_sock.events.data_io = 1
client_sock.connect(saddr)
PDU = NGAP_PDU_Descriptions.NGAP_PDU
IEs = []
IEs.append({'id': 27, 'criticality': 'reject', 'value': (
'GlobalRANNodeID', ('globalGNB-ID', {'pLMNIdentity': b'\x02\xf8\x98', 'gNB-ID': ('gNB-ID', (513, 32))}))}
)
IEs.append({'id': 82, 'criticality': 'reject', 'value': ('RANNodeName', 'test gNB')}
)
IEs.append({'id': 21, 'criticality': 'reject', 'value': ('PagingDRX', 'v128')})
IEs.append({'id': 102, 'criticality': 'reject', 'value': ('SupportedTAList', [{'tAC': b'\x01\x00\x01',
'broadcastPLMNList': [
{'pLMNIdentity': b'\x02\xf8\x98',
'tAISliceSupportList': [{
's-NSSAI': {
'sST': b'\x01',
'sD': b'\x00\x00d'}},
{
's-NSSAI': {
'sST': b'\x02',
'sD': b'\x00\x00d'}},
{
's-NSSAI': {
'sST': b'\x03',
'sD': b'\x00\x00d'}}]}]}])}
)
val = (
'initiatingMessage',
{'procedureCode': 21, 'criticality': 'reject', 'value': ('NGSetupRequest', {'protocolIEs': IEs})})
PDU.set_val(val)
client_sock.sctp_send(PDU.to_aper())
fromaddr, flags, msg, notif = client_sock.sctp_recv(2048)
print('%s__' % msg)
print(client_sock.get_sndbuf())
server:python
import socket
import sctp
from time import ctime
from ngap import *
from binascii import unhexlify

HOST = ''
PORT = 2904
BUFSIZE = 2048
ADDR = (HOST, PORT)

socket_serv = sctp.sctpsocket(socket.AF_INET, socket.SOCK_STREAM, None)
socket_serv.initparams.max_instreams = 3
socket_serv.initparams.num_ostreams = 3

socket_serv.bindx([ADDR])
socket_serv.listen(5)
socket_serv.events.data_io = 1
socket_serv.events.clear()
PDU = NGAP_PDU_Descriptions.NGAP_PDU

while True:
print('Waiting for user connecting')
conn_sock, addr = socket_serv.accept()
print('connecting:', addr)
msg = ''
while True:
fromaddr, flags, msg, notif = conn_sock.sctp_recv(maxlen=512)
PDU.from_aper(msg)
print(PDU.to_asn1())

    conn_sock.sctp_send(msg)
conn_sock.get_autoclose()

`

pypi version 0.7 is outdated

Hi there,
just want to ask if you plan to update pip3 people at some point. Version there is outdated and suffers with randomly "echo" already received traffic. New version from git is totally ok.

Thanks,
Ales

No luck after installing on Mac (OS X 10.6.8)

I've been playing around for the past couple hours trying to get this working on my Mac.

I've installed the SCTP libs from http://sctp.fh-muenster.de/index.html and I can build & install just fine but I keep running into socket.error: [Errno 43] Protocol not supported any time I try to instantiate an sctpsocket instance.

Traceback (most recent call last):
  File "test_local_cnx.py", line 24, in <module>
    tcp = sctpsocket_tcp(socket.AF_INET)
  File "sctp.py", line 1659, in __init__
    sctpsocket.__init__(self, family, TCP_STYLE, sk)
  File "sctp.py", line 1012, in __init__
    sk = socket.socket(family, style, IPPROTO_SCTP)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 182, in __init__
    _sock = _realsocket(family, type, proto)
socket.error: [Errno 43] Protocol not supported

sctp_recv read same packet continuously

I have developed a client server program where multiple clients connect to server and exchange sctp packets.
clients are places in one Virtual machine (VirtualBox) and Server is in another virtual machine, and interface is configured as host-only interface.

Environment

uname -a

Linux ucc1 3.10.27-1.el6.elrepo.x86_64 #1 SMP Thu Jan 16 15:56:52 EST 2014 x86_64 x86_64 x86_64 GNU/Linux

rpm -q lksctp-tools

lksctp-tools-1.0.10-7.el6.x86_64

two strange problems i am facing

  1. all of a sudden sctp_recv keeps receiving same package indefinitely.
  2. Some packets sent earlier get sent again and again randomly.

Any comments much appreciated.

[Query] Received data len from sctp_recv API

Hi,
I am using sctp_recv() API of the sctpsocket class in my server-client program.
Can you please let me know to know the length of the received data from the API sctp_recv()?

Thanks

_sctp.h goes in the wrong place

The Makefile that builds the _sctp.o file puts the _sctp.h in /usr/local. This isn't a problem for building/installing pysctp, but it's the wrong place: it should go in /usr/local/include so that other software can find it.

Method for specifying the Payload Protocol Identifier for Data Chunk?

SCTP provides a payload protocol identifier field for the data chunk which marks the application layer protocol being transmitted over SCTP. When using pySCTP to provide an SCTP server it currently defaults to 0, meaning unspecified. Is there a way to set this value so that messages sent as part of a given communication will be tagged with the correct payload protocol identifier?

Issue Ubuntu 14.04 kernel version 4.2.0-27-generic

does pysctp support for following configuration?
Ubuntu 14.04
kernel version 4.2.0-27-generic
python 3.4.3

when I run "sudo python setup.py install --dry-run" I see following errors

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

when I run "sudo ./test_local_cnx.py" I see following errors

ImportError: /home/hanuma/pysctp/pysctp/_sctp.so: undefined symbol: _Py_FalseStruct

can some body help me ?

Weird race condition between accept() and sctp_recvmsg()

On the python process I'm seeing an EINVAL returned by sctp_recvmsg() just after accept(). Here's the strace output for the same

epoll_wait(22, {{EPOLLIN, {u32=3, u64=41313874535776259}}}, 1023, 5000) = 1
accept(3, {sa_family=AF_INET, sin_port=htons(48385), sin_addr=inet_addr("127.0.0.1")}, [16]) = 23
getsockopt(23, 0x84 /* SOL_??? */, 2, "\3\0\3\0\10\0\10\0", [8]) = 0
getsockopt(23, 0x84 /* SOL_??? */, 11, "\1\0\0\0\0\0\0\0\0\0", [10]) = 0
recvmsg(23, 0x7ffeef79aad0, MSG_OOB|MSG_PEEK|MSG_DONTROUTE|MSG_CTRUNC|MSG_TRUNC|MSG_DONTWAIT|MSG_EOR|MSG_WAITALL|MSG_FIN|MSG_SYN|MSG_CONFIRM|MSG_RST|MSG_ERRQUEUE|MSG_NOSIGNAL|MSG_MORE|MSG_WAITFORONE|MSG_FASTOPEN|MSG_CMSG_CLOEXEC|0x9ffe0010) = -1 EINVAL (Invalid argument)

For now the workaround is to try again some more times if you receive an EINVAL.

"utf-8" decoding

SCTP library is using "UTF-8" to decode the received massage from the socket. So what if I wanna use different decoding algorithm, is it possible to modify that within the hard coding of the library?

sctp_send, error message too long

Hi when i will try send one file or other data more than 400KB i got Error Message too long. How i can send more data with this library. Do you have work example with big files or big binary data sending ?

bindx doesn't work with more than one address

Giving a list with more than one address tupel to sctpsocket_tcp.bindx() results in an OSError: [Errno 22] Invalid argument.

I looked into the _sctp.c library and apparently the parsing into saddrs fails.

I created some prints in _sctp.c:

static PyObject* bindx(PyObject* dummy, PyObject* args)
{
	PyObject* ret = 0;
	int fd;
	PyObject* addrs;
	struct sockaddr saddr;
	struct sockaddr* saddrs;
	int saddr_len, saddrs_len;
	int addrcount;
	int flags;
	int x;

	if (! PyArg_ParseTuple(args, "iOi", &fd, &addrs, &flags)) {
		return ret;
	}

	if (! PySequence_Check(addrs)) {
		PyErr_SetString(PyExc_ValueError, "Second parameter must be a sequence of address/port tuples");
		return ret;
	}

	addrcount = PySequence_Length(addrs);
	if (addrcount <= 0) {
		PyErr_SetString(PyExc_ValueError, "Second parameter must be a non-empty sequence");
		return ret;
	}

	saddrs_len = 0;
	saddrs = (struct sockaddr*) malloc(saddrs_len);

	for(x = 0; x < addrcount; ++x) {
		const char* caddr;
		int iport;

		printf("###################################\n");
		printf("caddr: %d\n", *caddr);
		printf("iport: %d\n", iport);

		PyObject* otuple = PySequence_GetItem(addrs, x);

		if (! PyArg_ParseTuple(otuple, "si", &caddr, &iport)) {
			free(saddrs);
			return ret;
		}
		
		if (! to_sockaddr(caddr, iport, &saddr, &saddr_len)) {
			PyErr_Format(PyExc_ValueError, "Invalid address: %s", caddr);
			free(saddrs);
			return ret;
		}

		if (saddr_len == 0) {
			PyErr_Format(PyExc_ValueError, "Invalid address family: %s", caddr);
			free(saddrs);
			return ret;
		}

		saddrs = realloc(saddrs, saddrs_len + saddr_len);
		memcpy( ((char*) saddrs) + saddrs_len, &saddr, saddr_len);
		saddrs_len += saddr_len;
	}
	printf("***************************************************\n");
	printf("sa_data 0: %s sa_family 0: %d\n", saddrs[0].sa_data, saddrs[0].sa_family);
	printf("sa_data 1: %s sa_family 1: %d\n", saddrs[1].sa_data, saddrs[1].sa_family);
	printf("sa_data 2: %s sa_family 2: %d\n", saddrs[2].sa_data, saddrs[2].sa_family);
	printf("sa_data 3: %s sa_family 3: %d\n", saddrs[3].sa_data, saddrs[3].sa_family);
	printf("fd: %d\n", fd);
	printf("addrcount: %d\n", addrcount);
	printf("flags: %d\n", flags);
	if (sctp_bindx(fd, saddrs, addrcount, flags)) {
		PyErr_SetFromErrno(PyExc_IOError);
	} else {
		ret = Py_None; Py_INCREF(ret);
	}

	free(saddrs);
	return ret;
}

For example, giving the addresses:

addresses.append(("127.0.0.1", 10000))
addresses.append(("127.0.0.2", 10001))
addresses.append(("127.0.0.3", 10002))
addresses.append(("127.0.0.4", 10003))

results in the following command line output:

###################################
caddr: 1
iport: 21956
###################################
caddr: 49
iport: 10000
###################################
caddr: 49
iport: 10001
###################################
caddr: 49
iport: 10002
***************************************************
sa_data 0: ' sa_family 0: 2
sa_data 1: ' sa_family 1: 2
sa_data 2: ' sa_family 2: 2
sa_data 3: ' sa_family 3: 2
fd: 3
addrcount: 4
flags: 1

All Python threads hang if one of them blocks on a recv/send

In a multi-threaded Python application if one of the threads calls send or recv on a sctp socket, all the threads hang. This is because of the Python GIL (global interpreter lock) not being released by the C module's code.

The issue can be fixed by releasing the lock before the blocking calls to sctp_sendmsg and sctp_recvmsg, patch follows:

diff --git a/_sctp.c b/_sctp.c
index 3ad048d..ec68fc9 100644
--- a/_sctp.c
+++ b/_sctp.c
@@ -1411,8 +1411,10 @@ static PyObject* sctp_send_msg(PyObject* dummy, PyObject* args)
                }
        }

+       Py_BEGIN_ALLOW_THREADS
        size_sent = sctp_sendmsg(fd, msg, msg_len, (struct sockaddr*) psto, sto_len, ppid, 
                                        flags, stream, ttl, context);
+       Py_END_ALLOW_THREADS

        if (size_sent < 0) {
                PyErr_SetFromErrno(PyExc_IOError);
@@ -1564,7 +1566,9 @@ static PyObject* sctp_recv_msg(PyObject* dummy, PyObject* args)
        bzero(&sfrom, sizeof(sfrom));
        bzero(&sinfo, sizeof(sinfo));

+       Py_BEGIN_ALLOW_THREADS
        size = sctp_recvmsg(fd, msg, max_len, (struct sockaddr*) &sfrom, &sfrom_len, &sinfo, &flags);
+       Py_END_ALLOW_THREADS                                                                                                                                                                                        

        if (size < 0) {                                                                                                                                                                                             
                free(msg);                                                                                                                                                                                          

create a 0.6.1 release

thanks for the latest fixes, highly appreciated!

I just created an arch-linux AUR package for this but had to use a specific commit from the master as a source. Would be much cooler, if you could just release a .1 release of the 0.6 with all fixes included!

Best regards

Ruben

Unable to install pysctp

I cloned the repo ran sudo python3 setup.py install

I get the following error, can someone please help me to debug it?

running install
running bdist_egg
running egg_info
writing pysctp.egg-info/PKG-INFO
writing dependency_links to pysctp.egg-info/dependency_links.txt
writing top-level names to pysctp.egg-info/top_level.txt
reading manifest file 'pysctp.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'TODO'
writing manifest file 'pysctp.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
running build_ext
building '_sctp' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include -I/usr/include/python3.6m -c _sctp.c -o build/temp.linux-x86_64-3.6/_sctp.o
_sctp.c:24:10: fatal error: netinet/sctp.h: No such file or directory
 #include <netinet/sctp.h>
          ^~~~~~~~~~~~~~~~
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

I have install python-dev and python3-dev
any help would be appreciated

How to install pysctp on windows 7

Hi,

I am trying to install pysctp on windows 7. I have python 2.7.8 installed.
D:\userdata\rkommine\Desktop\pysctp-0.6>python --version
Python 2.7.8

When I download the pysctp-0.6.tar.gz & extracted it & run the following command:
D:\userdata\rkommine\Desktop\pysctp-0.6>python setup.py install
running install
running build
running build_py
creating build
creating build\lib.win32-2.7
copying sctp.py -> build\lib.win32-2.7
running build_ext
building '_sctp' extension
error: Unable to find vcvarsall.bat

Could you please help how to install this modules on windows?

Thanks in advance.

Regards,
Ramakrishna

CI/CD publishing to PyPi

Hi Benoit,

I have seen you already started with CI/CD publishing of pycrate wheel to pypi. Thank you very much for that! I was wondering if you would be open to do it for this project as well? It would be much more convenient to have the binary wheels on pypi instead of just the source code, so server installation could be simplified (no need to maintain local builds or install gcc and headers onto servers).
I would be happy to contribute a simplified CI/CD yaml file for this project based on what you have in pycrate (https://github.com/P1sec/pycrate/blob/master/.github/workflows/cicd.yml), but it would still need your token to Pypi set in this project, so first I wanted to know if you would be open to support this?
Simplified would mean: rip out everything there is for Windows and Mac (?) because AFAIR pysctp is Linux only, and adjust tests etc.

Thanks,
Domi

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.