You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DCCManager.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. /*
  2. * Copyright (c) 2006-2014 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.addons.dcc;
  23. import com.dmdirc.ClientModule.GlobalConfig;
  24. import com.dmdirc.DMDircMBassador;
  25. import com.dmdirc.FrameContainer;
  26. import com.dmdirc.addons.dcc.events.DccChatRequestEvent;
  27. import com.dmdirc.addons.dcc.events.DccSendRequestEvent;
  28. import com.dmdirc.addons.dcc.io.DCC;
  29. import com.dmdirc.addons.dcc.io.DCCChat;
  30. import com.dmdirc.addons.dcc.io.DCCTransfer;
  31. import com.dmdirc.addons.dcc.kde.KFileChooser;
  32. import com.dmdirc.addons.ui_swing.SwingWindowFactory;
  33. import com.dmdirc.addons.ui_swing.components.frames.ComponentFrameFactory;
  34. import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
  35. import com.dmdirc.addons.ui_swing.injection.MainWindow;
  36. import com.dmdirc.commandline.CommandLineOptionsModule.Directory;
  37. import com.dmdirc.commandline.CommandLineOptionsModule.DirectoryType;
  38. import com.dmdirc.commandparser.parsers.GlobalCommandParser;
  39. import com.dmdirc.events.ServerCtcpEvent;
  40. import com.dmdirc.events.UserErrorEvent;
  41. import com.dmdirc.interfaces.CommandController;
  42. import com.dmdirc.interfaces.Connection;
  43. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  44. import com.dmdirc.interfaces.config.ConfigProvider;
  45. import com.dmdirc.interfaces.config.IdentityController;
  46. import com.dmdirc.logger.ErrorLevel;
  47. import com.dmdirc.messages.MessageSinkManager;
  48. import com.dmdirc.parser.interfaces.ClientInfo;
  49. import com.dmdirc.parser.interfaces.Parser;
  50. import com.dmdirc.plugins.PluginInfo;
  51. import com.dmdirc.ui.WindowManager;
  52. import com.dmdirc.ui.input.TabCompleterFactory;
  53. import com.dmdirc.util.URLBuilder;
  54. import java.awt.Window;
  55. import java.io.File;
  56. import java.io.IOException;
  57. import java.net.InetAddress;
  58. import java.net.UnknownHostException;
  59. import java.util.Arrays;
  60. import java.util.HashSet;
  61. import java.util.Set;
  62. import javax.inject.Inject;
  63. import javax.inject.Singleton;
  64. import javax.swing.JFileChooser;
  65. import javax.swing.JOptionPane;
  66. import net.engio.mbassy.listener.Handler;
  67. /**
  68. * This plugin adds DCC to DMDirc.
  69. */
  70. @Singleton
  71. public class DCCManager {
  72. /** Our DCC Container window. */
  73. private PlaceholderContainer container;
  74. /** Config manager to read settings from. */
  75. private final AggregateConfigProvider config;
  76. /** The sink manager to use to dispatch messages. */
  77. private final MessageSinkManager messageSinkManager;
  78. /** Window Management. */
  79. private final WindowManager windowManager;
  80. /** The command controller to use. */
  81. private final CommandController commandController;
  82. /** The factory to use for tab completers. */
  83. private final TabCompleterFactory tabCompleterFactory;
  84. /** The client's main window that will parent any new windows. */
  85. private final Window mainWindow;
  86. /** The configuration domain to use. */
  87. private final String domain;
  88. /** The URL builder to use when finding icons. */
  89. private final URLBuilder urlBuilder;
  90. /** The bus to dispatch events on. */
  91. private final DMDircMBassador eventBus;
  92. /**
  93. * Creates a new instance of this plugin.
  94. *
  95. * @param mainWindow The window that will parent any new dialogs.
  96. * @param pluginInfo This plugin's plugin info
  97. * @param identityController The Identity controller that provides the current config
  98. * @param globalConfig The configuration to read settings from.
  99. * @param commandController Command controller to register commands
  100. * @param messageSinkManager The sink manager to use to dispatch messages.
  101. * @param windowManager Window Management
  102. * @param tabCompleterFactory The factory to use for tab completers.
  103. * @param windowFactory The window factory to register the DCC implementations with.
  104. * @param componentFrameFactory Factory to use to create new component frames for DCC windows.
  105. * @param urlBuilder The URL builder to use when finding icons.
  106. * @param eventBus The bus to dispatch events on.
  107. * @param commandParser The command parser to use for DCC windows.
  108. * @param baseDirectory The directory to create a downloads directory within.
  109. */
  110. @Inject
  111. public DCCManager(
  112. @MainWindow final Window mainWindow,
  113. final PluginInfo pluginInfo,
  114. final IdentityController identityController,
  115. @GlobalConfig final AggregateConfigProvider globalConfig,
  116. final CommandController commandController,
  117. final MessageSinkManager messageSinkManager,
  118. final WindowManager windowManager,
  119. final TabCompleterFactory tabCompleterFactory,
  120. final SwingWindowFactory windowFactory,
  121. final ComponentFrameFactory componentFrameFactory,
  122. final URLBuilder urlBuilder,
  123. final DMDircMBassador eventBus,
  124. final GlobalCommandParser commandParser,
  125. @Directory(DirectoryType.BASE) final String baseDirectory) {
  126. this.mainWindow = mainWindow;
  127. this.messageSinkManager = messageSinkManager;
  128. this.windowManager = windowManager;
  129. this.commandController = commandController;
  130. this.tabCompleterFactory = tabCompleterFactory;
  131. this.domain = pluginInfo.getDomain();
  132. this.config = globalConfig;
  133. this.urlBuilder = urlBuilder;
  134. this.eventBus = eventBus;
  135. windowFactory.registerImplementation(
  136. new SwingWindowFactory.WindowProvider() {
  137. @Override
  138. public TextFrame getWindow(final FrameContainer container) {
  139. return componentFrameFactory.getComponentFrame(container, commandParser);
  140. }
  141. @Override
  142. public Set<String> getComponents() {
  143. return new HashSet<>(Arrays.asList(
  144. "com.dmdirc.addons.dcc.ui.PlaceholderPanel"));
  145. }
  146. });
  147. windowFactory.registerImplementation(
  148. new SwingWindowFactory.WindowProvider() {
  149. @Override
  150. public TextFrame getWindow(final FrameContainer container) {
  151. return componentFrameFactory.getComponentFrame(container, commandParser);
  152. }
  153. @Override
  154. public Set<String> getComponents() {
  155. return new HashSet<>(Arrays.asList(
  156. "com.dmdirc.addons.dcc.ui.TransferPanel"));
  157. }
  158. });
  159. final ConfigProvider defaults = identityController.getAddonSettings();
  160. defaults.setOption(domain, "receive.savelocation",
  161. baseDirectory + "downloads" + File.separator);
  162. }
  163. public String getDomain() {
  164. return domain;
  165. }
  166. /**
  167. * Ask the location to save a file, then start the download.
  168. *
  169. * @param nickname Person this dcc is from.
  170. * @param send The DCCSend to save for.
  171. * @param parser The parser this send was received on
  172. * @param reverse Is this a reverse dcc?
  173. * @param token Token used in reverse dcc.
  174. */
  175. public void saveFile(final String nickname, final DCCTransfer send,
  176. final Parser parser, final boolean reverse, final String token) {
  177. // New thread to ask the user where to save in to stop us locking the UI
  178. new Thread(new Runnable() {
  179. @Override
  180. public void run() {
  181. final JFileChooser jc = KFileChooser.getFileChooser(config,
  182. DCCManager.this,
  183. config.getOption(getDomain(), "receive.savelocation"));
  184. final int result;
  185. if (config.getOptionBool(getDomain(), "receive.autoaccept")) {
  186. result = JFileChooser.APPROVE_OPTION;
  187. } else {
  188. result = showFileChooser(send, jc);
  189. }
  190. if (result != JFileChooser.APPROVE_OPTION) {
  191. return;
  192. }
  193. send.setFileName(jc.getSelectedFile().getPath());
  194. if (!handleExists(send, jc, nickname, parser, reverse, token)) {
  195. return;
  196. }
  197. final boolean resume = handleResume(jc);
  198. if (reverse && !token.isEmpty()) {
  199. final TransferContainer container = new TransferContainer(DCCManager.this, send,
  200. config, "*Receive: " + nickname, nickname, null, urlBuilder, eventBus);
  201. windowManager.addWindow(getContainer(), container);
  202. send.setToken(token);
  203. if (resume) {
  204. if (config.getOptionBool(getDomain(),
  205. "receive.reverse.sendtoken")) {
  206. parser.sendCTCP(nickname, "DCC", "RESUME "
  207. + send.getShortFileName() + " 0 "
  208. + jc.getSelectedFile().length() + " "
  209. + token);
  210. } else {
  211. parser.sendCTCP(nickname, "DCC", "RESUME "
  212. + send.getShortFileName() + " 0 "
  213. + jc.getSelectedFile().length());
  214. }
  215. } else {
  216. if (listen(send)) {
  217. parser.sendCTCP(nickname, "DCC", "SEND "
  218. + send.getShortFileName() + " "
  219. + DCC.ipToLong(getListenIP(parser))
  220. + " " + send.getPort() + " "
  221. + send.getFileSize() + " " + token);
  222. }
  223. }
  224. } else {
  225. final TransferContainer container = new TransferContainer(DCCManager.this, send,
  226. config, "Receive: " + nickname, nickname, null, urlBuilder, eventBus);
  227. windowManager.addWindow(getContainer(), container);
  228. if (resume) {
  229. parser.sendCTCP(nickname, "DCC", "RESUME "
  230. + send.getShortFileName() + " "
  231. + send.getPort() + " "
  232. + jc.getSelectedFile().length());
  233. } else {
  234. send.connect();
  235. }
  236. }
  237. }
  238. }, "saveFileThread: " + send.getShortFileName()).start();
  239. }
  240. /**
  241. * Checks if the selected file exists and prompts the user as required.
  242. *
  243. * @param send DCC Transfer
  244. * @param jc File chooser
  245. * @param nickname Remote nickname
  246. * @param parser Parser
  247. * @param reverse Reverse DCC?
  248. * @param token DCC token
  249. *
  250. * @return true if the user wants to continue, false if they wish to abort
  251. */
  252. private boolean handleExists(final DCCTransfer send, final JFileChooser jc,
  253. final String nickname, final Parser parser, final boolean reverse,
  254. final String token) {
  255. if (jc.getSelectedFile().exists() && send.getFileSize() > -1
  256. && send.getFileSize() <= jc.getSelectedFile().length()) {
  257. if (config.getOptionBool(getDomain(), "receive.autoaccept")) {
  258. return false;
  259. } else {
  260. JOptionPane.showMessageDialog(
  261. mainWindow,
  262. "This file has already "
  263. + "been completed, or is longer than the file you are "
  264. + "receiving.\nPlease choose a different file.",
  265. "Problem with selected file",
  266. JOptionPane.ERROR_MESSAGE);
  267. saveFile(nickname, send, parser, reverse, token);
  268. return false;
  269. }
  270. }
  271. return true;
  272. }
  273. /**
  274. * Prompts the user to resume a transfer if required.
  275. *
  276. * @param jc File chooser
  277. *
  278. * @return true if the user wants to continue the transfer false otherwise
  279. */
  280. private boolean handleResume(final JFileChooser jc) {
  281. if (jc.getSelectedFile().exists()) {
  282. if (config.getOptionBool(getDomain(), "receive.autoaccept")) {
  283. return true;
  284. } else {
  285. final int result = JOptionPane.showConfirmDialog(
  286. mainWindow, "This file exists already"
  287. + ", do you want to resume an exisiting download?",
  288. "Resume Download?", JOptionPane.YES_NO_OPTION);
  289. return (result == JOptionPane.YES_OPTION);
  290. }
  291. }
  292. return false;
  293. }
  294. /**
  295. * Sets up and display a file chooser.
  296. *
  297. * @param send DCCTransfer object sending the file
  298. * @param jc File chooser
  299. *
  300. * @return the return state of the file chooser on popdown:
  301. * <ul>
  302. * <li>JFileChooser.CANCEL_OPTION
  303. * <li>JFileChooser.APPROVE_OPTION
  304. * <li>JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
  305. * </ul>
  306. */
  307. private int showFileChooser(final DCCTransfer send, final JFileChooser jc) {
  308. jc.setDialogTitle("Save " + send.getShortFileName() + " As - DMDirc");
  309. jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
  310. jc.setMultiSelectionEnabled(false);
  311. jc.setSelectedFile(new File(send.getFileName()));
  312. return jc.showSaveDialog(mainWindow);
  313. }
  314. /**
  315. * Make the given DCC start listening. This will either call dcc.listen() or
  316. * dcc.listen(startPort, endPort) depending on config.
  317. *
  318. * @param dcc DCC to start listening.
  319. *
  320. * @return True if Socket was opened.
  321. */
  322. protected boolean listen(final DCC dcc) {
  323. final boolean usePortRange = config.
  324. getOptionBool(getDomain(), "firewall.ports.usePortRange");
  325. try {
  326. if (usePortRange) {
  327. final int startPort = config.getOptionInt(getDomain(), "firewall.ports.startPort");
  328. final int endPort = config.getOptionInt(getDomain(), "firewall.ports.endPort");
  329. dcc.listen(startPort, endPort);
  330. } else {
  331. dcc.listen();
  332. }
  333. return true;
  334. } catch (IOException ioe) {
  335. return false;
  336. }
  337. }
  338. @Handler
  339. public void handleServerCtctpEvent(final ServerCtcpEvent event) {
  340. final boolean autoAccept = config.getOptionBool(getDomain(), "receive.autoaccept");
  341. final String[] ctcpData = event.getContent().split(" ");
  342. if (!"DCC".equalsIgnoreCase(event.getType())) {
  343. return;
  344. }
  345. switch (event.getType().toLowerCase()) {
  346. case "chat":
  347. if (ctcpData.length > 3) {
  348. handleChat(autoAccept, ctcpData, event.getClient(), event.getConnection());
  349. }
  350. break;
  351. case "send":
  352. if (ctcpData.length > 3) {
  353. handleSend(autoAccept, ctcpData, event.getClient(), event.getConnection());
  354. }
  355. break;
  356. case "resume":
  357. //Fallthrough
  358. case "accept":
  359. if (ctcpData.length > 2) {
  360. handleReceive(ctcpData, event.getClient(), event.getConnection());
  361. }
  362. break;
  363. default:
  364. break;
  365. }
  366. }
  367. /**
  368. * Handles a DCC chat request.
  369. *
  370. * @param dontAsk Don't ask any questions, assume yes.
  371. * @param ctcpData CTCP data bits
  372. * @param client Client receiving DCC
  373. * @param connection Connection DCC received on
  374. */
  375. private void handleChat(final boolean dontAsk, final String[] ctcpData,
  376. final ClientInfo client, final Connection connection) {
  377. final String nickname = client.getNickname();
  378. if (dontAsk) {
  379. handleDCCChat(connection.getParser(), nickname, ctcpData);
  380. } else {
  381. eventBus.publish(new DccChatRequestEvent(connection, nickname));
  382. new ChatRequestDialog(mainWindow, this, connection, nickname, ctcpData).display();
  383. }
  384. }
  385. void handleDCCChat(final Parser parser, final String nickname, final String[] ctcpData) {
  386. final long ipAddress;
  387. final int port;
  388. try {
  389. ipAddress = Long.parseLong(ctcpData[2]);
  390. port = Integer.parseInt(ctcpData[3]);
  391. } catch (NumberFormatException nfe) {
  392. return;
  393. }
  394. final DCCChat chat = new DCCChat();
  395. chat.setAddress(ipAddress, port);
  396. final String myNickname = parser.getLocalClient().getNickname();
  397. final DCCFrameContainer f = new ChatContainer(
  398. getContainer(),
  399. chat,
  400. config,
  401. commandController,
  402. "Chat: " + nickname,
  403. myNickname,
  404. nickname,
  405. tabCompleterFactory,
  406. messageSinkManager,
  407. urlBuilder,
  408. eventBus);
  409. windowManager.addWindow(getContainer(), f);
  410. f.addLine("DCCChatStarting", nickname, chat.getHost(), chat.getPort());
  411. chat.connect();
  412. }
  413. /**
  414. * Handles a DCC send request.
  415. *
  416. * @param dontAsk Don't ask any questions, assume yes.
  417. * @param ctcpData CTCP data bits
  418. * @param client Client that received the DCC
  419. * @param connection Connection the DCC was received on
  420. */
  421. private void handleSend(final boolean dontAsk, final String[] ctcpData, final ClientInfo client,
  422. final Connection connection) {
  423. final String nickname = client.getNickname();
  424. final String filename;
  425. String tmpFilename;
  426. // Clients tend to put files with spaces in the name in ""
  427. final StringBuilder filenameBits = new StringBuilder();
  428. int i;
  429. final boolean quoted = ctcpData[1].startsWith("\"");
  430. if (quoted) {
  431. for (i = 1; i < ctcpData.length; i++) {
  432. String bit = ctcpData[i];
  433. if (i == 1) {
  434. bit = bit.substring(1);
  435. }
  436. if (bit.endsWith("\"")) {
  437. filenameBits.append(" ").append(bit.substring(0, bit.length() - 1));
  438. break;
  439. } else {
  440. filenameBits.append(" ").append(bit);
  441. }
  442. }
  443. tmpFilename = filenameBits.toString().trim();
  444. } else {
  445. tmpFilename = ctcpData[1];
  446. i = 1;
  447. }
  448. // Try to remove path names if sent.
  449. // Change file separatorChar from other OSs first
  450. if (File.separatorChar == '/') {
  451. tmpFilename = tmpFilename.replace('\\', File.separatorChar);
  452. } else {
  453. tmpFilename = tmpFilename.replace('/', File.separatorChar);
  454. }
  455. // Then get just the name of the file.
  456. filename = new File(tmpFilename).getName();
  457. final String ip = ctcpData[++i];
  458. final String port = ctcpData[++i];
  459. long size;
  460. if (ctcpData.length + 1 > i) {
  461. try {
  462. size = Integer.parseInt(ctcpData[++i]);
  463. } catch (NumberFormatException nfe) {
  464. size = -1;
  465. }
  466. } else {
  467. size = -1;
  468. }
  469. final String token = (ctcpData.length - 1 > i
  470. && !ctcpData[i + 1].equals("T")) ? ctcpData[++i] : "";
  471. // Ignore incorrect ports, or non-numeric IP/Port
  472. final long ipLong;
  473. final int portInt;
  474. try {
  475. portInt = Integer.parseInt(port);
  476. if (portInt > 65535 || portInt < 0) {
  477. return;
  478. }
  479. ipLong = Long.parseLong(ip);
  480. } catch (NumberFormatException nfe) {
  481. return;
  482. }
  483. if (DCCTransfer.findByToken(token) == null && !dontAsk) {
  484. if (token.isEmpty() || port.equals("0")) {
  485. // Make sure this is not a reverse DCC Send that we no longer care about.
  486. eventBus.publish(new DccSendRequestEvent(connection, nickname, filename));
  487. new SendRequestDialog(mainWindow, this, token, ipLong, portInt, filename, size,
  488. nickname, connection).display();
  489. }
  490. }
  491. }
  492. void handleDCCSend(final String token, final long ip, final int port, final String filename,
  493. final long size, final String nickname, final Parser parser) {
  494. DCCTransfer send = DCCTransfer.findByToken(token);
  495. final boolean newSend = send == null;
  496. if (newSend) {
  497. send = new DCCTransfer(config.getOptionInt(getDomain(), "send.blocksize"));
  498. send.setTurbo(config.getOptionBool(getDomain(), "send.forceturbo"));
  499. } else {
  500. return;
  501. }
  502. send.setAddress(ip, port);
  503. send.setFileName(filename);
  504. send.setFileSize(size);
  505. saveFile(nickname, send, parser, port == 0, token);
  506. }
  507. /**
  508. * Handles a DCC chat request.
  509. *
  510. * @param ctcpData CTCP data bits
  511. * @param client Client receiving the DCC
  512. * @param connection Connection the DCC was received on
  513. */
  514. private void handleReceive(final String[] ctcpData, final ClientInfo client,
  515. final Connection connection) {
  516. final String filename;
  517. // Clients tend to put files with spaces in the name in ""
  518. final StringBuilder filenameBits = new StringBuilder();
  519. int i;
  520. final boolean quoted = ctcpData[1].startsWith("\"");
  521. if (quoted) {
  522. for (i = 1; i < ctcpData.length; i++) {
  523. String bit = ctcpData[i];
  524. if (i == 1) {
  525. bit = bit.substring(1);
  526. }
  527. if (bit.endsWith("\"")) {
  528. filenameBits.append(" ")
  529. .append(bit.substring(0, bit.length() - 1));
  530. break;
  531. } else {
  532. filenameBits.append(" ").append(bit);
  533. }
  534. }
  535. filename = filenameBits.toString().trim();
  536. } else {
  537. filename = ctcpData[1];
  538. i = 1;
  539. }
  540. final int port;
  541. final int position;
  542. try {
  543. port = Integer.parseInt(ctcpData[++i]);
  544. position = Integer.parseInt(ctcpData[++i]);
  545. } catch (NumberFormatException nfe) {
  546. return;
  547. }
  548. final String token = (ctcpData.length - 1 > i) ? " "
  549. + ctcpData[++i] : "";
  550. // Now look for a dcc that matches.
  551. for (DCCTransfer send : DCCTransfer.getTransfers()) {
  552. if (send.getPort() == port && (new File(send.getFileName()))
  553. .getName().equalsIgnoreCase(filename)) {
  554. if ((!token.isEmpty() && !send.getToken().isEmpty())
  555. && (!token.equals(send.getToken()))) {
  556. continue;
  557. }
  558. final Parser parser = connection.getParser();
  559. final String nick = client.getNickname();
  560. if (ctcpData[0].equalsIgnoreCase("resume")) {
  561. parser.sendCTCP(nick, "DCC", "ACCEPT " + ((quoted) ? "\""
  562. + filename + "\"" : filename) + " " + port + " "
  563. + send.setFileStart(position) + token);
  564. } else {
  565. send.setFileStart(position);
  566. if (port == 0) {
  567. // Reverse dcc
  568. if (listen(send)) {
  569. if (send.getToken().isEmpty()) {
  570. parser.sendCTCP(nick, "DCC", "SEND "
  571. + ((quoted) ? "\"" + filename
  572. + "\"" : filename) + " "
  573. + DCC.ipToLong(send.getHost())
  574. + " " + send.getPort()
  575. + " " + send.getFileSize());
  576. } else {
  577. parser.sendCTCP(nick, "DCC", "SEND "
  578. + ((quoted) ? "\"" + filename
  579. + "\"" : filename)
  580. + " " + DCC.ipToLong(send.getHost())
  581. + " " + send.getPort()
  582. + " " + send.getFileSize() + " "
  583. + send.getToken());
  584. }
  585. }
  586. } else {
  587. send.connect();
  588. }
  589. }
  590. }
  591. }
  592. }
  593. /**
  594. * Retrieves the container for the placeholder.
  595. *
  596. * @since 0.6.4
  597. * @return This plugin's placeholder container
  598. */
  599. public synchronized PlaceholderContainer getContainer() {
  600. if (container == null) {
  601. createContainer();
  602. }
  603. return container;
  604. }
  605. /**
  606. * Removes the cached container.
  607. *
  608. * @since 0.6.4
  609. */
  610. public synchronized void removeContainer() {
  611. container = null;
  612. }
  613. /**
  614. * Create the container window.
  615. */
  616. protected void createContainer() {
  617. container = new PlaceholderContainer(this, config, mainWindow, urlBuilder, eventBus);
  618. windowManager.addWindow(container);
  619. }
  620. /**
  621. * Called when the plugin is loaded.
  622. */
  623. public void onLoad() {
  624. final File dir = new File(config.getOption(getDomain(),
  625. "receive.savelocation"));
  626. if (dir.exists()) {
  627. if (!dir.isDirectory()) {
  628. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  629. "Unable to create download dir (file exists instead)", ""));
  630. }
  631. } else {
  632. try {
  633. dir.mkdirs();
  634. dir.createNewFile();
  635. } catch (IOException ex) {
  636. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, null,
  637. "Unable to create download dir", ""));
  638. }
  639. }
  640. eventBus.subscribe(this);
  641. }
  642. /**
  643. * Called when this plugin is Unloaded.
  644. */
  645. public synchronized void onUnload() {
  646. eventBus.unsubscribe(this);
  647. if (container != null) {
  648. container.close();
  649. }
  650. }
  651. /**
  652. * Get the IP Address we should send as our listening IP.
  653. *
  654. * @param parser Parser the IRC Parser where this dcc is initiated
  655. *
  656. * @return The IP Address we should send as our listening IP.
  657. */
  658. public String getListenIP(final Parser parser) {
  659. final String configIP = config.getOption(getDomain(), "firewall.ip");
  660. if (!configIP.isEmpty()) {
  661. try {
  662. return InetAddress.getByName(configIP).getHostAddress();
  663. } catch (UnknownHostException ex) { //NOPMD - handled below
  664. //Continue below
  665. }
  666. }
  667. if (parser != null) {
  668. final String myHost = parser.getLocalClient().getHostname();
  669. if (!myHost.isEmpty()) {
  670. try {
  671. return InetAddress.getByName(myHost).getHostAddress();
  672. } catch (UnknownHostException e) { //NOPMD - handled below
  673. //Continue below
  674. }
  675. }
  676. }
  677. try {
  678. return InetAddress.getLocalHost().getHostAddress();
  679. } catch (UnknownHostException e) {
  680. // This is almost certainly not what we want, but we can't work out
  681. // the right one.
  682. return "127.0.0.1"; //NOPMD
  683. }
  684. }
  685. }