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 29KB

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