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.socks5transport().setChildren(getCandidatesAsElements());
225			packet.setContent(content);
226			this.sendJinglePacket(packet);
227			this.status = STATUS_INITIATED;
228		}
229	}
230	
231	private List<Element> getCandidatesAsElements() {
232		List<Element> elements = new ArrayList<Element>();
233		for(JingleCandidate c : this.candidates) {
234			elements.add(c.toElement());
235		}
236		return elements;
237	}
238	
239	private void sendAccept() {
240		status = STATUS_ACCEPTED;
241		connectNextCandidate();
242		this.mJingleConnectionManager.getPrimaryCandidate(this.account, new OnPrimaryCandidateFound() {
243			
244			@Override
245			public void onPrimaryCandidateFound(boolean success,final JingleCandidate candidate) {
246				final JinglePacket packet = bootstrapPacket("session-accept");
247				final Content content = new Content();
248				content.setFileOffer(fileOffer);
249				content.setTransportId(transportId);
250				if ((success)&&(!equalCandidateExists(candidate))) {
251					final SocksConnection socksConnection = new SocksConnection(JingleConnection.this, candidate);
252					connections.put(candidate.getCid(), socksConnection);
253					socksConnection.connect(new OnSocksConnection() {
254						
255						@Override
256						public void failed() {
257							Log.d("xmppService","connection to our own primary candidate failed");
258							content.socks5transport().setChildren(getCandidatesAsElements());
259							packet.setContent(content);
260							sendJinglePacket(packet);
261						}
262						
263						@Override
264						public void established() {
265							Log.d("xmppService","connected to primary candidate");
266							mergeCandidate(candidate);
267							content.socks5transport().setChildren(getCandidatesAsElements());
268							packet.setContent(content);
269							sendJinglePacket(packet);
270						}
271					});
272				} else {
273					Log.d("xmppService","did not find a primary candidate for ourself");
274					content.socks5transport().setChildren(getCandidatesAsElements());
275					packet.setContent(content);
276					sendJinglePacket(packet);
277				}
278			}
279		});
280		
281	}
282	
283	private JinglePacket bootstrapPacket(String action) {
284		JinglePacket packet = new JinglePacket();
285		packet.setAction(action);
286		packet.setFrom(account.getFullJid());
287		packet.setTo(this.message.getCounterpart());
288		packet.setSessionId(this.sessionId);
289		packet.setInitiator(this.initiator);
290		return packet;
291	}
292	
293	private void sendJinglePacket(JinglePacket packet) {
294		//Log.d("xmppService",packet.toString());
295		account.getXmppConnection().sendIqPacket(packet,responseListener);
296	}
297	
298	private void accept(JinglePacket packet) {
299		Content content = packet.getJingleContent();
300		mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
301		this.status = STATUS_ACCEPTED;
302		this.connectNextCandidate();
303		IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
304		account.getXmppConnection().sendIqPacket(response, null);
305	}
306
307	private void transportInfo(JinglePacket packet) {
308		Content content = packet.getJingleContent();
309		if (content.hasSocks5Transport()) {
310			if (content.socks5transport().hasChild("activated")) {
311				onProxyActivated.success();
312			} else if (content.socks5transport().hasChild("activated")) {
313				onProxyActivated.failed();
314			} else if (content.socks5transport().hasChild("candidate-error")) {
315				Log.d("xmppService","received candidate error");
316				this.receivedCandidate = true;
317				if (status == STATUS_ACCEPTED) {
318					this.connect();
319				}
320			} else if (content.socks5transport().hasChild("candidate-used")){
321				String cid = content.socks5transport().findChild("candidate-used").getAttribute("cid");
322				if (cid!=null) {
323					Log.d("xmppService","candidate used by counterpart:"+cid);
324					JingleCandidate candidate = getCandidate(cid);
325					candidate.flagAsUsedByCounterpart();
326					this.receivedCandidate = true;
327					if ((status == STATUS_ACCEPTED)&&(this.sentCandidate)) {
328						this.connect();
329					} else {
330						Log.d("xmppService","ignoring because file is already in transmission or we havent sent our candidate yet");
331					}
332				} else {
333					Log.d("xmppService","couldn't read used candidate");
334				}
335			} else {
336				Log.d("xmppService","empty transport");
337			}
338		}
339		
340		IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
341		account.getXmppConnection().sendIqPacket(response, null);
342	}
343
344	private void connect() {
345		final SocksConnection connection = chooseConnection();
346		this.transport = connection;
347		if (connection==null) {
348			Log.d("xmppService","could not find suitable candidate");
349			this.disconnect();
350			this.status = STATUS_FAILED;
351			this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_FAILED);
352		} else {
353			this.status = STATUS_TRANSMITTING;
354			if (connection.isProxy()) {
355				if (connection.getCandidate().isOurs()) {
356					Log.d("xmppService","candidate "+connection.getCandidate().getCid()+" was our proxy and needs activation");
357					IqPacket activation = new IqPacket(IqPacket.TYPE_SET);
358					activation.setTo(connection.getCandidate().getJid());
359					activation.query("http://jabber.org/protocol/bytestreams").setAttribute("sid", this.getSessionId());
360					activation.query().addChild("activate").setContent(this.getCounterPart());
361					this.account.getXmppConnection().sendIqPacket(activation, new OnIqPacketReceived() {
362						
363						@Override
364						public void onIqPacketReceived(Account account, IqPacket packet) {
365							if (packet.getType()==IqPacket.TYPE_ERROR) {
366								onProxyActivated.failed();
367							} else {
368								onProxyActivated.success();
369								sendProxyActivated(connection.getCandidate().getCid());
370							}
371						}
372					});
373				}
374			} else {
375				if (initiator.equals(account.getFullJid())) {
376					Log.d("xmppService","we were initiating. sending file");
377					connection.send(file,onFileTransmitted);
378				} else {
379					Log.d("xmppService","we were responding. receiving file");
380					connection.receive(file,onFileTransmitted);
381				}
382			}
383		}
384	}
385	
386	private SocksConnection chooseConnection() {
387		SocksConnection connection = null;
388		Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
389	    while (it.hasNext()) {
390	    	Entry<String, SocksConnection> pairs = it.next();
391	    	SocksConnection currentConnection = pairs.getValue();
392	    	//Log.d("xmppService","comparing candidate: "+currentConnection.getCandidate().toString());
393	        if (currentConnection.isEstablished()&&(currentConnection.getCandidate().isUsedByCounterpart()||(!currentConnection.getCandidate().isOurs()))) {
394	        	//Log.d("xmppService","is usable");
395	        	if (connection==null) {
396	        		connection = currentConnection;
397	        	} else {
398	        		if (connection.getCandidate().getPriority()<currentConnection.getCandidate().getPriority()) {
399	        			connection = currentConnection;
400	        		} else if (connection.getCandidate().getPriority()==currentConnection.getCandidate().getPriority()) {
401	        			//Log.d("xmppService","found two candidates with same priority");
402	        			if (initiator.equals(account.getFullJid())) {
403	        				if (currentConnection.getCandidate().isOurs()) {
404	        					connection = currentConnection;
405	        				}
406	        			} else {
407	        				if (!currentConnection.getCandidate().isOurs()) {
408	        					connection = currentConnection;
409	        				}
410	        			}
411	        		}
412	        	}
413	        }
414	        it.remove();
415	    }
416		return connection;
417	}
418
419	private void sendSuccess() {
420		JinglePacket packet = bootstrapPacket("session-terminate");
421		Reason reason = new Reason();
422		reason.addChild("success");
423		packet.setReason(reason);
424		this.sendJinglePacket(packet);
425		this.disconnect();
426		this.status = STATUS_FINISHED;
427		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_RECIEVED);
428	}
429	
430	private void finish() {
431		this.status = STATUS_FINISHED;
432		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND);
433		this.disconnect();
434	}
435	
436	public void cancel() {
437		this.disconnect();
438		this.status = STATUS_CANCELED;
439		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_REJECTED);
440	}
441
442	private void connectNextCandidate() {
443		for(JingleCandidate candidate : this.candidates) {
444			if ((!connections.containsKey(candidate.getCid())&&(!candidate.isOurs()))) {
445				this.connectWithCandidate(candidate);
446				return;
447			}
448		}
449		this.sendCandidateError();
450	}
451	
452	private void connectWithCandidate(final JingleCandidate candidate) {
453		final SocksConnection socksConnection = new SocksConnection(this,candidate);
454		connections.put(candidate.getCid(), socksConnection);
455		socksConnection.connect(new OnSocksConnection() {
456			
457			@Override
458			public void failed() {
459				Log.d("xmppService", "connection failed with "+candidate.getHost()+":"+candidate.getPort());
460				connectNextCandidate();
461			}
462			
463			@Override
464			public void established() {
465				Log.d("xmppService", "established connection with "+candidate.getHost()+":"+candidate.getPort());
466				sendCandidateUsed(candidate.getCid());
467			}
468		});
469	}
470
471	private void disconnect() {
472		Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
473	    while (it.hasNext()) {
474	        Entry<String, SocksConnection> pairs = it.next();
475	        pairs.getValue().disconnect();
476	        it.remove();
477	    }
478	}
479	
480	private void sendProxyActivated(String cid) {
481		JinglePacket packet = bootstrapPacket("transport-info");
482		Content content = new Content();
483		//TODO: put these into actual variables
484		content.setAttribute("creator", "initiator");
485		content.setAttribute("name", "a-file-offer");
486		content.setTransportId(this.transportId);
487		content.socks5transport().addChild("activated").setAttribute("cid", cid);
488		packet.setContent(content);
489		this.sendJinglePacket(packet);
490	}
491	
492	private void sendCandidateUsed(final String cid) {
493		JinglePacket packet = bootstrapPacket("transport-info");
494		Content content = new Content();
495		//TODO: put these into actual variables
496		content.setAttribute("creator", "initiator");
497		content.setAttribute("name", "a-file-offer");
498		content.setTransportId(this.transportId);
499		content.setUsedCandidate(cid);
500		packet.setContent(content);
501		this.sendJinglePacket(packet);
502		this.sentCandidate = true;
503		if ((receivedCandidate)&&(status == STATUS_ACCEPTED)) {
504			connect();
505		}
506	}
507	
508	private void sendCandidateError() {
509		JinglePacket packet = bootstrapPacket("transport-info");
510		Content content = new Content();
511		//TODO: put these into actual variables
512		content.setAttribute("creator", "initiator");
513		content.setAttribute("name", "a-file-offer");
514		content.setTransportId(this.transportId);
515		content.setCandidateError();
516		packet.setContent(content);
517		this.sendJinglePacket(packet);
518		this.sentCandidate = true;
519		if ((receivedCandidate)&&(status == STATUS_ACCEPTED)) {
520			connect();
521		}
522	}
523
524	public String getInitiator() {
525		return this.initiator;
526	}
527	
528	public String getResponder() {
529		return this.responder;
530	}
531	
532	public int getStatus() {
533		return this.status;
534	}
535	
536	private boolean equalCandidateExists(JingleCandidate candidate) {
537		for(JingleCandidate c : this.candidates) {
538			if (c.equalValues(candidate)) {
539				return true;
540			}
541		}
542		return false;
543	}
544	
545	private void mergeCandidate(JingleCandidate candidate) {
546		for(JingleCandidate c : this.candidates) {
547			if (c.equals(candidate)) {
548				return;
549			}
550		}
551		this.candidates.add(candidate);
552	}
553	
554	private void mergeCandidates(List<JingleCandidate> candidates) {
555		for(JingleCandidate c : candidates) {
556			mergeCandidate(c);
557		}
558	}
559	
560	private JingleCandidate getCandidate(String cid) {
561		for(JingleCandidate c : this.candidates) {
562			if (c.getCid().equals(cid)) {
563				return c;
564			}
565		}
566		return null;
567	}
568	
569	interface OnProxyActivated {
570		public void success();
571		public void failed();
572	}
573}