[Lua] 使用 LuaSec 套件來連線 HTTPS 網站

[Lua] 使用 LuaSec 套件來連線 HTTPS 網站

之前在 [Lua] 設定 HTTP 連線時的逾時秒數 這篇裡,

有用到  socket.http 來連線到 HTTP 網站,

不過用它來連 HTTPS 網站時,不知道為什麼,

有時候會成功,有時候會失敗…

 

舉例來說,用同樣的 http 物件,

連 Google 可以,連台南市圖卻不行:

> http = require("socket.http")

> http.request{url = "https://www.google.com"}
1	200	table: 0x7fdb7340c2c0	HTTP/1.1 200 OK

> http.request{url = "https://lib.tnml.tn.edu.tw/"}
nil	connection refused

 

查了一下,有人是說 HTTPS 網站要用 LuaSec 來連線才行~

先用  luarocks 來安裝 luasec,

不過它要求要有 OpenSSL 的標頭檔才能編譯:

testuser@localhost ~ $ sudo luarocks install luasec

Warning: falling back to wget - install luasec to get native HTTPS support
Installing https://luarocks.org/luasec-1.0.1-1.src.rock

Error: Could not find header file for OPENSSL
  No file openssl/ssl.h in /usr/local/include
  No file openssl/ssl.h in /usr/include
  No file openssl/ssl.h in /include
You may have to install OPENSSL in your system and/or pass OPENSSL_DIR or OPENSSL_INCDIR to the luarocks command.
Example: luarocks install luasec OPENSSL_DIR=/usr/local

 

在 Mac 上,可以直接用 Homebrew 來安裝 openssl 套件:

testuser@localhost ~ $ brew info openssl

openssl@1.1: stable 1.1.1k (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/openssl@1.1/1.1.1k (8,071 files, 18.5MB)
  Poured from bottle on 2021-03-27 at 17:00:38
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openssl@1.1.rb
License: OpenSSL
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@1.1 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> /Users/jeff_lai/.bash_profile

For compilers to find openssl@1.1 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

For pkg-config to find openssl@1.1 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"

 

接著就可以在 luarocks 的指令裡加上  OPENSSL_DIR 參數,

來指定 OpenSSL 目錄的位置了:

sudo luarocks install luasec OPENSSL_DIR=/usr/local/opt/openssl

 

安裝好 LuaSec 後,

可以使用  ssl.https 物件來對 HTTPS 網站連線囉:

> https = require 'ssl.https'
> https.request{url = "https://lib.tnml.tn.edu.tw"}
1	200	table: 0x7fa74792af40	HTTP/1.1 200 OK

 

參考資料:

(本頁面已被瀏覽過 11 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料