JingleConnection.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import java.util.ArrayList;
  4import java.util.HashMap;
  5import java.util.Iterator;
  6import java.util.List;
  7import java.util.Map.Entry;
  8
  9import android.util.Log;
 10
 11import eu.siacs.conversations.entities.Account;
 12import eu.siacs.conversations.entities.Conversation;
 13import eu.siacs.conversations.entities.Message;
 14import eu.siacs.conversations.services.XmppConnectionService;
 15import eu.siacs.conversations.xml.Element;
 16import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 17import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
 18import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 19import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
 20import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 21
 22public class JingleConnection {
 23
 24	private JingleConnectionManager mJingleConnectionManager;
 25	private XmppConnectionService mXmppConnectionService;
 26	
 27	public static final int STATUS_INITIATED = 0;
 28	public static final int STATUS_ACCEPTED = 1;
 29	public static final int STATUS_TERMINATED = 2;
 30	public static final int STATUS_CANCELED = 3;
 31	public static final int STATUS_FINISHED = 4;
 32	public static final int STATUS_TRANSMITTING = 5;
 33	public static final int STATUS_FAILED = 99;
 34	
 35	private int status = -1;
 36	private Message message;
 37	private String sessionId;
 38	private Account account;
 39	private String initiator;
 40	private String responder;
 41	private List<JingleCandidate> candidates = new ArrayList<JingleCandidate>();
 42	private HashMap<String, SocksConnection> connections = new HashMap<String, SocksConnection>();
 43	
 44	private String transportId;
 45	private Element fileOffer;
 46	private JingleFile file = null;
 47	
 48	private boolean receivedCandidate = false;
 49	private boolean sentCandidate = false;
 50	
 51	private JingleTransport transport = null;
 52	
 53	private OnIqPacketReceived responseListener = new OnIqPacketReceived() {
 54		
 55		@Override
 56		public void onIqPacketReceived(Account account, IqPacket packet) {
 57			if (packet.getType() == IqPacket.TYPE_ERROR) {
 58				mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 59				status = STATUS_FAILED;
 60			}
 61		}
 62	};
 63	
 64	final OnFileTransmitted onFileTransmitted = new OnFileTransmitted() {
 65		
 66		@Override
 67		public void onFileTransmitted(JingleFile file) {
 68			if (responder.equals(account.getFullJid())) {
 69				sendSuccess();
 70				mXmppConnectionService.markMessage(message, Message.STATUS_RECIEVED);
 71			}
 72			Log.d("xmppService","sucessfully transmitted file. sha1:"+file.getSha1Sum());
 73		}
 74	};
 75	
 76	private OnProxyActivated onProxyActivated = new OnProxyActivated() {
 77		
 78		@Override
 79		public void success() {
 80			if (initiator.equals(account.getFullJid())) {
 81				Log.d("xmppService","we were initiating. sending file");
 82				transport.send(file,onFileTransmitted);
 83			} else {
 84				transport.receive(file,onFileTransmitted);
 85				Log.d("xmppService","we were responding. receiving file");
 86			}
 87		}
 88		
 89		@Override
 90		public void failed() {
 91			Log.d("xmppService","proxy activation failed");
 92		}
 93	};
 94	
 95	public JingleConnection(JingleConnectionManager mJingleConnectionManager) {
 96		this.mJingleConnectionManager = mJingleConnectionManager;
 97		this.mXmppConnectionService = mJingleConnectionManager.getXmppConnectionService();
 98	}
 99	
100	public String getSessionId() {
101		return this.sessionId;
102	}
103	
104	public String getAccountJid() {
105		return this.account.getFullJid();
106	}
107	
108	public String getCounterPart() {
109		return this.message.getCounterpart();
110	}
111	
112	public void deliverPacket(JinglePacket packet) {
113		
114		if (packet.isAction("session-terminate")) {
115			Reason reason = packet.getReason();
116			if (reason!=null) {
117				if (reason.hasChild("cancel")) {
118					this.cancel();
119				} else if (reason.hasChild("success")) {
120					this.finish();
121				}
122			} else {
123				Log.d("xmppService","remote terminated for no reason");
124				this.cancel();
125			}
126			} else if (packet.isAction("session-accept")) {
127			accept(packet);
128		} else if (packet.isAction("transport-info")) {
129			transportInfo(packet);
130		} else {
131			Log.d("xmppService","packet arrived in connection. action was "+packet.getAction());
132		}
133	}
134	
135	public void init(Message message) {
136		this.message = message;
137		this.account = message.getConversation().getAccount();
138		this.initiator = this.account.getFullJid();
139		this.responder = this.message.getCounterpart();
140		this.sessionId = this.mJingleConnectionManager.nextRandomId();
141		if (this.candidates.size() > 0) {
142			this.sendInitRequest();
143		} else {
144			this.mJingleConnectionManager.getPrimaryCandidate(account, new OnPrimaryCandidateFound() {
145				
146				@Override
147				public void onPrimaryCandidateFound(boolean success, final JingleCandidate candidate) {
148					if (success) {
149						final SocksConnection socksConnection = new SocksConnection(JingleConnection.this, candidate);
150						connections.put(candidate.getCid(), socksConnection);
151						socksConnection.connect(new OnSocksConnection() {
152							
153							@Override
154							public void failed() {
155								Log.d("xmppService","connection to our own primary candidete failed");
156								sendInitRequest();
157							}
158							
159							@Override
160							public void established() {
161								Log.d("xmppService","succesfully connected to our own primary candidate");
162								mergeCandidate(candidate);
163								sendInitRequest();
164							}
165						});
166						mergeCandidate(candidate);
167					} else {
168						Log.d("xmppService","no primary candidate of our own was found");
169						sendInitRequest();
170					}
171				}
172			});
173		}
174		
175	}
176	
177	public void init(Account account, JinglePacket packet) {
178		this.status = STATUS_INITIATED;
179		Conversation conversation = this.mXmppConnectionService.findOrCreateConversation(account, packet.getFrom().split("/")[0], false);
180		this.message = new Message(conversation, "receiving image file", Message.ENCRYPTION_NONE);
181		this.message.setType(Message.TYPE_IMAGE);
182		this.message.setStatus(Message.STATUS_RECIEVING);
183		String[] fromParts = packet.getFrom().split("/");
184		this.message.setPresence(fromParts[1]);
185		this.account = account;
186		this.initiator = packet.getFrom();
187		this.responder = this.account.getFullJid();
188		this.sessionId = packet.getSessionId();
189		Content content = packet.getJingleContent();
190		this.transportId = content.getTransportId();
191		this.mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
192		this.fileOffer = packet.getJingleContent().getFileOffer();
193		if (fileOffer!=null) {
194			this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message);
195			Element fileSize = fileOffer.findChild("size");
196			Element fileName = fileOffer.findChild("name");
197			this.file.setExpectedSize(Long.parseLong(fileSize.getContent()));
198			conversation.getMessages().add(message);
199			this.mXmppConnectionService.databaseBackend.createMessage(message);
200			if (this.mXmppConnectionService.convChangedListener!=null) {
201				this.mXmppConnectionService.convChangedListener.onConversationListChanged();
202			}
203			if (this.file.getExpectedSize()<=this.mJingleConnectionManager.getAutoAcceptFileSize()) {
204				Log.d("xmppService","auto accepting file from "+packet.getFrom());
205				this.sendAccept();
206			} else {
207				Log.d("xmppService","not auto accepting new file offer with size: "+this.file.getExpectedSize()+" allowed size:"+this.mJingleConnectionManager.getAutoAcceptFileSize());
208			}
209		} else {
210			Log.d("xmppService","no file offer was attached. aborting");
211		}
212	}
213	
214	private void sendInitRequest() {
215		JinglePacket packet = this.bootstrapPacket("session-initiate");
216		Content content = new Content();
217		if (message.getType() == Message.TYPE_IMAGE) {
218			content.setAttribute("creator", "initiator");
219			content.setAttribute("name", "a-file-offer");
220			content.setTransportId(this.transportId);
221			this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message);
222			content.setFileOffer(this.file);
223			this.transportId = this.mJingleConnectionManager.nextRandomId();
224			content.setTransportId(this.transportId);
225			content.socks5transport().setChildren(getCandidatesAsElements());
226			packet.setContent(content);
227			this.sendJinglePacket(packet);
228			this.status = STATUS_INITIATED;
229		}
230	}
231	
232	private List<Element> getCandidatesAsElements() {
233		List<Element> elements = new ArrayList<Element>();
234		for(JingleCandidate c : this.candidates) {
235			elements.add(c.toElement());
236		}
237		return elements;
238	}
239	
240	private void sendAccept() {
241		status = STATUS_ACCEPTED;
242		connectNextCandidate();
243		this.mJingleConnectionManager.getPrimaryCandidate(this.account, new OnPrimaryCandidateFound() {
244			
245			@Override
246			public void onPrimaryCandidateFound(boolean success,final JingleCandidate candidate) {
247				final JinglePacket packet = bootstrapPacket("session-accept");
248				final Content content = new Content();
249				content.setFileOffer(fileOffer);
250				content.setTransportId(transportId);
251				if ((success)&&(!equalCandidateExists(candidate))) {
252					final SocksConnection socksConnection = new SocksConnection(JingleConnection.this, candidate);
253					connections.put(candidate.getCid(), socksConnection);
254					socksConnection.connect(new OnSocksConnection() {
255						
256						@Override
257						public void failed() {
258							Log.d("xmppService","connection to our own primary candidate failed");
259							content.socks5transport().setChildren(getCandidatesAsElements());
260							packet.setContent(content);
261							sendJinglePacket(packet);
262						}
263						
264						@Override
265						public void established() {
266							Log.d("xmppService","connected to primary candidate");
267							mergeCandidate(candidate);
268							content.socks5transport().setChildren(getCandidatesAsElements());
269							packet.setContent(content);
270							sendJinglePacket(packet);
271						}
272					});
273				} else {
274					Log.d("xmppService","did not find a primary candidate for ourself");
275					content.socks5transport().setChildren(getCandidatesAsElements());
276					packet.setContent(content);
277					sendJinglePacket(packet);
278				}
279			}
280		});
281		
282	}
283	
284	private JinglePacket bootstrapPacket(String action) {
285		JinglePacket packet = new JinglePacket();
286		packet.setAction(action);
287		packet.setFrom(account.getFullJid());
288		packet.setTo(this.message.getCounterpart());
289		packet.setSessionId(this.sessionId);
290		packet.setInitiator(this.initiator);
291		return packet;
292	}
293	
294	private void sendJinglePacket(JinglePacket packet) {
295		//Log.d("xmppService",packet.toString());
296		account.getXmppConnection().sendIqPacket(packet,responseListener);
297	}
298	
299	private void accept(JinglePacket packet) {
300		Content content = packet.getJingleContent();
301		mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
302		this.status = STATUS_ACCEPTED;
303		this.connectNextCandidate();
304		IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
305		account.getXmppConnection().sendIqPacket(response, null);
306	}
307
308	private void transportInfo(JinglePacket packet) {
309		Content content = packet.getJingleContent();
310		if (content.hasSocks5Transport()) {
311			if (content.socks5transport().hasChild("activated")) {
312				onProxyActivated.success();
313			} else if (content.socks5transport().hasChild("activated")) {
314				onProxyActivated.failed();
315			} else if (content.socks5transport().hasChild("candidate-error")) {
316				Log.d("xmppService","received candidate error");
317				this.receivedCandidate = true;
318				if (status == STATUS_ACCEPTED) {
319					this.connect();
320				}
321			} else if (content.socks5transport().hasChild("candidate-used")){
322				String cid = content.socks5transport().findChild("candidate-used").getAttribute("cid");
323				if (cid!=null) {
324					Log.d("xmppService","candidate used by counterpart:"+cid);
325					JingleCandidate candidate = getCandidate(cid);
326					candidate.flagAsUsedByCounterpart();
327					this.receivedCandidate = true;
328					if ((status == STATUS_ACCEPTED)&&(this.sentCandidate)) {
329						this.connect();
330					} else {
331						Log.d("xmppService","ignoring because file is already in transmission or we havent sent our candidate yet");
332					}
333				} else {
334					Log.d("xmppService","couldn't read used candidate");
335				}
336			} else {
337				Log.d("xmppService","empty transport");
338			}
339		}
340		
341		IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
342		account.getXmppConnection().sendIqPacket(response, null);
343	}
344
345	private void connect() {
346		final SocksConnection connection = chooseConnection();
347		this.transport = connection;
348		if (connection==null) {
349			Log.d("xmppService","could not find suitable candidate");
350			this.disconnect();
351			this.status = STATUS_FAILED;
352			this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_FAILED);
353		} else {
354			this.status = STATUS_TRANSMITTING;
355			if (connection.isProxy()) {
356				if (connection.getCandidate().isOurs()) {
357					Log.d("xmppService","candidate "+connection.getCandidate().getCid()+" was our proxy and needs activation");
358					IqPacket activation = new IqPacket(IqPacket.TYPE_SET);
359					activation.setTo(connection.getCandidate().getJid());
360					activation.query("http://jabber.org/protocol/bytestreams").setAttribute("sid", this.getSessionId());
361					activation.query().addChild("activate").setContent(this.getCounterPart());
362					this.account.getXmppConnection().sendIqPacket(activation, new OnIqPacketReceived() {
363						
364						@Override
365						public void onIqPacketReceived(Account account, IqPacket packet) {
366							if (packet.getType()==IqPacket.TYPE_ERROR) {
367								onProxyActivated.failed();
368							} else {
369								onProxyActivated.success();
370								sendProxyActivated(connection.getCandidate().getCid());
371							}
372						}
373					});
374				}
375			} else {
376				if (initiator.equals(account.getFullJid())) {
377					Log.d("xmppService","we were initiating. sending file");
378					connection.send(file,onFileTransmitted);
379				} else {
380					Log.d("xmppService","we were responding. receiving file");
381					connection.receive(file,onFileTransmitted);
382				}
383			}
384		}
385	}
386	
387	private SocksConnection chooseConnection() {
388		SocksConnection connection = null;
389		Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
390	    while (it.hasNext()) {
391	    	Entry<String, SocksConnection> pairs = it.next();
392	    	SocksConnection currentConnection = pairs.getValue();
393	    	//Log.d("xmppService","comparing candidate: "+currentConnection.getCandidate().toString());
394	        if (currentConnection.isEstablished()&&(currentConnection.getCandidate().isUsedByCounterpart()||(!currentConnection.getCandidate().isOurs()))) {
395	        	//Log.d("xmppService","is usable");
396	        	if (connection==null) {
397	        		connection = currentConnection;
398	        	} else {
399	        		if (connection.getCandidate().getPriority()<currentConnection.getCandidate().getPriority()) {
400	        			connection = currentConnection;
401	        		} else if (connection.getCandidate().getPriority()==currentConnection.getCandidate().getPriority()) {
402	        			//Log.d("xmppService","found two candidates with same priority");
403	        			if (initiator.equals(account.getFullJid())) {
404	        				if (currentConnection.getCandidate().isOurs()) {
405	        					connection = currentConnection;
406	        				}
407	        			} else {
408	        				if (!currentConnection.getCandidate().isOurs()) {
409	        					connection = currentConnection;
410	        				}
411	        			}
412	        		}
413	        	}
414	        }
415	        it.remove();
416	    }
417		return connection;
418	}
419
420	private void sendSuccess() {
421		JinglePacket packet = bootstrapPacket("session-terminate");
422		Reason reason = new Reason();
423		reason.addChild("success");
424		packet.setReason(reason);
425		this.sendJinglePacket(packet);
426		this.disconnect();
427		this.status = STATUS_FINISHED;
428		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_RECIEVED);
429	}
430	
431	private void finish() {
432		this.status = STATUS_FINISHED;
433		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND);
434		this.disconnect();
435	}
436	
437	public void cancel() {
438		this.disconnect();
439		this.status = STATUS_CANCELED;
440		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_REJECTED);
441	}
442
443	private void connectNextCandidate() {
444		for(JingleCandidate candidate : this.candidates) {
445			if ((!connections.containsKey(candidate.getCid())&&(!candidate.isOurs()))) {
446				this.connectWithCandidate(candidate);
447				return;
448			}
449		}
450		this.sendCandidateError();
451	}
452	
453	private void connectWithCandidate(final JingleCandidate candidate) {
454		final SocksConnection socksConnection = new SocksConnection(this,candidate);
455		connections.put(candidate.getCid(), socksConnection);
456		socksConnection.connect(new OnSocksConnection() {
457			
458			@Override
459			public void failed() {
460				Log.d("xmppService", "connection failed with "+candidate.getHost()+":"+candidate.getPort());
461				connectNextCandidate();
462			}
463			
464			@Override
465			public void established() {
466				Log.d("xmppService", "established connection with "+candidate.getHost()+":"+candidate.getPort());
467				sendCandidateUsed(candidate.getCid());
468			}
469		});
470	}
471
472	private void disconnect() {
473		Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
474	    while (it.hasNext()) {
475	        Entry<String, SocksConnection> pairs = it.next();
476	        pairs.getValue().disconnect();
477	        it.remove();
478	    }
479	}
480	
481	private void sendProxyActivated(String cid) {
482		JinglePacket packet = bootstrapPacket("transport-info");
483		Content content = new Content();
484		//TODO: put these into actual variables
485		content.setAttribute("creator", "initiator");
486		content.setAttribute("name", "a-file-offer");
487		content.setTransportId(this.transportId);
488		content.socks5transport().addChild("activated").setAttribute("cid", cid);
489		packet.setContent(content);
490		this.sendJinglePacket(packet);
491	}
492	
493	private void sendCandidateUsed(final String cid) {
494		JinglePacket packet = bootstrapPacket("transport-info");
495		Content content = new Content();
496		//TODO: put these into actual variables
497		content.setAttribute("creator", "initiator");
498		content.setAttribute("name", "a-file-offer");
499		content.setTransportId(this.transportId);
500		content.setUsedCandidate(cid);
501		packet.setContent(content);
502		this.sendJinglePacket(packet);
503		this.sentCandidate = true;
504		if ((receivedCandidate)&&(status == STATUS_ACCEPTED)) {
505			connect();
506		}
507	}
508	
509	private void sendCandidateError() {
510		JinglePacket packet = bootstrapPacket("transport-info");
511		Content content = new Content();
512		//TODO: put these into actual variables
513		content.setAttribute("creator", "initiator");
514		content.setAttribute("name", "a-file-offer");
515		content.setTransportId(this.transportId);
516		content.setCandidateError();
517		packet.setContent(content);
518		this.sendJinglePacket(packet);
519		this.sentCandidate = true;
520		if ((receivedCandidate)&&(status == STATUS_ACCEPTED)) {
521			connect();
522		}
523	}
524
525	public String getInitiator() {
526		return this.initiator;
527	}
528	
529	public String getResponder() {
530		return this.responder;
531	}
532	
533	public int getStatus() {
534		return this.status;
535	}
536	
537	private boolean equalCandidateExists(JingleCandidate candidate) {
538		for(JingleCandidate c : this.candidates) {
539			if (c.equalValues(candidate)) {
540				return true;
541			}
542		}
543		return false;
544	}
545	
546	private void mergeCandidate(JingleCandidate candidate) {
547		for(JingleCandidate c : this.candidates) {
548			if (c.equals(candidate)) {
549				return;
550			}
551		}
552		this.candidates.add(candidate);
553	}
554	
555	private void mergeCandidates(List<JingleCandidate> candidates) {
556		for(JingleCandidate c : candidates) {
557			mergeCandidate(c);
558		}
559	}
560	
561	private JingleCandidate getCandidate(String cid) {
562		for(JingleCandidate c : this.candidates) {
563			if (c.getCid().equals(cid)) {
564				return c;
565			}
566		}
567		return null;
568	}
569	
570	interface OnProxyActivated {
571		public void success();
572		public void failed();
573	}
574}