お待たせしました!って誰も待ってないか...v(-_-;)
P105/P110MのKlapプロトコル(最新ファーム)対応版を作ってみた。
【対応ファームウェア】
P110M: 1.1.0 Build 231009 Rel.155719 以降
P105: 1.4.1 Build 20231103 Rel. 36519 以降
※ESP32対応版は下記を参照。
TP-LINK Tapo P110M のKlapプロトコル対応版 (ESP32)
ちなみにKlapプロトコル専用なので古いファームには下記投稿のコマンドを使用する必要がある。
TP-LINK TAPO P100/P105/P110をLinux/Windowsから直接制御する
【既知の問題】
現状ではセッション開始後の最初のリクエストがときどきHTTP-403エラーになるという不具合が残されている。セッション開始のためのハンドシェーク処理は成功するもののその後のリクエストがなぜかエラーになってしまいハンドシェークからやり直さないとリカバリーできないという現象でリクエストが成功した場合にはその後も問題はない。時間をかけて調べてみたが今のところ原因不明...orz
【セッション復元機能】
試験では通常0~2回、まれに最大5回までのリトライで成功してはいるがコマンド実行毎に新たにセッションを開始するとリトライにより実行時間にかなり悪影響を与えてしまう。
改善策としてセッション情報を保存/復元できるようにしてみたところ効果バツグン。通常ならコマンド実行毎に3回の通信が必要なところセッション復元できれば1回の通信で済むから3倍速となる。
セッション情報は次の場所に”tapo2-xxx.xxx.xxx.xxx”の名前でデバイス毎に保存され間違って削除されても問題はない。
linux: /var/tmp
windows: TEMP或いはTMP環境変数が示すフォルダ
【参照ライブラリ】
libb64は変更なし。(というか変更してはいけない)
json-developを3.11.3にアップデート。
mbedtlsを2.28.6にアップデート。
※mbedtlsの現在の最新はV3系であるが環境依存ファイルを生成するためにpythonやperlが必須となってしまったため断念しV2系の最新にアップデート。
【コンパイルの事前準備】
適当なフォルダにsources.zipを展開する。展開されたmbedtls-2.28.6フォルダに入って次のコマンドを実行する。
linux: make no_test
windows(MSYS2-MinGW): make CC=gcc no_test WINDOWS=1
【コンパイル】
展開先フォルダでmakeを実行する。再コンパイルするときはmakeする前にmake cleanを実行する。
【ダウンロード】
sources.zip
tapo2.exe (windows-x64)
【修正履歴】
2024-03-18
HiroさんよりCrypt::random()が落ちるというフィードバックあり。ググッてみたらmbedtlsのmbedtls_ctr_drbg_seed()にメモリリークの可能性があるらしいのでとりあえずrand()関数による実装に変更。おまけとしてVisual C++でもコンパイルできるようなコードに修正してみた...試してないけど。(-_-;)
2024-01-13
昨日からP105を回し続けているがエラーもなく別端末からの排他制御エラー(-1012)も発生しなくなったようだ。ということは現状でOKということかな?ふと気になって参考にさせて頂いたplugp100で試してみたらP105の電源オンオフは出来なかった。もしかして世界初のP105のKlapプロトコル対応?...それはともかく昨日はお天気も良くロケットも気持ちよさそうに飛び立っていって良き日であった。(^o^)
と思っていたらいきなりP105がエラーばかり起こして何もできなくなった。TAPOアプリからの操作も出来ない。でも暫く待ってたら復旧した。普段はそう頻繁にオンオフすることはないだろうという前提であれば大丈夫なのかな...(-_-;)
2024-01-12
P105の挙動が怪しい。HTTPリクエストの送信処理を変更してみたところだいぶましにはなったような気もするがごくまれにP105がハングアップしてしまうことがある。P105にはタイミングバグがあるのかな?もしそうだとすると厄介だ。P110Mは一日中ぶん回しても問題ないのに...
P105の-1301エラーは処理遅延の警告みたいであるが頻繁に出てウザイので無視するように修正。
2024-01-11
昨日はうまく動作していたP105が今日はなぜか-1012エラーで動かない...orz
そういえばP105のon/off操作にはterminalUUID指定が必要なことを思い出し実装を追加してみたところうまく動作するようにはなったが端末Aからon/off操作した後に端末Bからon/off操作しようとしても2分経過しないと-1012エラーになってしまう。なぜだろう?
とりあえず動作するようにはなったので再公開。(-_-;)
ちなみにP105はHWの処理能力が足りないのか不安定っぽい。これから購入する人はP110Mのほうが安定してるのでお勧め。
2024-01-10
mbedtlsの使い方のミスによるメモリーリークの修正、及び、通信毎にソケットを接続切断するように修正。
★★★昨日までにDLした方は入れ替えをお願いします。★★★
2024-01-09
httpclint.hが、ごちゃごちゃしてだいぶ見苦しなってきたので整理整頓&修正を行った。
2024-01-08
細かな改良。
2023-12-28
HTTP処理を改良しリトライの処理時間を短縮してみた。リトライしたのがわからないぐらいにはなった。かな。
2023-12-26
軽微なバグを修正。RaspberryPi/Ubuntu/Windowsで動作を確認。
2023-12-25
セッションタイムアウト値が間違っていたので修正。
【ソースコード】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 |
/* tapo2.h - TP-Link Tapo Klap Client Library Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <time.h> #include <string> #include "httpclient.h" #include "crypt.h" #include "debug.h" // Requires download. (https://github.com/nlohmann/json) #include "nlohmann/json.hpp" using json = nlohmann::json; // for convenience #define TAPO_HTTP_403_RETRY 10 #define TAPO_SEED_SIZE 16 #define TAPO_SHA1_SIZE 20 #define TAPO_SHA256_SIZE 32 #define TAPO_KEY_SIZE (128 >> 3) #define TAPO_SEQ_TYPE int32_t #define TAPO_DEBUG 0 class Tapo2 { public: Tapo2(void) { } virtual ~Tapo2(void) { } bool begin(const char *deviceIp, const char *username, const char *password) { struct __attribute__((packed)) { unsigned char username[TAPO_SHA1_SIZE]; unsigned char password[TAPO_SHA1_SIZE]; } auth; endSession(); _deviceIp = deviceIp; _crypt.digest(_crypt.MD_SHA1, (const unsigned char *)username, strlen(username), auth.username); _crypt.digest(_crypt.MD_SHA1, (const unsigned char *)password, strlen(password), auth.password); _crypt.digest(_crypt.MD_SHA256, auth.username, sizeof(auth), _authHash); #if !(TAPO_DEBUG & 2) // load session data loadSession(deviceIp); #endif // support for winsock if (!_http.startup()) { Debug::printf(__FILE__, __LINE__, "HttpClient::startup() failed.\n"); return false; } return true; } void end(void) { // save session data saveSession(); endSession(); // support for winsock _http.cleanup(); } bool setDeviceOn(bool on) { json payload, response; payload["method"] = "set_device_info"; payload["params"]["device_on"] = on; payload["terminalUUID"] = getTerminalUUID(); /* for P105 */ payload["requestTimeMils"] = millis(); /* for P105 */ if (request(payload, response)) { int status = response["error_code"].get<int>(); if ((status != 0) && (status != -1301)) Debug::printf(__FILE__, __LINE__, "TAPO Error Code (%d)\n", status); else return true; } return false; } bool getDeviceInfo(std::string &info) { json payload, response; payload["method"] = "get_device_info"; if (request(payload, response)) { int status = response["error_code"].get<int>(); if (status) Debug::printf(__FILE__, __LINE__, "TAPO Error Code = %d\n", status); else { char *temp = (char *)_request.data; std::string str; str = response["result"]["ssid"].dump(); temp[_crypt.base64Decode(str.c_str(), str.length(), temp)] = 0; response["result"]["ssid"] = temp; str = response["result"]["nickname"].dump(); temp[_crypt.base64Decode(str.c_str(), str.length(), temp)] = 0; response["result"]["nickname"] = temp; info = response["result"].dump(); /* for P105 */ str = response["result"]["mac"].dump(); snprintf(_session.terminalUUID, sizeof(_session.terminalUUID), "%s", str.c_str()); return true; } } info.clear(); return false; } bool getEnergyUsage(std::string &info) { json payload, response; payload["method"] = "get_energy_usage"; if (request(payload, response)) { int status = response["error_code"].get<int>(); if (status) Debug::printf(__FILE__, __LINE__, "TAPO Error Code = %d\n", status); else { info = response["result"].dump(); return true; } } info.clear(); return false; } private: const char *getTerminalUUID(void) { if (!_session.terminalUUID[0]) { /* for P105 */ std::string info; getDeviceInfo(info); } return _session.terminalUUID; } bool request(json& message, json& response) { int status = 403; for (int i = 0; (status == 403) && (i < TAPO_HTTP_403_RETRY); ++i) { if (beginSession()) { unsigned char hash[sizeof(_authHash)]; std::string msg = message.dump(); std::string url = "app/request?seq="; url += std::to_string(++_session.seq); memcpy(_request.sig, _session.sig, sizeof(_request.sig)); _request.seq[0] = _session.iv.seq[0] = (unsigned char)(_session.seq >> 24); _request.seq[1] = _session.iv.seq[1] = (unsigned char)(_session.seq >> 16); _request.seq[2] = _session.iv.seq[2] = (unsigned char)(_session.seq >> 8); _request.seq[3] = _session.iv.seq[3] = (unsigned char)(_session.seq >> 0); size_t len = _crypt.cipher(_crypt.OPERATION_ENCRYPT, (const unsigned char *)msg.c_str(), msg.length(), _request.data, _session.key, _session.iv.hash); _crypt.digest(_crypt.MD_SHA256, _request.sig, len + sizeof(hash), hash); memcpy(_request.sig, hash, sizeof(_request.sig) + sizeof(_request.seq)); _session.sessionStart = time(NULL); _http.clear(); _http.addHeader(_http.HTTP_CONTENT_TYPE, HTTP_CONTENT_TYPE); _http.addHeader(_http.HTTP_COOKIE, _session.sessionId); if ((status = _http.request(_deviceIp.c_str(), 80, _http.HTTP_METHOD_POST, url.c_str(), _request.sig, len + sizeof(hash))) != HTTP_CODE_OK) { if (TAPO_DEBUG || (i == TAPO_HTTP_403_RETRY - 1) || (status != 403)) Debug::printf(__FILE__, __LINE__, "(%d) HttpClient::request(\"%s\", %d, \"%s\", \"%s\", %p, %zu) = %d\n", i, _deviceIp.c_str(), 80, _http.HTTP_METHOD_POST, url.c_str(), _request.sig, len + sizeof(hash), status); } else { _request.data[_crypt.cipher(_crypt.OPERATION_DECRYPT, (unsigned char *)_http.response().content() + sizeof(hash), _http.response().length() - sizeof(hash), _request.data, _session.key, _session.iv.hash)] = 0; response = json::parse(_request.data); if (TAPO_DEBUG && i) Debug::printf(__FILE__, __LINE__, "TAPO Session Retries (%d)\n", i); return true; } } endSession(); } return false; } bool handshake1(void) { typedef struct __attribute__((packed)) { unsigned char remoteSeed[sizeof(_localSeed)]; unsigned char serverHash[sizeof(_authHash)]; } response_t; int status; unsigned char hash[sizeof(_authHash)]; struct __attribute__((packed)) { unsigned char localSeed[sizeof(_localSeed)]; unsigned char remoteSeed[sizeof(_remoteSeed)]; unsigned char authHash[sizeof(_authHash)]; } auth; _crypt.random(_localSeed, sizeof(_localSeed)); _session.sessionStart = time(NULL); _http.clear(); _http.addHeader(_http.HTTP_CONTENT_TYPE, HTTP_CONTENT_TYPE); if ((status = _http.request(_deviceIp.c_str(), 80, _http.HTTP_METHOD_POST, "app/handshake1", _localSeed, sizeof(_localSeed))) != HTTP_CODE_OK) Debug::printf(__FILE__, __LINE__, "HttpClient::request(\"%s\", %d, \"%s\", \"%s\", %p, %zu) = %d\n", _deviceIp.c_str(), 80, _http.HTTP_METHOD_POST, "app/handshake1", _localSeed, sizeof(_localSeed), status); else { response_t *response = (response_t *)_http.response().content(); memcpy(_remoteSeed, response->remoteSeed, sizeof(_remoteSeed)); memcpy(auth.remoteSeed, _remoteSeed, sizeof(auth.remoteSeed)); memcpy(auth.localSeed , _localSeed , sizeof(auth.localSeed )); memcpy(auth.authHash , _authHash , sizeof(auth.authHash )); _crypt.digest(_crypt.MD_SHA256, auth.localSeed, sizeof(auth), hash); if (memcmp(hash, response->serverHash, sizeof(hash)) != 0) Debug::printf(__FILE__, __LINE__, "Login failed\n"); else { std::string cookie = _http.response().getHeader(_http.HTTP_SET_COOKIE, ""); // parse cookie int left = 0; int right = -1; while (right + 1 < (int)cookie.length()) { left = right + 1; right = cookie.find_first_of(';', left); if (right < 0) right = cookie.length(); int mid = cookie.find_first_of('=', left); if (mid < 0) mid = right; std::string name = cookie.substr(left, mid - left); std::string value = cookie.substr(mid + 1, right - (mid + 1)); if (strcasecmp(name.c_str(), "TP_SESSIONID") == 0) snprintf(_session.sessionId, sizeof(_session.sessionId), "%s", cookie.substr(left, right - left).c_str()); if (strcasecmp(name.c_str(), "TIMEOUT") == 0) _session.sessionExpire = atoi(value.c_str()) - 60; } if ((_session.sessionId[0] != 0) && (_session.sessionExpire != 0)) return true; Debug::printf(__FILE__, __LINE__, "Cookie not set\n"); } } return false; } bool handshake2(void) { int status; unsigned char hash[sizeof(_authHash)]; struct __attribute__((packed)) { unsigned char remoteSeed[sizeof(_remoteSeed)]; unsigned char localSeed[sizeof(_localSeed)]; unsigned char authHash[sizeof(_authHash)]; } auth; memcpy(auth.remoteSeed, _remoteSeed, sizeof(auth.remoteSeed)); memcpy(auth.localSeed , _localSeed , sizeof(auth.localSeed )); memcpy(auth.authHash , _authHash , sizeof(auth.authHash )); _crypt.digest(_crypt.MD_SHA256, auth.remoteSeed, sizeof(auth), hash); _session.sessionStart = time(NULL); _http.clear(); _http.addHeader(_http.HTTP_CONTENT_TYPE, HTTP_CONTENT_TYPE); _http.addHeader(_http.HTTP_COOKIE, _session.sessionId); if ((status = _http.request(_deviceIp.c_str(), 80, _http.HTTP_METHOD_POST, "app/handshake2", hash, sizeof(hash))) != HTTP_CODE_OK) Debug::printf(__FILE__, __LINE__, "HttpClient::request(\"%s\", %d, \"%s\", \"%s\", %p, %zu) = %d\n", _deviceIp.c_str(), 80, _http.HTTP_METHOD_POST, "app/handshake2", hash, sizeof(hash), status); else { struct __attribute__((packed)) { unsigned char prefix[3]; unsigned char localSeed[sizeof(_localSeed)]; unsigned char remoteSeed[sizeof(_remoteSeed)]; unsigned char authHash[sizeof(_authHash)]; } cipher; memcpy(cipher.localSeed , _localSeed , sizeof(cipher.localSeed )); memcpy(cipher.remoteSeed, _remoteSeed, sizeof(cipher.remoteSeed)); memcpy(cipher.authHash , _authHash , sizeof(cipher.authHash )); // key cipher.prefix[0] = 'l'; cipher.prefix[1] = 's'; cipher.prefix[2] = 'k'; _crypt.digest(_crypt.MD_SHA256, cipher.prefix, sizeof(cipher), hash); memcpy(_session.key, hash, sizeof(_session.key)); // sig cipher.prefix[0] ='l'; cipher.prefix[1] ='d'; cipher.prefix[2] ='k'; _crypt.digest(_crypt.MD_SHA256, cipher.prefix, sizeof(cipher), hash); memcpy(_session.sig, hash, sizeof(_session.sig)); // iv cipher.prefix[1] = 'i'; cipher.prefix[2] = 'v'; _crypt.digest(_crypt.MD_SHA256, cipher.prefix + 1, sizeof(cipher) - 1, hash); memcpy(_session.iv.hash, hash, sizeof(_session.iv)); _session.seq = ((uint32_t)_session.iv.seq[0] << 24) | ((uint32_t)_session.iv.seq[1] << 16) | ((uint16_t)_session.iv.seq[2] << 8) | (_session.iv.seq[3] << 0); } return status == HTTP_CODE_OK; } bool beginSession(void) { // session timeouted ? if ((_session.sessionExpire != 0) && (time(NULL) - _session.sessionStart < _session.sessionExpire)) return true; // handshake if (handshake1() && handshake2()) return true; endSession(); return false; } void endSession(void) { memset(&_session, 0, sizeof(_session)); } void loadSession(const char *deviceIp) { const char *temp; #if __linux__ temp = "/var/tmp"; #else const char *TEMPNAMES[] = { "TEMP", "TMP" }; for (size_t i = 0; i < sizeof(TEMPNAMES) / sizeof(TEMPNAMES[0]); ++i) { temp = getenv(TEMPNAMES[i]); if (temp && *temp) break; } #endif _sessionFile = temp && *temp ? temp : "."; _sessionFile += "/tapo2-"; _sessionFile += deviceIp; FILE *fp; if ((fp = fopen(_sessionFile.c_str(), "rb"))) { fread(&_session, 1, sizeof(_session), fp); fclose(fp); } } void saveSession(void) { FILE *fp; if ((fp = fopen(_sessionFile.c_str(), "wb"))) { fwrite(&_session, 1, sizeof(_session), fp); fclose(fp); } } unsigned long millis(void) { #if defined(_WIN32) || defined(_WIN64) return GetTickCount(); #else struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ((unsigned long long)ts.tv_sec * 1000) + (ts.tv_nsec / 1000000); #endif } struct { time_t sessionStart; time_t sessionExpire; char sessionId[64]; TAPO_SEQ_TYPE seq; unsigned char key[TAPO_KEY_SIZE]; unsigned char sig[TAPO_SHA256_SIZE - sizeof(TAPO_SEQ_TYPE)]; struct __attribute__((packed)) { unsigned char hash[TAPO_KEY_SIZE - sizeof(TAPO_SEQ_TYPE)]; unsigned char seq[sizeof(TAPO_SEQ_TYPE)]; } iv; char terminalUUID[32]; /* for P105 */ } _session; struct __attribute__((packed)) { unsigned char sig[sizeof(_session.sig)]; unsigned char seq[sizeof(_session.seq)]; unsigned char data[HTTP_MAX_CONTENT_LENGTH]; } _request; std::string _sessionFile; std::string _deviceIp; HttpClient _http; Crypt _crypt; unsigned char _localSeed[TAPO_SEED_SIZE]; unsigned char _remoteSeed[TAPO_SEED_SIZE]; unsigned char _authHash[TAPO_SHA256_SIZE]; const char *HTTP_CONTENT_TYPE = "application/octet-stream"; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 |
/* httpclient.h - HTTP Client Library for Linux/Windows/Arduino Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <string> #include <vector> #define HTTP_CODE_OK 200 #define HTTP_CONNECT_TIMEOUT 3000 #define HTTP_SESSION_TIMEOUT 1000 #define HTTP_SESSION_TIMEOUT2 20 #define HTTP_MAX_CONTENT_LENGTH 2048 typedef struct { std::string name; std::string value; } http_name_value_t; class HttpHeader { protected: std::vector<http_name_value_t> _headers; void addNameValue(std::vector<http_name_value_t> &vec, const char *name, int value) { addNameValue(vec, name, std::to_string(value).c_str()); } void addNameValue(std::vector<http_name_value_t> &vec, const char *name, const char *value) { for(auto it = vec.begin(); it != vec.end(); ++it) { if (strcasecmp(it->name.c_str(), name) == 0) { it->value = value; return; } } vec.push_back({name, value}); } const char *getNameValue(std::vector<http_name_value_t> &vec, const char *name, const char *defval = "") { for(auto it = vec.begin(); it != vec.end(); ++it) { if (strcasecmp(it->name.c_str(), name) == 0) return it->value.c_str(); } return defval; } std::string& listNameValue(std::string& list, std::vector<http_name_value_t> &vec, const char *sep, const char *dlm, bool last) { for(auto it = vec.begin(); it != vec.end(); ++it) { if (list.size()) list += dlm; list += it->name; list += sep; list += it->value; } if (last && list.size()) list += dlm; return list; } public: void addHeader(const char *name, const char *value) { addNameValue(_headers, name, value); } void addHeader(const char *name, int value) { addNameValue(_headers, name, value); } const char *getHeader(const char *name, const char *defval = "") { return getNameValue(_headers, name, defval); } static const char *HTTP_METHOD_GET; static const char *HTTP_METHOD_POST; static const char *HTTP_HOST; static const char *HTTP_CONNECTION; static const char *HTTP_CONTENT_TYPE; static const char *HTTP_CONTENT_LENGTH; static const char *HTTP_SET_COOKIE; static const char *HTTP_COOKIE; static const char *HTTP_MIME_TEXT_HTML; static const char *HTTP_MIME_TEXT_PLAIN; static const char *HTTP_LF; }; class HttpRequest : public HttpHeader { public: void clear(void) { _headers.clear(); // addHeader(HTTP_CONNECTION, "close"); addHeader(HTTP_CONTENT_TYPE, HTTP_MIME_TEXT_HTML); addHeader(HTTP_CONTENT_LENGTH, "0"); } std::string& getHttpString(std::string& str, const char *host, const char *path, const char *method, int clen) { std::vector<http_name_value_t> headers = _headers; str = method; str += " /"; str += path; str += " HTTP/"; if (host && *host) { str += "1.1"; addNameValue(headers, HTTP_HOST, host); } else str += "1.0"; addNameValue(headers, HTTP_CONTENT_LENGTH, clen); listNameValue(str, headers, ": ", HTTP_LF, true); str += HTTP_LF; return str; } }; class HttpResponse : public HttpHeader { private: char _content[HTTP_MAX_CONTENT_LENGTH]; size_t _maxlen; size_t _length; int _mode; std::string _result[3]; public: HttpResponse(void) { clear(); } virtual ~HttpResponse(void) { } void clear(void) { _mode = 0; _maxlen = SIZE_MAX; _length = 0; _result[0] = ""; _result[1] = "-1"; _result[2] = ""; _headers.clear(); } char *buffer(size_t& len) { len = sizeof(_content) - _length; return _content + _length; } bool parse(int append) { char *p, *q, *r; int n; if (append > 0) { _length += append; if (_mode < 2) { for (p = _content, r = nullptr; (q = (char *)memchr(p, '\n', _length)); p = r) { if (*(q - 1) == '\r') *(q - 1) = 0; *q = 0; r = q + 1; if (_mode == 0) { for (size_t i = 0; p && *p; ++i) { p += strspn(p, " "); if ((q = strchr(p, ' '))) *q++ = 0; if (i < sizeof(_result) / sizeof(_result[0])) _result[i] = p; p = q; } _mode = 1; } else if (*p == 0) { _mode = 2; break; } else { p += strspn(p, " "); if ((q = strchr(p, ':'))) { *q++ = 0; q += strspn(q, " "); n = strlen(q); while (n && (*(q + --n) == ' ')) *(q + n) = 0; n = strlen(p); while (n && (*(p + --n) == ' ')) *(p + n) = 0; addHeader(p, q); if (strcasecmp(p, HTTP_CONTENT_LENGTH) == 0) { if ((n = atoi(q)) >= 0) _maxlen = n; } } } if (r >= _content + _length) break; } if (r) memcpy(_content, r, _length -= (size_t)(r - _content)); } } return (_mode < 2) || (_length < _maxlen); } const char *getHttpVersion(void) { return _result[0].c_str(); } int getHttpStatus(void) { return std::stoi(_result[1]); } const char *getHttpMessage(void) { return _result[2].c_str(); } const char *getContentType(void) { return getHeader(HTTP_CONTENT_TYPE, ""); } int getContentLength(void) { return std::stoi(getHeader(HTTP_CONTENT_LENGTH, "-1"), nullptr, 10); } size_t length(void) { return _mode == 2 ? _length : 0; } const char *content(void) { return _content; } std::string& getHttpString(std::string& str) { str.clear(); for (size_t i = 0; i < sizeof(_result) / sizeof(_result[0]); ++i) { str += _result[i]; if (i + 1 < sizeof(_result) / sizeof(_result[0])) str += ' '; } listNameValue(str, _headers, ": ", "\n", true); return str; } }; class BaseHttpClient : public HttpRequest { protected: HttpResponse _response; public: BaseHttpClient(void) { } virtual ~BaseHttpClient(void) { } void clear(void) { HttpRequest::clear(); _response.clear(); } virtual int open(const char *host, int port = 80) = 0; virtual void close(int sock) = 0; virtual int request0(int sock, const char *method, const char *path, const unsigned char *content, size_t clen) = 0; int request(const char *host, int port, const char *method, const char *path, const unsigned char *content, size_t clen) { int sock, status = -1; if ((sock = open(host, port)) >= 0) { status = request0(sock, method, path, content, clen); close(sock); } return status; } HttpResponse& response(void) { return _response; } virtual bool startup(void) { return true; } virtual void cleanup(void) { } }; /************************************************************ ARDUINO ************************************************************/ #if defined(ARDUINO) #include <Arduino.h> #if defined(ESP32) #include <WiFi.h> #endif class HttpClient : public BaseHttpClient { private: Client *_client; #if defined(ESP32) WiFiClient _esp32_wificlient; bool _esp32_wificlient_class; #endif public: HttpClient(void) { #if defined(ESP32) _client = &_esp32_wificlient; _esp32_wificlient_class = true; #else _client = nullptr; #endif } void client(Client& client) { _client = &client; #if defined(ESP32) _esp32_wificlient_class = false; #endif } int open(const char *host, int port = 80) override { if (!_client) return -1; #if defined(ESP32) if (_esp32_wificlient_class) { int status = ((WiFiClient *)_client)->connect(host, port, HTTP_CONNECT_TIMEOUT); if (status >= 0) ((WiFiClient *)_client)->setNoDelay(true); return status; } #endif return _client->connect(host, port); } void close(int sock) override { if ((sock >= 0) && _client) _client->stop(); } int request0(int sock, const char *method, const char *path, const unsigned char *content, size_t clen) override { _response.clear(); if ((sock >= 0) && _client) { std::string http, localIp; #if defined(EP32) if (_esp32_wificlient_class) localIp = ((WiFiClient *)_client)->localIP().toString().c_str(); #endif getHttpString(http, localIp.c_str(), path, method, clen); size_t len; char *buf = _response.buffer(len); if (len < http.size() + clen) return -3; strcpy(buf, http.c_str()); memcpy(buf + http.size(), content, clen); if (_client->write((const unsigned char *)buf, http.size() + clen) != http.size() + clen) return -2; _client->setTimeout(HTTP_SESSION_TIMEOUT); while (1) { buf = _response.buffer(len); len = _client->read((unsigned char *)buf, len); if (((len == 0) && !_client->connected()) || !_response.parse(len)) break; _client->setTimeout(HTTP_SESSION_TIMEOUT2); yield(); } } return _response.getHttpStatus(); } }; /************************************************************ WINDOWS ************************************************************/ #elif defined(_WIN32) || defined(_WIN64) #include <ws2tcpip.h> class HttpClient : public BaseHttpClient { public: int open(const char *host, int port = 80) override { int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock >= 0) { struct sockaddr_in addr = {}; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(host); unsigned long mode; mode = 1; ioctlsocket(sock, FIONBIO, &mode); ::connect(sock, (const struct sockaddr *)&addr, sizeof(addr)); mode = 0; ioctlsocket(sock, FIONBIO, &mode); struct timeval timeout = { HTTP_CONNECT_TIMEOUT / 1000, (HTTP_CONNECT_TIMEOUT % 1000) * 1000 }; fd_set wrfds; FD_ZERO(&wrfds); FD_SET(sock, &wrfds); if (select(sock + 1, NULL, &wrfds, NULL, &timeout) > 0) { char noDelay = 1; setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay)); } else { closesocket(sock); sock = -1; } } return sock; } void close(int sock) override { if (sock >= 0) { char c; shutdown(sock, SD_SEND); recv(sock, &c, sizeof(c), 0); closesocket(sock); } } int request0(int sock, const char *method, const char *path, const unsigned char *content, size_t clen) override { _response.clear(); if (sock >= 0) { std::string http, localIp; struct sockaddr_in addr; socklen_t socklen = sizeof(addr); if (getsockname(sock, (struct sockaddr*)&addr, &socklen) == 0) localIp = inet_ntoa(addr.sin_addr); getHttpString(http, localIp.c_str(), path, method, clen); size_t len; char *buf = _response.buffer(len); if (len < http.size() + clen) return -3; strcpy(buf, http.c_str()); memcpy(buf + http.size(), content, clen); if ((size_t)send(sock, buf, http.size() + clen, 0) != http.size() + clen) return -2; struct timeval timeout = { HTTP_SESSION_TIMEOUT / 1000, (HTTP_SESSION_TIMEOUT % 1000) * 1000 }; while (1) { fd_set rdfds; int n; FD_ZERO(&rdfds); FD_SET(sock, &rdfds); if ((n = select(sock + 1, &rdfds, NULL, NULL, &timeout)) < 0) break; if (n > 0) { buf = _response.buffer(len); n = recv(sock, buf, len, 0); } if ((n <= 0) || !_response.parse(n)) break; timeout = { HTTP_SESSION_TIMEOUT2 / 1000, (HTTP_SESSION_TIMEOUT2 % 1000) * 1000 }; } } return _response.getHttpStatus(); } bool startup(void) override { WSADATA wsaData; return WSAStartup(MAKEWORD(2, 2), &wsaData) == 0; } void cleanup(void) override { WSACleanup(); } }; /************************************************************ LINUX ************************************************************/ #else #include <time.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> class HttpClient : public BaseHttpClient { public: int open(const char *host, int port = 80) override { int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock >= 0) { struct sockaddr_in addr = {}; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(host); int flags = fcntl(sock, F_GETFL); fcntl(sock, F_SETFL, flags | O_NONBLOCK); ::connect(sock, (const struct sockaddr *)&addr, sizeof(addr)); fcntl(sock, F_SETFL, flags); struct timeval timeout = { HTTP_CONNECT_TIMEOUT / 1000, (HTTP_CONNECT_TIMEOUT % 1000) * 1000 }; fd_set wrfds; FD_ZERO(&wrfds); FD_SET(sock, &wrfds); if (select(sock + 1, NULL, &wrfds, NULL, &timeout) > 0) { int noDelay = 1; setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay)); } else { ::close(sock); sock = -1; } } return sock; } void close(int sock) override { if (sock >= 0) { char c; shutdown(sock, SHUT_WR); recv(sock, &c, sizeof(c), 0); ::close(sock); } } int request0(int sock, const char *method, const char *path, const unsigned char *content, size_t clen) override { _response.clear(); if (sock >= 0) { std::string http, localIp; struct sockaddr_in addr; socklen_t socklen = sizeof(addr); if (getsockname(sock, (struct sockaddr*)&addr, &socklen) == 0) localIp = inet_ntoa(addr.sin_addr); getHttpString(http, localIp.c_str(), path, method, clen); size_t len; char *buf = _response.buffer(len); if (len < http.size() + clen) return -3; strcpy(buf, http.c_str()); memcpy(buf + http.size(), content, clen); if ((size_t)send(sock, buf, http.size() + clen, MSG_NOSIGNAL) != http.size() + clen) return -2; struct timeval timeout = { HTTP_SESSION_TIMEOUT / 1000, (HTTP_SESSION_TIMEOUT % 1000) * 1000 }; while (1) { fd_set rdfds; int n; FD_ZERO(&rdfds); FD_SET(sock, &rdfds); if ((n = select(sock + 1, &rdfds, NULL, NULL, &timeout)) < 0) break; if (n > 0) { buf = _response.buffer(len); n = recv(sock, buf, len, 0); } if ((n <= 0) || !_response.parse(n)) break; timeout = { HTTP_SESSION_TIMEOUT2 / 1000, (HTTP_SESSION_TIMEOUT2 % 1000) * 1000 }; } } return _response.getHttpStatus(); } }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/* httpclient.cpp - HTTP Client Library for Linux/Windows Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "httpclient.h" const char *HttpHeader::HTTP_METHOD_GET = "GET"; const char *HttpHeader::HTTP_METHOD_POST = "POST"; const char *HttpHeader::HTTP_HOST = "Host"; const char *HttpHeader::HTTP_CONNECTION = "Connection"; const char *HttpHeader::HTTP_CONTENT_TYPE = "Content-Type"; const char *HttpHeader::HTTP_CONTENT_LENGTH = "Content-Length"; const char *HttpHeader::HTTP_SET_COOKIE = "Set-Cookie"; const char *HttpHeader::HTTP_COOKIE = "Cookie"; const char *HttpHeader::HTTP_MIME_TEXT_HTML = "text/html"; const char *HttpHeader::HTTP_MIME_TEXT_PLAIN = "text/plain"; const char *HttpHeader::HTTP_LF = "\r\n"; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
/* crypt.h - Crypt Library for MBEDTLS Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <string.h> #include <stdlib.h> #include <time.h> #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/cipher.h" #include "mbedtls/pk.h" #include "libb64/cencode.h" #include "libb64/cdecode.h" #include "debug.h" #define CRYPT_RANDOM_BUGFIX 1 class Crypt { public: typedef enum { CIPHER_ID_NONE = MBEDTLS_CIPHER_ID_NONE, CIPHER_ID_NULL = MBEDTLS_CIPHER_ID_NULL, CIPHER_ID_AES = MBEDTLS_CIPHER_ID_AES, CIPHER_ID_DES = MBEDTLS_CIPHER_ID_DES } CIPHER_ID; typedef enum { CIPHER_MODE_NONE = MBEDTLS_MODE_NONE, CIPHER_MODE_ECB = MBEDTLS_MODE_ECB, CIPHER_MODE_CBC = MBEDTLS_MODE_CBC, CIPHER_MODE_CFB = MBEDTLS_MODE_CFB, CIPHER_MODE_OFB = MBEDTLS_MODE_OFB, CIPHER_MODE_CTR = MBEDTLS_MODE_CTR, CIPHER_MODE_GCM = MBEDTLS_MODE_GCM, CIPHER_MODE_STREAM = MBEDTLS_MODE_STREAM, CIPHER_MODE_CCM = MBEDTLS_MODE_CCM } CIPHER_MODE; typedef enum { PADDING_PKCS7 = MBEDTLS_PADDING_PKCS7, PADDING_ONE_AND_ZEROS = MBEDTLS_PADDING_ONE_AND_ZEROS, PADDING_ZEROS_AND_LEN = MBEDTLS_PADDING_ZEROS_AND_LEN, PADDING_ZEROS = MBEDTLS_PADDING_ZEROS, PADDING_NONE = MBEDTLS_PADDING_NONE } PADDING; typedef enum { MD_NONE = MBEDTLS_MD_NONE, MD_MD2 = MBEDTLS_MD_MD2, MD_MD4 = MBEDTLS_MD_MD4, MD_MD5 = MBEDTLS_MD_MD5, MD_SHA1 = MBEDTLS_MD_SHA1, MD_SHA224 = MBEDTLS_MD_SHA224, MD_SHA256 = MBEDTLS_MD_SHA256, MD_SHA384 = MBEDTLS_MD_SHA384, MD_SHA512 = MBEDTLS_MD_SHA512, MD_RIPEMD160 = MBEDTLS_MD_RIPEMD160 } MD; typedef enum { OPERATION_NONE = MBEDTLS_OPERATION_NONE, OPERATION_DECRYPT = MBEDTLS_DECRYPT, OPERATION_ENCRYPT = MBEDTLS_ENCRYPT } OPERATION; Crypt(CIPHER_ID cipher_id = CIPHER_ID_AES, int key_bitlen = 128, CIPHER_MODE cipher_mode = CIPHER_MODE_CBC, PADDING padding_mode = PADDING_PKCS7) : _key_bitlen(key_bitlen), _cipher_id((mbedtls_cipher_id_t)cipher_id), _cipher_mode((mbedtls_cipher_mode_t)cipher_mode), _padding_mode((mbedtls_cipher_padding_t)padding_mode) { } virtual ~Crypt(void) { } bool random(unsigned char *output, size_t olen, const unsigned char *custom = nullptr, size_t len = 0) { #if CRYPT_RANDOM_BUGFIX srand(time(NULL)); while (olen) { unsigned short n = rand(); for (size_t i = 0; i < sizeof(n); ++i) { *output++ = n; if (--olen == 0) break; n >>= 8; } } return true; #else int status; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_entropy_context entropy; mbedtls_entropy_init(&entropy); mbedtls_ctr_drbg_init(&ctr_drbg); if ((status = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, custom, len)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_ctr_drbg_seed(%p, %p, %p, %p, %zu) = %d\n", &ctr_drbg, mbedtls_entropy_func, &entropy, custom, len, status); else if ((status = mbedtls_ctr_drbg_random(&ctr_drbg, output, olen)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_ctr_drbg_random(%p, %p, %zu) = %d\n", &ctr_drbg, output, olen, status); mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); return status == 0; #endif } size_t digest(MD md_type, const unsigned char *input, size_t ilen, unsigned char *output) { int status = 0; const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type((mbedtls_md_type_t)md_type); size_t olen = mbedtls_md_get_size(md_info); if (input && output) { if ((status = mbedtls_md(md_info, input, ilen, output)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_md(%p, %p, %zu, %p) = %d\n", md_info, input, ilen, output, status); } return status == 0 ? olen : 0; } size_t cipher(OPERATION operation, const unsigned char *input, size_t ilen, unsigned char *output, const unsigned char *key, const unsigned char *iv) { int status; size_t olen = 0; size_t iv_len = _key_bitlen >> 3; mbedtls_cipher_context_t cipher; mbedtls_cipher_init(&cipher); const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_values(_cipher_id, _key_bitlen, _cipher_mode); if ((status = mbedtls_cipher_setup(&cipher, cipher_info)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_cipher_setup(%p, %p) = %d\n", &cipher, cipher_info, status); else if ((status = mbedtls_cipher_set_padding_mode(&cipher, _padding_mode)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_cipher_set_padding_mode(%p, %d) = %d\n", &cipher, _padding_mode, status); else if ((status = mbedtls_cipher_setkey(&cipher, key, _key_bitlen, (mbedtls_operation_t)operation)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_cipher_setkey(%p, %p, %zu, %d) = %d\n", &cipher, key, _key_bitlen, operation, status); else if ((status = mbedtls_cipher_crypt(&cipher, iv, iv_len, input, ilen, output, &olen)) != 0) Debug::printf(__FILE__, __LINE__, "mbedtls_cipher_crypt(%p, %p, %zu, %p, %zu, %p, %p) = %d\n", &cipher, iv, iv_len, input, ilen, output, &olen, status); mbedtls_cipher_free(&cipher); return olen; } int base64Encode(const char *input, int ilen, char *output) { base64_encodestate state; base64_init_encodestate(&state); ilen = base64_encode_block(input, ilen, output, &state); return ilen + base64_encode_blockend(output + ilen, &state); } int base64Decode(const char *input, int ilen, char *output) { base64_decodestate state; base64_init_decodestate(&state); return base64_decode_block(input, ilen, output, &state); } private: int _key_bitlen; mbedtls_cipher_id_t _cipher_id; mbedtls_cipher_mode_t _cipher_mode; mbedtls_cipher_padding_t _padding_mode; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
/* debug.h - Debug Utility Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stdio.h> #include <stdarg.h> #include <string.h> class Debug { private: static bool _output; public: static bool enable(void) { return _output; } static void enable(bool output) { _output = output; } static void printf(const char *file, int line, const char *format,...) { if (_output) { const char *p = strrchr(file, '/'); const char *q = strrchr(file, '\\'); if (p < q) p = q; fprintf(stderr, "[%s:%d] ", p ? p + 1 : file, line); va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } } static void printf(const char *format,...) { if (_output) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } } static void printbytes(const unsigned char *buf, size_t len) { if (_output) { while (len--) fprintf(stderr, "%02X", *buf++); fprintf(stderr, "\n"); } } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* debug.cpp - Debug Utility Copyright (c) 2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "debug.h" bool Debug::_output = true; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
TARGET = tapo2 OBJS += tapo2.o OBJS += httpclient.o OBJS += debug.o OBJS += ./libb64/cencode.o OBJS += ./libb64/cdecode.o INCLUDES += -I. INCLUDES += -I./json-develop-3.11.3/include INCLUDES += -I./mbedtls-2.28.6/include LIBS += -L./mbedtls-2.28.6/library LIBS += -lmbedcrypto LIBS += -lm ifeq ($(OS),Windows_NT) LIBS += -lwsock32 LIBS += -lws2_32 endif LIBS += -static -lstdc++ CFLAGS += $(INCLUDES) -Wall CXXFLAGS += $(CFLAGS) -std=c++11 -Wno-psabi LDFLAGS = .c.o: $(CC) $(CFLAGS) -c $< -o $(<:.c=.o) .cpp.o: $(CXX) $(CXXFLAGS) -c $< -o $(<:.cpp=.o) $(TARGET): $(OBJS) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS) all: $(TARGET) .PHONY: clean clean: $(RM) $(TARGET) $(OBJS) |