~psiphon-inc/psiphon/trunk

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
/*
 * Copyright (c) 2010, Psiphon Inc.
 * All rights reserved.
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdafx.h"
#include "locallistener.h"
#include "psiclient.h"

LocalListener::LocalListener(const string& IP, unsigned short port) :
    m_listenIP(IP), m_listenPort(port)
{
    m_listenSocket = -1;
}

LocalListener::~LocalListener(void)
{
    // close listening socket
    closesocket(m_listenSocket);
}

void LocalListener::Initialize(void)
{
    char sockopt;

    m_listenSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    m_sin.sin_family = AF_INET;
    m_sin.sin_port = htons(m_listenPort);
    if (INADDR_NONE == (m_sin.sin_addr.s_addr = inet_addr(m_listenIP.c_str())))
    {
        my_print(false, _T("inet_addr error: %s"), _tcserror(errno));
        throw 0;
    }

    sockopt = 1;
    setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt));

    /*
    // TODO: I don't think this is needed
    unsigned long opt = 1;
    if (ioctlsocket(m_listenSocket, FIONBIO, &opt) == SOCKET_ERROR)
    {
        my_print(false, _T("ioctlsocket error: %s"), _tcserror(errno));
        throw 0;
    }
    */

    m_sinlen = sizeof(m_sin);
    if (-1 == bind(m_listenSocket, (struct sockaddr *)&m_sin, m_sinlen))
    {
        my_print(false, _T("bind error: %s"), _tcserror(errno));
        throw 0;
    }

    if (-1 == listen(m_listenSocket, 2))
    {
        my_print(false, _T("listen error: %s"), _tcserror(errno));
        throw 0;
    }
 
    const char* x = inet_ntoa(m_sin.sin_addr);
    my_print(true,
             _T("waiting for TCP connection on %hs:%d..."),
             inet_ntoa(m_sin.sin_addr), ntohs(m_sin.sin_port));
}

void LocalListener::Accept(int& forwardSocket)
{
    forwardSocket = accept(m_listenSocket, (struct sockaddr *)&m_sin, &m_sinlen);
    if (-1 == forwardSocket)
    {
        my_print(false, _T("accept error: %d"), WSAGetLastError());
        throw 0;
    }
}

int LocalListener::ListenSocket(void)
{
    return m_listenSocket;
}