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

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