openDataConnection method

Future<bool> openDataConnection()

Implementation

Future<bool> openDataConnection() async {
  try {
    await _gettingDataSocket;
  } catch (e) {
    logger.generalLog('Error while waiting for data socket: $e');
  }
  if (dataSocket == null) {
    sendResponse('425 Can\'t open data connection');
    return false;
  }
  sendResponse('150 Opening data connection');
  // RFC 4217 §9 and §12.6/§12.7: the protection level is checked on the
  // command that starts the transfer, and TLS is negotiated on the data
  // connection after the 150 reply. Some clients (e.g. Python ftplib) only
  // start the handshake once they have read the 150, so it must not be
  // awaited before replying. The FTP server is always the TLS server here,
  // even in active mode where it opened the TCP connection (RFC 4217 §7).
  if (protectionLevel == ProtectionLevel.private_ &&
      securityContext != null) {
    final rawSocket = dataSocket!;
    try {
      dataSocket = await SecureSocket.secureServer(
        rawSocket,
        securityContext!,
      ).timeout(const Duration(seconds: 30));
    } catch (e) {
      logger.generalLog('TLS negotiation failed on data connection: $e');
      rawSocket.destroy();
      dataSocket = null;
      try {
        dataListener?.close();
      } catch (_) {}
      dataListener = null;
      // RFC 4217 §9: close the data port and follow the 150 with 522.
      sendResponse('522 TLS negotiation failed on data connection');
      return false;
    }
  }
  return true;
}