Khiêm Nguyễn
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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 ![](https://hackmd.io/_uploads/SkTi2tU53.png) 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. ![](https://hackmd.io/_uploads/SkQlfNYqn.png) ## 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 ![](https://hackmd.io/_uploads/rJTaTxEn3.png) ## 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 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully