# Remote Procedure Call
*Khái quát:*
Remote Procedure Call(RPC) là 1 kỹ thuật tính toán phân tán trong đó 1 chương trình máy tính gọi 1 thủ tục(hàm con hoặc yêu cầu) để thực thi tại 1 địa chỉ khác với chính nó. Thủ tục có thể trên chính máy đó hoặc tại 1 máy khác trong cùng 1 hệ thống mạng
Ý tưởng đằng sau kĩ thuật này là cho 1 máy tính có thể gọi hoặc thực thi 1 hàm con tại 1 máy tính khác tương tự như cái nó gọi và thực thi hàm con tại local, nhưng các chi tiết về giao tiếp giữa client-server sẽ được ẩn đi với client.
RPC là 1 giao thức request-response, tuân theo mẫu mô hình client-server

Client sẽ tạo 1 yêu cầu để thực thi 1 thủ tục trên 1 máy server. Giống với lệnh call cục bộ tại local, client sẽ treo cho đến khi kết quả của thủ tục được trả về từ server. Các tham số của thủ tục được truyền thông qua network đến với server. Thủ tục được thực thi trên server, và cuối cùng kết quả được trả về client. Rồi Client tiếp tục thực thi
*Chi tiết:*
Trước khi đi sâu vào kỹ thuật này, ta cần biết rằng: Trong quá trình lập trình ứng dụng, 1 ứng dụng có thể có nhiều tiến trình khác nhau, chạy đồng thời. Các tiến trình này có thể chạy trên cùng 1 hệ thống, hoặc chạy trên nhiều hệ thồng khác nhau. Các tiến trình này trao đổi thông tin qua lại với nhau,quá trình này được gọi là **Interprocess Communications(IPC)**. Và **Remote Procedure Call(RPC)** được sinh ra để khiến cho việc thực hiện IPC dễ dàng hơn.
Microsoft Windows API cung cấp cơ chế RPC tuân theo **Open Software Foundation (OSF), Distributed Computing Environment (DCE)**. Có nghĩa là, bất kì ứng dụng nào sử dụng RPC dựa vào Windows API, hoàn toàn có thể trao đổi với ứng dụng khác sử dụng RPC theo chuẩn DCE.
*Các thuật ngữ cần lưu ý*
* Interface: Giao diện mô tả cách thức hoạt động của RPC, RPC có 1 ngôn ngữ riêng để mô tả cách hoạt động của nó, được gọi là **Interface Denfinition Language (IDL)**. IDL của Microsoft là MIDL.
* Remote Procedure: là các hàm tuân theo interface được định nghĩa trước
* Client: là chương trình sử dụng RPC để thực hiện 1 nhiệm vụ
* Server: là nơi nhận yêu cầu từ các Client, thực hiện nhiệm vụ định trước, sau đó trả kết quả về Client]
*Các thành phân chính của Microsoft RPC*
* Trình biên dịch MIDL (MIDL Compiler)
* Các thư viện liên kết động
* Name Service Provider
* Endpoint Mapper
## Trình biên dịch MIDL (MIDL Compiler)
Đây là ngôn ngữ mô tả interface được Microsoft sử dụng. Viết một file IDL cũng tương tự như khi định nghĩa header trong ngôn ngữ C, nhưng bản thân ngôn ngữ này có thêm một vài keyword khác biệt. IDL tập trung mô tả thuộc tính của hàm và các tham số của hàm. Sau khi mô tả IDL xong, nó cần được dịch thành các file .c và .h thông qua MIDL compiler.
Để dễ hiểu, mình sẽ ví dụ như sau:
```c=
#include <stdio.h>
#include <string.h>
#define MAX_BUFF (256)
void SayYouDo(const char *s)
{
printf("%s", s);
}
void main(void)
{
char buf[MAX_BUFF];
printf("Enter a string and press [ENTER]. Enter QUIT to exit.\n");
do
{
memset(buf, 0, sizeof(buf));
if (fgets(buf, 256, stdin)== NULL)
break;
SayYouDo(buf);
} while (strcmp(buf, "QUIT\n"));
}
```
Logic của chương trình rất đơn giản
* Đợi người dùng nhập dữ liệu, hiển thị nó ra màn hình.
* Nếu người dùng nhập QUIT, thì hiển thị QUIT và thoát.
Câu hỏi được đặt ra là, sẽ ra sao nếu như ta sử dụng RPC với chương trình này.
### Build IDL
```midl=
// File SayYouDo.idl
// Compiling SayYouDo.idl:
// midl /app_config SayYouDo.idl
[
// interface unique identifier.
uuid(DB875AD4-0DC5-4FF9-8245-79CA730FA6F3),
// Version 1.0 of this interface.
version(4.0),
// This interface will use an implicit binding
implicit_handle(handle_t hBinding)
]
interface RpcExample
{
void SayYouDo(
[in, string] const char* s // a zero-terminated string.
);
void ShutdownRpc(void);
}
```
Mô tả trên bao gồm
**UUID**: Các interface được phân biệt với nhau thông qua **UUID**, địa chỉ này là duy nhất.
**version**: Cho biết phiên bản của interface
**Binding handle**:
Trên thực tế, RPC client và RPC server có thể nằm trên cùng một máy tính hoặc trên 2 máy tính khác nhau. Client và server có thể giao tiếp thông qua nhiều loại giao thức khác nhau (TCP, Named pipe, ...). Về mặt logic, client và server chỉ hiểu là đang kết nối với nhau thông qua binding handle mà không cần hiểu nền tảng giao tiếp bên dưới (TCP, Named pipe, ...) đang dùng là gì.
Có 3 loại binding handle có thể dùng được, bao gồm: **implict_handle**, **auto_handle**, **explicit_handle**
* **implicit_handle** có nghĩa là binding handle được hiểu ngầm định, không cần phải có trong tham số khi gọi hàm RPC. Nên dùng loại này.
* **explicit_handle** có nghĩa là binding handle được hiểu tường minh, buộc phải có trong tham số khi gọi hàm RPC. Đây là tham số đầu tiên của hàm.
* **auto_handle:** có thể hiểu là kiểu kết hợp của 2 kiểu trên.
Biên dịch MIDL bằng MIDL compiler có sẵn của Visual Studio
**interface**: Định nghĩa interface bao gồm tên hàm và các tham số. Các tham số cần định nghĩa rõ kiểu dữ liệu.
Sử dụng MIDL Compiler để sinh code cho client và server. Quá trình này sẽ tạo ra 3 file:
SayYouDo.h: Header cho cả client và server
SayYouDo_c.c: Client stub
SayYouDo_s.c: server stub
Trong quá trình biên dịch, cần lưu ý: chọn đúng nền tảng (x86, x64 hay ia64) khi biên dịch. Tham số này có thể tham khảo thông qua tùy chọn /win32, /x64 hoặc /ia64 của midl compiler.

## RPC Server
```c++=
// Server.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include "SayYouDo_h.h"
#pragma comment(lib, "Rpcrt4.lib") // RPC Functions
#if defined UNICODE || defined _UNICODE
#define RPC_TSTR RPC_WSTR
#else
#define RPC_TSTR RPC_CSTR
#endif
//#define RPC_PROTOCOL RPC_TSTR("ncacn_ip_tcp")
//#define RPC_NETWORK_ADDRESS (NULL)
//#define RPC_END_POINT RPC_TSTR("4747")
HANDLE hStopEvent = NULL;
// Server functions.
#ifdef __cplusplus
extern "C" {
#endif
void SayYouDo(const unsigned char* s)
{
std::cout << s;
}
void ShutdownRpc(void)
{
if (hStopEvent)
{
SetEvent(hStopEvent);
}
}
#ifdef __cplusplus
}
#endif
// Naive security callback.
RPC_STATUS CALLBACK SecurityCallback(RPC_IF_HANDLE /*hInterface*/, void* /*pBindingHandle*/)
{
return RPC_S_OK; // Always allow anyone.
}
int main(int argc, char* argv[])
{
RPC_STATUS status;
hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (hStopEvent == NULL)
return 0;
// Uses the protocol combined with the endpoint for receiving RPC.
std::cout << "Initializing RPC server ..." << std::endl;
status = RpcServerUseProtseqEpA(
(RPC_CSTR)("ncacn_ip_tcp"), // protocol.
RPC_C_PROTSEQ_MAX_REQS_DEFAULT, // Backlog queue .
(RPC_CSTR)("4747"), // endpoint.
NULL); // No security.
if (status)
exit(status);
std::cout << "Registering RPC server ..." << std::endl;
status = RpcServerRegisterIf2(
RpcExample_v4_0_s_ifspec, // Interface to register.
NULL,
NULL,
RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH, // Forces use of security callback.
RPC_C_LISTEN_MAX_CALLS_DEFAULT, // Use default number of concurrent calls.
(unsigned)-1, // Infinite max size of incoming data blocks.
SecurityCallback); // Naive security callback.
if (status)
exit(status);
// Start to listen for RPC.
std::cout << "Listen RPC server ..." << std::endl;
status = RpcServerListen(
1, // Recommended minimum number of threads.
RPC_C_LISTEN_MAX_CALLS_DEFAULT, // Recommended maximum number of threads.
TRUE); //dont wait
// Start listening now. Wait for stop-message
WaitForSingleObject(hStopEvent, INFINITE);
Sleep(1000);
RpcMgmtStopServerListening(RpcExample_v4_0_s_ifspec);
RpcServerUnregisterIf(RpcExample_v4_0_s_ifspec, NULL, 0);
CloseHandle(hStopEvent);
std::cout << "Server stopped." << std::endl;
if (status)
exit(status);
return 0;
}
// Memory allocator
void* __RPC_USER midl_user_allocate(size_t size)
{
return malloc(size);
}
void __RPC_USER midl_user_free(void* p)
{
free(p);
}
```
### Đăng kí interface
Chương trình sẽ đăng kí một interface với hệ thống thông qua hàm RpcServerRegisterIf2.
```c++=
RPC_STATUS RPC_ENTRY RpcServerRegisterIf2(
RPC_IF_HANDLE IfSpec,
UUID *MgrTypeUuid,
RPC_MGR_EPV *MgrEpv,
unsigned int Flags,
unsigned int MaxCalls,
unsigned int MaxRpcSize,
RPC_IF_CALLBACK_FN *IfCallbackFn
);
```
Các bạn nên dùng hàm RpcServerRegisterIf2 hoặc RpcServerRegisterIfEx thay cho RpcServerRegisterIf khi đăng kí interface. Nên thiết lập cờ RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH khi đăng kí interface, IfCallbackFn thì có thể thiết lập hoặc đặt bằng NULL.
Điều này sẽ tránh cho client ( xin nhắc lại là client) bị crash giữa chừng khi kết nối tới RPC server. Lỗi này khá khó chịu! Client sẽ bị crash khi gọi hàm NdrClientCall2, trong lúc cố kết nối tới server. Các bạn sẽ không bao giờ dùng hàm NdrClientCall2 trong code của các bạn, NdrClientCall2 được sinh ra tự động trong client code stub.
RpcServerListen để bắt đầu nhận kết nối từ client. Sau hàm này, server có thể coi là sẵn sàng.
## RPC Client
```c++=
#include <iostream>
#include <string>
#include "SayYouDo_h.h"
#pragma comment(lib, "Rpcrt4.lib") // RPC Functions
#if defined UNICODE || defined _UNICODE
#define RPC_TSTR RPC_WSTR
#else
#define RPC_TSTR RPC_CSTR
#endif
//#define RPC_PROTOCOL RPC_CSTR("ncacn_np")
//#define RPC_NETWORK_ADDRESS (NULL)
//#define RPC_END_POINT RPC_CSTR("\pipe\hello")
int main(int argc, char* argv[])
{
RPC_STATUS status;
RPC_CSTR szStringBinding = NULL;
// Creates a string binding handle.
status = RpcStringBindingComposeA(
NULL, // UUID to bind to.
(RPC_CSTR)("ncacn_ip_tcp"), // protocol.
(RPC_CSTR)("localhost"), // network address to use.
(RPC_CSTR)("4747"), // endpoint.
NULL, // Protocol dependent network options to use.
&szStringBinding); // String binding output.
if (status)
exit(status);
// Validates the format of the string binding handle
status = RpcBindingFromStringBindingA(
szStringBinding, // The string binding to validate.
&hBinding); // Put the result in the implicit binding handle
if (status)
exit(status);
char buf[256];
memset(buf, 0, sizeof(buf));
bool bStopped = false;
std::cout << "Enter a string and press [ENTER]. Enter QUIT to exit." << std::endl;
do
{
fgets(buf, 256, stdin);
bStopped = (strcmp(buf, "QUIT\n") == 0);
RpcTryExcept
{
SayYouDo((const unsigned char*)buf);
}
RpcExcept(1)
{
std::cerr << "Exception " << RpcExceptionCode() << std::endl;
bStopped = true;
break;
}
RpcEndExcept
} while (!bStopped);
// send shutdown signal
RpcTryExcept
{
// Calls the RPC function.
ShutdownRpc();
}
RpcExcept(1)
{
std::cerr << "Exception " << RpcExceptionCode() << std::endl;
}
RpcEndExcept
// Free the memory allocated by a string.
status = RpcStringFreeA(
&szStringBinding); // String to be freed.
if (status)
exit(status);
// Releases binding handle
status = RpcBindingFree(
&hBinding); // Frees the implicit binding handle
if (status)
exit(status);
return 0;
}
// Memory allocator
void* __RPC_USER midl_user_allocate(size_t size)
{
return malloc(size);
}
void __RPC_USER midl_user_free(void* p)
{
free(p);
}
```
Client sử dụng `RpcStringBindingComposeA()` để tạo binding string và chuyển đổi string thành binding handle thông qua hàm `RpcBindingFromStringBindingA()`
Client cũng cần 2 hàm cho việc quản lý bộ nhớ động, như ở server.
Sau khi tạo handle thành công, client sẽ gọi hàm thông qua RPC như sau:
```c++=
RpcTryExcept
{
SayYouDo((const unsigned char *)buf);
}
RpcExcept(1)
{
std::cerr << "Exception " << RpcExceptionCode() << std::endl;
}
RpcEndExcept
```
## Compile and Link

## Lưu ý khi dùng **explicit_handle**
Trong trường hợp dùng **explicit_handle** thì cần khai báo như sau:
```MIDL=
// File SayYouDo.idl
// Compiling SayYouDo.idl:
// midl /app_config SayYouDo.idl
[
// interface unique identifier.
uuid(DB875AD4-0DC5-4FF9-8245-79CA730FA6F3),
// Version 1.0 of this interface.
version(4.0),
explicit_handle
]
interface RpcExample
{
void SayYouDo(
[in] handle_t hBinding,
[in, string] const char* s // a zero-terminated string.
);
void ShutdownRpc( [in] handle_t hBinding );
}
```
**Server**:
```c++=
// Server functions.
#ifdef __cplusplus
extern "C"{
#endif
void SayYouDo(handle_t hBinding, const unsigned char *s)
{
std::cout << s;
}
void ShutdownRpc( handle_t hBinding)
{
if (hStopEvent)
{
SetEvent(hStopEvent);
}
}
#ifdef __cplusplus
}
#endif
```
**Client**:
```c++=
// Validates the format of the string binding handle
status = RpcBindingFromStringBinding(
szStringBinding, // The string binding to validate.
&hBinding); // Put the result in the implicit binding handle
if (status)
exit(status);
RpcTryExcept
{
SayYouDo(hBinding, (const unsigned char *)buf);
}
RpcExcept(1)
{
std::cerr << "Exception " << RpcExceptionCode() << std::endl;
}
RpcEndExcept
```