您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

DCCManager.java 30KB

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