FileZilla客户端源码解析

时间:2021-09-01 22:26:11

FileZilla客户端源码解析

  FTP是TCP/IP协议组的协议,有指令通路和数据通路两条通道。一般来说,FTP标准命令TCP端口号是21,Port方式数据传输端口是20。

  FileZilla作为populate open source project,自然也有指令通路和数据通路。然而,FileZilla源码极少有注释,网上参考资料也寥寥无几。FileZilla用的到类库多且复杂(客户端wxWeidgets、GnuTLS、sqlite3、GNU IDN Library - Libidn,服务端boost、zlib),模式也不易理解(proxy模式、改编CAsynSocket的CAsynSocketEx、layer等)。想要完全搞懂FileZilla的细节似乎是件很困难的事情。好在我只需了解里面核心代码的工作原理,能封装为己所用即可。

  FileZilla官方论坛回答提问时指出,engine工程重点是ControlSocket.h和transfersocket.h,显然,一个对应ftp控制,另一个对应数据传输。interface工程重点是Mainfrm.h、state.h、commandqueue.h(出于效率考虑,很复杂)。engine工程其他重点类有 CServer, CServerPath, CDirectoryListing, COptionsBase,客户端interface工程其他重点类有 COptions。此外,客户端interface定义了资源文件dialog.xrc和menu.xrc(这两个用wxWidgets资源编辑器打开。用文本打开也可以,内容是xml格式)。该论坛链接地址为https://forum.filezilla-project.org/viewtopic.php?f=3&t=8443。截图如下

FileZilla客户端源码解析

1  command指令相关

1.1  CCommand指令类,头文件:commands.h,工程:engine,性质:抽象类、虚基类

  CCommand及其基类定义了ftp指令实体,是CCommandQueue操作的基本单元。例如:

 m_pCommandQueue->ProcessCommand(new CConnectCommand(server));
m_pCommandQueue->ProcessCommand(new CListCommand(path, _T(""), LIST_FLAG_FALLBACK_CURRENT));

  表示向CCommandQueue队列末尾插入连接指令CConnectCommand和获取文件列表指令CListCommand。

  CCommand子类由宏DECLARE_COMMAND定义,DECLARE_COMMAND定义的子类是实现了CCommand的纯虚函数GetId和Clone,实现如下:

 // Small macro to simplify command class declaration
// Basically all this macro does, is to declare the class and add the required
// standard functions to it.
#define DECLARE_COMMAND(name, id) \
class name : public CCommand \
{ \
public: \
virtual enum Command GetId() const { return id; } \
virtual CCommand* Clone() const { return new name(*this); }

  ccommand子类列表如下:

FileZilla客户端源码解析

  类图如下:

FileZilla客户端源码解析

1.2  CCommandQueue客户端命令队列,头文件:commandqueue.h,工程:engine,性质:客户端命令缓存操作

  CCommandQueue用作为CCommand基类的缓存操作,内部维护了list列表 std::list<CCommand *> m_CommandList。基本操作如下:

 void ProcessCommand(CCommand *pCommand);    //入队操作
void ProcessNextCommand(); //向m_pEngine提交command请求
void Finish(COperationNotification *pNotification); //CMainFrame的OnEngineEvent函数收到服务端nId_operation确认指令后,执行出队操作,并调用ProcessNextCommand

  以点击QuickConnect按钮为例,简单说一下上面3个函数的调用关系。QuickConnect将向队列顺序插入connectcommand和listcommand。connnect是list的基础,没有TCP连接自然不可能取回服务端列表信息,connect先入队,list后入队。

  入队操作ProcessCommand没什么好说的,源码如下,如果队列长度为1,取出首元素进行ProcessNextCommand处理。

 void CCommandQueue::ProcessCommand(CCommand *pCommand)
{
m_CommandList.push_back(pCommand);
if (m_CommandList.size() == )
{
m_pState->NotifyHandlers(STATECHANGE_REMOTE_IDLE);
ProcessNextCommand();
}
}

  ProcessNextCommand,内部用while取出列表第一个元素,提交一个command请求,也就是connect command,实现代码为:

int res = m_pEngine->Command(*pCommand);

  m_pEngine内部调用Windows socket函数WSAEventSelect发送connect请求(socket.h/cpp内实现),由于是异步调用,无法立即得到响应,返回FZ_REPLY_WOULDBLOCK(等价于WSAEWOULDBLOCK,定义在commands.h),并退出while循环。当list请求入队时,ProcessCommand监测到当前队列有两个元素,则直接返回。List command将待在connect command后,直至获取到服务端对connect的确认后,再进行m_pEngine->Command操作。

  客户端收到服务端确认后,CMainFrame::OnEngineEvent将收到通知NotificationId(notification.h/cpp)。如果通知为nId_operation类型,将调用Finish。在finish内部,将对nId_operation的返回值进行判断,如果返回FZ_REPLY_OK(服务端确认连接),执行以下代码:

 void CCommandQueue::Finish(COperationNotification *pNotification)
{
...
CCommand* pCommand = m_CommandList.front();
...
else if (pCommand->GetId() == cmd_connect && pNotification->nReplyCode == FZ_REPLY_OK)
{
m_pState->SetSuccessfulConnect();
m_CommandList.pop_front();
}
...
ProcessNextCommand();
}

  取出队列首元素并判断类型,如果是connect command且通知回传FZ_REPLY_OK,则表示connect成功,将首元素移出队列,ProcessNextCommand取出首元素(此时应当是list command),提交m_pEngine->Command请求,进行下一个command循环。如果客户端收到服务端对list请求的处理后,将list command出队,队列为空。

2  通知消息相关

2.1  CNotification通知类,头文件:notification.h,工程:engine,性质:抽象类、虚基类

  CNotification及其基类定义了服务端数据解析后的通知消息。这类消息将回传给CMainFrame,CMainFrame的OnEngineEvent函数接收到消息后,根据消息id参数NotificationId判断消息类型,并进行处理。NotificationId定义在notification.h,其子类和消息含义定义如下:

FileZilla客户端源码解析

  类图如下:

FileZilla客户端源码解析

2.2  Notification通知传递路径

  FTP使用TCP通信,底层自然是socket。客户端收到服务端数据后,将收到的字节流逐层转化成CNotification和其他结构。为方便理解CNotification,避免陷入wsWidgets底部的事件通知(FileZilla底层socket使用wsWidgets的event handler来处理事件,我不懂wsWidgets,花了很长时间才梳理清楚关系),我从CMainFrame对CNotification的处理开始介绍。

2.2.1  CMainFrame的OnEngineEvent函数,头文件:Mainfrm.h,工程:FileZilla,性质:CNotification对客户端处理函数

  看一下OnEngineEvent函数的主要结构:

 void CMainFrame::OnEngineEvent(wxEvent &event)
{
CNotification *pNotification = pState->m_pEngine->GetNextNotification();
while (pNotification)
{
switch (pNotification->GetID())
{
case nId_logmsg:
m_pStatusView->AddToLog(reinterpret_cast<CLogmsgNotification *>(pNotification));
if (COptions::Get()->GetOptionVal(OPTION_MESSAGELOG_POSITION) == )
m_pQueuePane->Highlight();
delete pNotification;
break;
case nId_operation:
pState->m_pCommandQueue->Finish(reinterpret_cast<COperationNotification*>(pNotification));
if (m_bQuit)
{
Close();
return;
}
break;
case nId_listing:
case nId_asyncrequest:
case nId_active:
case nId_transferstatus:
case nId_sftp_encryption:
case nId_local_dir_created:
default:
delete pNotification;
break;
}
pNotification = pState->m_pEngine->GetNextNotification();
}
}

  switch分支对通知类型作判断,如果是nId_logmsg通知,则用AddToLog函数(CStatusView类,StatusView.h,FileZilla工程)取出通知的文本数据,并在客户端界面上输出。如果是nId_operation通知,则表明CCommandQueue的头元素command已得到服务端确认,调用CCommandQueue的Finish函数将头元素出队,在Finish内部,投递下一个cmmand请求(见1.2节介绍)。其余消息类型没有验证,这里就不写了。

2.2.2  CFileZillaEnginePrivate类AddNotification函数,头文件:engineprivate.h,工程:engine,性质:管理CNotification队列,触发CMainFrame的OnEngineEvent函数

  CFileZillaEnginePrivate类功能很多也很重要,这里只讲与CNotification队列相关的内容。CFileZillaEnginePrivate类内部维护了CNotification队列m_NotificationList。底层服务通过调用CFileZillaEnginePrivate类的AddNotification函数向m_NotificationList内插入通知。AddNotification定义如下:

 void CFileZillaEnginePrivate::AddNotification(CNotification *pNotification)
{
m_lock.Enter();
m_NotificationList.push_back(pNotification); if (m_maySendNotificationEvent && m_pEventHandler)
{
m_maySendNotificationEvent = false;
m_lock.Leave();
wxFzEvent evt(wxID_ANY);
evt.SetEventObject(this);
wxPostEvent(m_pEventHandler, evt);
}
else
m_lock.Leave();
}

  在AddNotification内部,使用bool变量m_maySendNotificationEvent控制向CMainFrame发出wxPostEvent调用,该调用将触发CMainFrame的OnEngineEvent函数。而在CMainFrame的OnEngineEvent中,将循环从通知队列取出通知,直到队列为空时,m_maySendNotificationEvent又变成了true。该控制方式和CCommandQueue类似。

2.2.3  CFtpControlSocket类OnSocketEvent函数,头文件:ftpcontrolsocket.h,工程:engine,性质:control socket的实体类,CSocketEvent事件分类

  CFtpControlSocket是CRealControlSocket子类,后者又是CControlSocket的子类,CControlSocket和CRealControlSocket定义了一些接口,由CFtpControlSocket实现。CFtpControlSocke继承CRealControlSocket的OnSocketEvent函数被底层socket调用,用于对底层socket event的分类处理。OnSocketEvent代码如下:

 void CRealControlSocket::OnSocketEvent(CSocketEvent &event)
{
if (!m_pBackend)
return; switch (event.GetType())
{
case CSocketEvent::hostaddress:
{
const wxString& address = event.GetData();
LogMessage(Status, _("Connecting to %s..."), address.c_str());
}
break;
case CSocketEvent::connection_next:
if (event.GetError())
LogMessage(Status, _("Connection attempt failed with \"%s\", trying next address."), CSocket::GetErrorDescription(event.GetError()).c_str());
break;
case CSocketEvent::connection:
if (event.GetError())
{
LogMessage(Status, _("Connection attempt failed with \"%s\"."), CSocket::GetErrorDescription(event.GetError()).c_str());
OnClose(event.GetError());
}
else
{
if (m_pProxyBackend && !m_pProxyBackend->Detached())
{
m_pProxyBackend->Detach();
m_pBackend = new CSocketBackend(this, m_pSocket);
}
OnConnect();
}
break;
case CSocketEvent::read:
OnReceive();
break;
case CSocketEvent::write:
OnSend();
break;
case CSocketEvent::close:
OnClose(event.GetError());
break;
default:
LogMessage(Debug_Warning, _T("Unhandled socket event %d"), event.GetType());
break;
}
}

  例如,当收到事件类型为CSocketEvent::hostaddress时,LogMessage内部会调用AddNotification函数插入事件通知。收到CSocketEvent::read,会调用CFtpControlSocket的OnReceive接收消息,OnReceive内部解析服务端数据后会调用AddNotification。

2.2.4  CSocketEventDispatcher,头文件:socket.h,工程:engine,性质:socket 事件分发

   CSocketEventDispatcher实现了底层socket事件的分发,CSocketEventDispatcher内部维护了一个CSocketEvent列表m_pending_events。CSocketEventDispatcher基于singleton模式实现,唯一的外部访问接口是CSocketEventDispatcher::Get()函数,这意味着所有的socket event都由一个m_pending_events管理。CSocketEventDispatcher类定义如下:

 class CSocketEventDispatcher : protected wxEvtHandler
{
public:
void SendEvent(CSocketEvent* evt); //加入一个CSocketEvent
void RemovePending(const CSocketEventHandler* pHandler); //移除一个与CSocketEventHandler关联的SocketEvent
void RemovePending(const CSocketEventSource* pSource); //移除一个与CSocketEventHandler关联的SocketEvent
void UpdatePending(const CSocketEventHandler* pOldHandler, const CSocketEventSource* pOldSource, CSocketEventHandler* pNewHandler, CSocketEventSource* pNewSource); //修改SocketEvent内容
static CSocketEventDispatcher& Get(); //singleton访问接口
private:
CSocketEventDispatcher();
~CSocketEventDispatcher();
virtual bool ProcessEvent(wxEvent& event); //m_pending_events不为空的话,取出首元素,处理,调用OnSocketEvent
std::list<CSocketEvent*> m_pending_events; //socketEvent列表
wxCriticalSection m_sync; //互斥访问锁
static CSocketEventDispatcher m_dispatcher;//全局唯一实例
bool m_inside_loop;
};

  底层socket会调用CSocketEventDispatcher::Get().SendEvent(evt)函数向dispatcher加入socket event,由于低层socket(socket.h/cpp)内部使用了wxWidgets线程和事件管理,这里就不介绍了。有兴趣的可以在工程内搜索一下CSocketEventDispatcher::Get().SendEvent关键字,自行了解。

3  FileZilla客户端FTP控制指令流程

  综合所述,FileZilla客户端与服务端控制指令通信的流程大致如下:

  1:CCommandQueue的ProcessCommand函数提交command请求到command队列,如果command队列长度为1,则调用ProcessNextCommand处理首条command。

  2:ProcessNextCommand利用CFileZillaEngine的Command函数对请求进行分类处理,并提交到底层socket。

  3:底层socket利用异步通信WSAEventSelect向服务端发出请求。

  4:未收到服务端确认前,CCommandQueue首元素不出队,其余command请求暂停投递。

  5:底层socket收到服务端数据,底层socket调用CSocketEventDispatcher::Get().SendEvent将socket event加入socketevent队列

  6:SendEvent内部调用AddPendingEvent,触发ProcessEvent对socket event队列进行处理

  7:ProcessEvent判断队列是否为空,非空调用OnSocketEvent

  8:OnSocketEvent(由CSocketEventHandler的子类实现,如CFtpSocketControl)对socket event类型进行判断,logmsg解析、send、recv等操作,然后调用CFileZillaEnginePrivate类的AddNotification函数向m_NotificationList通知队列内插入操作结果Notification。

  9:AddNotification内部构造wxID_ANY消息,并post该消息到CMainFrame。

  10:CMainFrame的OnEngineEvent函数对nofication的ID进行判断,例如,logmsg通知,则打印信息。nId_operation,则将CCommandQueue首元素出队,取出下一个元素,投递请求。

  附上几个关键类的类关系图:

FileZilla客户端源码解析

4  FTP数据上传数据

  回顾1.1节,有command子类CFileTransferCommand,可以猜想,数据上传必然和此类有关。在QueueView.cpp的SendNextCommand内下断点,进入

 nt res = engineData.pEngine->Command(CFileTransferCommand(fileItem->GetLocalPath().GetPath() + fileItem->GetLocalFile(), fileItem->GetRemotePath(),    fileItem->GetRemoteFile(), fileItem->Download(), fileItem->m_transferSettings));

  给Engine提交filetransfile请求。进入FileZillaEngine后,调用FileTransfer函数,将请求提交给ControlSocket处理。

Engine工程预编译设置:

1:threadex.cpp和socket.cpp文件设置Not Using Precompiled Headers

2:FileZillaEngine.cpp设置为FileZilla客户端源码解析

3:其余cpp设置为:FileZilla客户端源码解析

1

FileZilla客户端源码解析的更多相关文章

  1. vs2008编译FileZilla客户端源码

    vs2008编译FileZilla客户端源码 下载FileZilla客户端源码,下载地址https://download.filezilla-project.org/. FileZilla客户端解决方 ...

  2. Netty5客户端源码解析

    Netty5客户端源码解析 今天来分析下netty5的客户端源码,示例代码如下: import io.netty.bootstrap.Bootstrap; import io.netty.channe ...

  3. Feign 客户端源码解析

    Feign的使用非常简单,增加如下配置之后,便可以使用Feign进行调用.非常简单是不是.主要的工作由Feign框架完成.业务代码只提供了一个Interface, 然后由Feign动态生成代理类来实现 ...

  4. Spring Cloud系列(四):Eureka源码解析之客户端

    一.自动装配 1.根据自动装配原理(详见:Spring Boot系列(二):Spring Boot自动装配原理解析),找到spring-cloud-netflix-eureka-client.jar的 ...

  5. 第零章 dubbo源码解析目录

    第一章 第一个dubbo项目 第二章  dubbo内核之spi源码解析 2.1  jdk-spi的实现原理 2.2 dubbo-spi源码解析 第三章 dubbo内核之ioc源码解析 第四章 dubb ...

  6. Fabric1&period;4源码解析:客户端安装链码

          看了看客户端安装链码的部分,感觉还是比较简单的,所以在这里记录一下.       还是先给出安装链码所使用的命令好了,这里就使用官方的安装链码的一个例子: #-n 指定mycc是由用户定义 ...

  7. Netty源码解析—客户端启动

    Netty源码解析-客户端启动 Bootstrap示例 public final class EchoClient { static final boolean SSL = System.getPro ...

  8. HDFS源码解析:教你用HDFS客户端写数据

    摘要:终于开始了这个很感兴趣但是一直觉得困难重重的源码解析工作,也算是一个好的开端. 本文分享自华为云社区<hdfs源码解析之客户端写数据>,作者: dayu_dls. 在我们客户端写数据 ...

  9. 转载-FileZilla Server源码分析(1)

    FileZilla Server源码分析(1) 分类: VC 2012-03-27 17:32 2363人阅读 评论(0) 收藏 举报 serversocketftp服务器usersockets工作 ...

随机推荐

  1. 新浪微博UWP UI意见征求

    各位园主,卑职最近在忙一些新浪微博UWP的事儿,其中有一些UI上的design和实现,拿出来见见公婆,请大家给个意见: 您是喜欢A还是B.麻烦直接回在评论区了,写A或B,愿意多写几句意见的更欢迎! 先 ...

  2. BZOJ 2448&colon; 挖油

    Description [0,x]中全是1,其余全是0,每个点有一个权值,求最坏情况下得到x的最小权值. Sol DP+单调队列. 首先就是一个 \(O(n^3)\) 的DP. \(f[i][j]\) ...

  3. poj2392 多重背包

    //Accepted 868 KB 188 ms //多重背包 #include <cstdio> #include <cstring> #include <iostre ...

  4. Java 异常Exception e中e的getMessage&lpar;&rpar;和toString&lpar;&rpar;以及 e&period;printStackTrace&lpar;&rpar;&semi;方法的区别

    Exception e中e的getMessage()和toString()方法的区别: 示例代码1: public class TestInfo {     private static String ...

  5. Thrift架构介绍

    Thrift是一个跨语言的服务部署框架,最初由Facebook于2007年开发,2008年进入Apache开源项目.Thrift通过一个中间语言(IDL, 接口定义语言)来定义RPC的接口和数据类型, ...

  6. 【经验总结】- IDEA无法显示Project目录怎么办

    1. 关闭IDEA 2.然后删除项目文件夹下的.idea文件夹 3.重新用IDEA工具打开项目 4.再次点击如下图即可搞定    

  7. alpha冲刺(1&sol;10)

    前言 队名:旅法师 作业链接 队长博客 燃尽图 会议 会议照片 会议内容 陈晓彬(组长) 今日进展: 召开会议 安排任务 博客撰写 构建之法的阅读 问题困扰: Java的学习感觉无从下手,学基础语法好 ...

  8. 【比赛游记】THUWC2019酱油记

    往期回顾:THUSC2018酱油记 day 0 早上 7 点的动车,不知道是从哪儿到哪儿的(雾),只知道从福建到广东 233333 一个值得思考的问题:福建人会不会被广东人吃啊? 动车上玩空洞骑士,可 ...

  9. IIS7的网站通过https访问提示ssl&lowbar;error&lowbar;rx&lowbar;record&lowbar;too&lowbar;long

    IIS7的网站通过https访问,提示ssl_error_rx_record_too_long,如下图所示: 解决办法: 一.导入服务器的SSL证书至IIS 1.打开IIS,找到服务器证书 2.导入本 ...

  10. Strom入门

    Worker.Executor.Task详解: Storm在集群上运行一个Topology时,主要通过以下3个实体来完成Topology的执行工作:1. Worker Process(工作进程)——S ...