summaryrefslogtreecommitdiffstats
blob: 560bf7b23088fb2868231c3e6cf476585d138cd3 (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
/*
 * Copyright (c) 2010 Remko Tron¨on
 * Licensed under the GNU General Public License v3.
 * See Documentation/Licenses/GPLv3.txt for more information.
 */
/*
 * Copyright (c) 2010, Isode Limited, London, England.
 * All rights reserved.
 */
package com.isode.stroke.network;

import com.isode.stroke.network.DomainNameServiceQuery.Result;
import com.isode.stroke.signals.Signal1;
import com.isode.stroke.signals.SignalConnection;
import com.isode.stroke.signals.Slot;
import com.isode.stroke.signals.Slot1;
import com.isode.stroke.signals.Slot2;
import java.util.ArrayList;
import java.util.Collection;

public class Connector {

    public static Connector create(String hostname, DomainNameResolver resolver, ConnectionFactory connectionFactory, TimerFactory timerFactory) {
        return new Connector(hostname, resolver, connectionFactory, timerFactory);
    }

    public void setTimeoutMilliseconds(int milliseconds) {
        timeoutMilliseconds = milliseconds;
    }

    public void start() {
        assert currentConnection == null;
        assert serviceQuery == null;
        assert timer == null;
        queriedAllServices = false;
        serviceQuery = resolver.createServiceQuery("_xmpp-client._tcp." + hostname);
        serviceQuery.onResult.connect(new Slot1<Collection<DomainNameServiceQuery.Result>>() {
            public void call(Collection<Result> p1) {
                handleServiceQueryResult(p1);
            }
        });
        if (timeoutMilliseconds > 0) {
            timer = timerFactory.createTimer(timeoutMilliseconds);
            timer.onTick.connect(new Slot() {
                public void call() {
                    handleTimeout();
                }
            });
            timer.start();
        }
        serviceQuery.run();
    }

    public void stop() {
        finish(null);
    }

    public final Signal1<Connection> onConnectFinished = new Signal1<Connection>();

    private Connector(String hostname, DomainNameResolver resolver, ConnectionFactory connectionFactory, TimerFactory timerFactory) {
        this.hostname = hostname;
        this.resolver = resolver;
        this.connectionFactory = connectionFactory;
        this.timerFactory = timerFactory;
    }

    private void handleServiceQueryResult(Collection<Result> result) {
        serviceQueryResults = new ArrayList<Result>();
        serviceQueryResults.addAll(result);
        serviceQuery = null;
        tryNextServiceOrFallback();
    }

    private void handleAddressQueryResult(Collection<HostAddress> addresses, DomainNameResolveError error) {
      	//std::cout << "Connector::handleAddressQueryResult(): Start" << std::endl;
	addressQuery = null;
	if (error != null || addresses.isEmpty()) {
		if (!serviceQueryResults.isEmpty()) {
			serviceQueryResults.remove(0);
		}
		tryNextServiceOrFallback();
	}
	else {
		addressQueryResults = new ArrayList<HostAddress>();
                addressQueryResults.addAll(addresses);
		tryNextAddress();
	}
    }

    private void queryAddress(String hostname) {
        assert addressQuery == null;
        addressQuery = resolver.createAddressQuery(hostname);
        addressQuery.onResult.connect(new Slot2<Collection<HostAddress>, DomainNameResolveError>() {
            public void call(Collection<HostAddress> p1, DomainNameResolveError p2) {
                handleAddressQueryResult(p1, p2);
            }
        });
        addressQuery.run();
    }

    private void tryNextServiceOrFallback() {
        if (queriedAllServices) {
		//std::cout << "Connector::tryNextServiceOrCallback(): Queried all hosts. Error." << std::endl;
		finish(null);
	}
	else if (serviceQueryResults.isEmpty()) {
		//std::cout << "Connector::tryNextHostName(): Falling back on A resolution" << std::endl;
		// Fall back on simple address resolving
		queriedAllServices = true;
		queryAddress(hostname);
	}
	else {
		//std::cout << "Connector::tryNextHostName(): Querying next address" << std::endl;
		queryAddress(serviceQueryResults.get(0).hostname);
	}
    }

    private void tryNextAddress() {
       	if (addressQueryResults.isEmpty()) {
		//std::cout << "Connector::tryNextAddress(): Done trying addresses. Moving on" << std::endl;
		// Done trying all addresses. Move on to the next host.
		if (!serviceQueryResults.isEmpty()) {
			serviceQueryResults.remove(0);
		}
		tryNextServiceOrFallback();
	}
	else {
		//std::cout << "Connector::tryNextAddress(): trying next address." << std::endl;
		HostAddress address = addressQueryResults.get(0);
		addressQueryResults.remove(0);

		int port = 5222;
		if (!serviceQueryResults.isEmpty()) {
			port = serviceQueryResults.get(0).port;
		}

		tryConnect(new HostAddressPort(address, port));
	}
    }

    private void tryConnect(HostAddressPort target) {
       	assert currentConnection == null;
	//std::cout << "Connector::tryConnect() " << target.getAddress().toString() << " " << target.getPort() << std::endl;
	currentConnection = connectionFactory.createConnection();
	currentConnectionConnectFinishedConnection = currentConnection.onConnectFinished.connect(new Slot1<Boolean>() {
            public void call(Boolean p1) {
                handleConnectionConnectFinished(p1);
            }
        });

	currentConnection.connect(target);
    }

    private void handleConnectionConnectFinished(boolean error) {
        //std::cout << "Connector::handleConnectionConnectFinished() " << error << std::endl;
	currentConnectionConnectFinishedConnection.disconnect();
	if (error) {
		currentConnection = null;
		if (!addressQueryResults.isEmpty()) {
			tryNextAddress();
		}
		else {
			if (!serviceQueryResults.isEmpty()) {
				serviceQueryResults.remove(0);
			}
			tryNextServiceOrFallback();
		}
	}
	else {
		finish(currentConnection);
	}
    }

    private void finish(Connection connection) {
      	if (timer != null) {
		timer.stop();
		timer.onTick.disconnectAll();
		timer = null;
	}
	if (serviceQuery != null) {
		serviceQuery.onResult.disconnectAll();
		serviceQuery = null;
	}
	if (addressQuery != null) {
		addressQuery.onResult.disconnectAll();
		addressQuery = null;
	}
	if (currentConnection != null) {
		currentConnectionConnectFinishedConnection.disconnect();
		currentConnection = null;
	}
	onConnectFinished.emit(connection);
    }

    private void handleTimeout() {
        finish(null);
    }
    private String hostname;
    private DomainNameResolver resolver;
    private ConnectionFactory connectionFactory;
    private TimerFactory timerFactory;
    private int timeoutMilliseconds = 0;
    private Timer timer;
    private DomainNameServiceQuery serviceQuery;
    private ArrayList<DomainNameServiceQuery.Result> serviceQueryResults;
    private DomainNameAddressQuery addressQuery;
    private ArrayList<HostAddress> addressQueryResults;
    private boolean queriedAllServices = true;
    private Connection currentConnection;
    private SignalConnection currentConnectionConnectFinishedConnection;
}