summaryrefslogtreecommitdiffstats
blob: 282367923d1ed39f9959d30422828743a4ffe7ec (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
/*
 * Copyright (c) 2010-2016, Isode Limited, London, England.
 * All rights reserved.
 */
/*
 * Copyright (c) 2010 Remko Tronçon
 * All rights reserved.
 */
package com.isode.stroke.network;

import com.isode.stroke.network.DomainNameServiceQuery.Result;
import com.isode.stroke.signals.Signal2;
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, int port, String serviceLookupPrefix, DomainNameResolver resolver, ConnectionFactory connectionFactory, TimerFactory timerFactory) {
        return new Connector(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory);
    }

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

    public void start() {
        assert currentConnection == null;
        assert serviceQuery == null;
        assert timer == null;
        queriedAllServices = false;
        
        if (timeoutMilliseconds > 0) {
            timer = timerFactory.createTimer(timeoutMilliseconds);
            timer.onTick.connect(new Slot() {
                public void call() {
                    handleTimeout();
                }
            });
        }
        if (serviceLookupPrefix != null) {
            serviceQuery = resolver.createServiceQuery(serviceLookupPrefix, hostname);
            serviceQuery.onResult.connect(new Slot1<Collection<DomainNameServiceQuery.Result>>() {
                public void call(Collection<Result> p1) {
                    handleServiceQueryResult(p1);
                }
            });
            serviceQuery.run();
        }
        else if (new HostAddress(hostname).isValid()) {
            // hostname is already a valid address; skip name lookup.
            foundSomeDNS = true;
            addressQueryResults.add(new HostAddress(hostname));
            tryNextAddress();
        }
        else {
            queryAddress(hostname);
        }
    }

    public void stop() {
        if (currentConnectionConnectFinishedConnection != null) {
            currentConnectionConnectFinishedConnection.disconnect();
            currentConnectionConnectFinishedConnection = null;
        }
        if (currentConnection != null) {
            currentConnection.disconnect();
        }
        finish(null);
    }

    public final Signal2<Connection, com.isode.stroke.base.Error> onConnectFinished = new Signal2<Connection, com.isode.stroke.base.Error>();

    private Connector(String hostname,int port, String serviceLookupPrefix, DomainNameResolver resolver, ConnectionFactory connectionFactory, TimerFactory timerFactory) {
        this.hostname = hostname;
        this.resolver = resolver;
        this.connectionFactory = connectionFactory;
        this.timerFactory = timerFactory;
        this.port = port;
        this.serviceLookupPrefix = serviceLookupPrefix;
        this.timeoutMilliseconds = 0;
        this.queriedAllServices = true;
        this.foundSomeDNS = false;
    }

    private void handleServiceQueryResult(Collection<Result> result) {
        serviceQueryResults = new ArrayList<Result>();
        serviceQueryResults.addAll(result);
        serviceQuery = null;
        if (!serviceQueryResults.isEmpty()) {
            foundSomeDNS = true;
        }
        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 {
            foundSomeDNS = true;
            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 connectPort = (port == -1) ? 5222 : port;
		if (!serviceQueryResults.isEmpty()) {
			connectPort = serviceQueryResults.get(0).port;
		}

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

    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);
    if (timer != null) {
        timer.start();
    }
    }

    private void handleConnectionConnectFinished(boolean error) {
        //std::cout << "Connector::handleConnectionConnectFinished() " << error << std::endl;
    if (timer != null) {
        timer.stop();
        timer = null;
    }        
	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, (connection != null || foundSomeDNS) ? null : new DomainNameResolveError());
    }

    private void handleTimeout() {
        //SWIFT_LOG(debug) << "Timeout" << std::endl;
        handleConnectionConnectFinished(true);
    }
    
    @Override
    public String toString() {
        return "Connector to \"" + hostname + "\" " +
        (currentConnection == null ? "not connected" : "using " + currentConnection);
    }


    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 = new ArrayList<DomainNameServiceQuery.Result>();
    private DomainNameAddressQuery addressQuery;
    private ArrayList<HostAddress> addressQueryResults = new ArrayList<HostAddress>();
    private boolean queriedAllServices = true;
    private Connection currentConnection;
    private SignalConnection currentConnectionConnectFinishedConnection;
    private final int port;
    private final String serviceLookupPrefix;
    private boolean foundSomeDNS = false;
}