/* * Authored by Alex Hultman, 2018-2026. * Intellectual property of third-party. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "App.h" #include #include "Utilities.h" using namespace v8; /* uWS.App.ws('/pattern', behavior) */ template void uWS_App_ws(const FunctionCallbackInfo &args) { /* pattern, behavior */ if (missingArguments(2, args)) { return; } Isolate *isolate = args.GetIsolate(); PerContextData *perContextData = (PerContextData *) Local::Cast(args.Data())->Value(); APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); /* This one is default constructed with defaults */ typename APP::template WebSocketBehavior behavior = {}; NativeString pattern(args.GetIsolate(), args[0]); if (pattern.isInvalid(args)) { return; } NoexceptPersistent upgradePf; NoexceptPersistent openPf; NoexceptPersistent messagePf; NoexceptPersistent drainPf; NoexceptPersistent closePf; NoexceptPersistent droppedPf; NoexceptPersistent pingPf; NoexceptPersistent pongPf; NoexceptPersistent subscriptionPf; /* Get the behavior object */ if (args.Length() == 2) { Local behaviorObject = Local::Cast(args[1]); /* maxPayloadLength or default */ MaybeLocal maybeMaxPayloadLength = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "maxPayloadLength", NewStringType::kNormal).ToLocalChecked()); if (!maybeMaxPayloadLength.IsEmpty() && !maybeMaxPayloadLength.ToLocalChecked()->IsUndefined()) { behavior.maxPayloadLength = maybeMaxPayloadLength.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(); } /* idleTimeout or default */ MaybeLocal maybeIdleTimeout = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "idleTimeout", NewStringType::kNormal).ToLocalChecked()); if (!maybeIdleTimeout.IsEmpty() && !maybeIdleTimeout.ToLocalChecked()->IsUndefined()) { behavior.idleTimeout = maybeIdleTimeout.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(); } /* maxLifetime or default */ MaybeLocal maybeMaxLifetime = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "maxLifetime", NewStringType::kNormal).ToLocalChecked()); if (!maybeMaxLifetime.IsEmpty() && !maybeMaxLifetime.ToLocalChecked()->IsUndefined()) { /* Cap at 239 to avoid modulo wraparound in uSockets (240 % 240 == 0 == current timestamp, causing immediate timeout), and ensure non-negative */ behavior.maxLifetime = std::max(0, std::min(maybeMaxLifetime.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(), 239)); } /* closeOnBackpressureLimit or default */ MaybeLocal maybeCloseOnBackpressureLimit = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "closeOnBackpressureLimit", NewStringType::kNormal).ToLocalChecked()); if (!maybeCloseOnBackpressureLimit.IsEmpty() && !maybeCloseOnBackpressureLimit.ToLocalChecked()->IsUndefined()) { behavior.closeOnBackpressureLimit = maybeCloseOnBackpressureLimit.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(); } /* sendPingsAutomatically or default */ MaybeLocal maybeSendPingsAutomatically = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "sendPingsAutomatically", NewStringType::kNormal).ToLocalChecked()); if (!maybeSendPingsAutomatically.IsEmpty() && !maybeSendPingsAutomatically.ToLocalChecked()->IsUndefined()) { behavior.sendPingsAutomatically = maybeSendPingsAutomatically.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(); } /* Compression or default, map from 0, 1, 2 to disabled, shared, dedicated. This is actually the enum */ MaybeLocal maybeCompression = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "compression", NewStringType::kNormal).ToLocalChecked()); if (!maybeCompression.IsEmpty() && !maybeCompression.ToLocalChecked()->IsUndefined()) { behavior.compression = (uWS::CompressOptions) maybeCompression.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(); } /* maxBackpressure or default */ MaybeLocal maybeMaxBackpressure = behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "maxBackpressure", NewStringType::kNormal).ToLocalChecked()); if (!maybeMaxBackpressure.IsEmpty() && !maybeMaxBackpressure.ToLocalChecked()->IsUndefined()) { behavior.maxBackpressure = maybeMaxBackpressure.ToLocalChecked()->Int32Value(isolate->GetCurrentContext()).ToChecked(); } /* Upgrade */ upgradePf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "upgrade", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Open */ openPf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "open", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Message */ messagePf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "message", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Drain */ drainPf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "drain", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Close */ closePf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "close", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Dropped */ droppedPf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "dropped", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Ping */ pingPf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "ping", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Pong */ pongPf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "pong", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); /* Subscription */ subscriptionPf.Reset(args.GetIsolate(), Local::Cast(behaviorObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "subscription", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked())); } /* Upgrade handler is always optional */ if (upgradePf != Undefined(isolate)) { behavior.upgrade = [upgradePf = std::move(upgradePf), perContextData](auto *res, auto *req, auto *context) { Isolate *isolate = perContextData->isolate; HandleScope hs(isolate); Local upgradeLf = Local::New(isolate, upgradePf); Local resObject = perContextData->resTemplate[getAppTypeIndex()].Get(isolate)->Clone(); //resObject->SetAlignedPointerInInternalField(0, res); setInternalPointer(resObject, res); Local reqObject = perContextData->reqTemplate[std::is_same::value].Get(isolate)->Clone(); //reqObject->SetAlignedPointerInInternalField(0, req); setInternalPointer(reqObject, req); Local argv[3] = {resObject, reqObject, External::New(isolate, (void *) context)}; CallJS(isolate, upgradeLf, 3, argv); /* Properly invalidate req */ //reqObject->SetAlignedPointerInInternalField(0, nullptr); setInternalPointer(reqObject, nullptr); /* µWS itself will terminate if not responded and not attached * onAborted handler, so we can assume it's done */ }; } /* Open handler is NOT optional for the wrapper */ behavior.open = [openPf = std::move(openPf), perContextData](auto *ws) { Isolate *isolate = perContextData->isolate; HandleScope hs(isolate); /* Create a new websocket object */ Local wsObject = perContextData->wsTemplate[getAppTypeIndex()].Get(isolate)->Clone(); //wsObject->SetAlignedPointerInInternalField(0, ws); setInternalPointer(wsObject, ws); /* Retrieve temporary userData object */ PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); /* Copy entires from userData, only if we have it set (not the case for default constructor) */ if (!perSocketData->socketPf.IsEmpty()) { /* socketPf points to a stack allocated NoexceptPersistent, or nullptr, at this point */ Local userData = Local::New(isolate, perSocketData->socketPf); /* Merge userData and wsObject; this code is exceedingly horrible */ Local keys; if (userData->GetOwnPropertyNames(isolate->GetCurrentContext()).ToLocal(&keys)) { for (int i = 0; i < keys->Length(); i++) { wsObject->Set(isolate->GetCurrentContext(), keys->Get(isolate->GetCurrentContext(), i).ToLocalChecked(), userData->Get(isolate->GetCurrentContext(), keys->Get(isolate->GetCurrentContext(), i).ToLocalChecked()).ToLocalChecked() ).ToChecked(); } } /* Also copy symbol properties */ Local symbols; if (userData->GetOwnPropertyNames(isolate->GetCurrentContext(), static_cast(SKIP_STRINGS)).ToLocal(&symbols)) { for (int i = 0; i < symbols->Length(); i++) { wsObject->Set(isolate->GetCurrentContext(), symbols->Get(isolate->GetCurrentContext(), i).ToLocalChecked(), userData->Get(isolate->GetCurrentContext(), symbols->Get(isolate->GetCurrentContext(), i).ToLocalChecked()).ToLocalChecked() ).ToChecked(); } } } /* Attach a new V8 object with pointer to us, to it */ perSocketData->socketPf.Reset(isolate, wsObject); Local openLf = Local::New(isolate, openPf); if (!openLf->IsUndefined()) { Local argv[] = {wsObject}; CallJS(isolate, openLf, 1, argv); } }; /* Message handler is always optional */ if (messagePf != Undefined(isolate)) { behavior.message = [messagePf = std::move(messagePf), isolate](auto *ws, std::string_view message, uWS::OpCode opCode) { HandleScope hs(isolate); Local messageArrayBuffer = ArrayBuffer_New(isolate, (void *) message.data(), message.length()); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local argv[3] = {Local::New(isolate, perSocketData->socketPf), messageArrayBuffer, Boolean::New(isolate, opCode == uWS::OpCode::BINARY)}; CallJS(isolate, Local::New(isolate, messagePf), 3, argv); /* Important: we clear the ArrayBuffer to make sure it is not invalidly used after return */ messageArrayBuffer->Detach(); }; } /* Dropped handler is always optional (similar to message) */ if (droppedPf != Undefined(isolate)) { behavior.dropped = [droppedPf = std::move(droppedPf), isolate](auto *ws, std::string_view message, uWS::OpCode opCode) { HandleScope hs(isolate); Local messageArrayBuffer = ArrayBuffer_New(isolate, (void *) message.data(), message.length()); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local argv[3] = {Local::New(isolate, perSocketData->socketPf), messageArrayBuffer, Boolean::New(isolate, opCode == uWS::OpCode::BINARY)}; CallJS(isolate, Local::New(isolate, droppedPf), 3, argv); /* Important: we clear the ArrayBuffer to make sure it is not invalidly used after return */ messageArrayBuffer->Detach(); }; } /* Drain handler is always optional */ if (drainPf != Undefined(isolate)) { behavior.drain = [drainPf = std::move(drainPf), isolate](auto *ws) { HandleScope hs(isolate); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local argv[1] = {Local::New(isolate, perSocketData->socketPf) }; CallJS(isolate, Local::New(isolate, drainPf), 1, argv); }; } /* Subscription handler is always optional */ if (subscriptionPf != Undefined(isolate)) { behavior.subscription = [subscriptionPf = std::move(subscriptionPf), isolate](auto *ws, std::string_view topic, int newCount, int oldCount) { HandleScope hs(isolate); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local argv[4] = {Local::New(isolate, perSocketData->socketPf), ArrayBuffer_New(isolate, (void *) topic.data(), topic.length()), Integer::New(isolate, newCount), Integer::New(isolate, oldCount)}; CallJS(isolate, Local::New(isolate, subscriptionPf), 4, argv); }; } /* Ping handler is always optional */ if (pingPf != Undefined(isolate)) { behavior.ping = [pingPf = std::move(pingPf), isolate](auto *ws, std::string_view message) { HandleScope hs(isolate); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local argv[2] = {Local::New(isolate, perSocketData->socketPf), ArrayBuffer_New(isolate, (void *) message.data(), message.length())}; CallJS(isolate, Local::New(isolate, pingPf), 2, argv); }; } /* Pong handler is always optional */ if (pongPf != Undefined(isolate)) { behavior.pong = [pongPf = std::move(pongPf), isolate](auto *ws, std::string_view message) { HandleScope hs(isolate); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local argv[2] = {Local::New(isolate, perSocketData->socketPf), ArrayBuffer_New(isolate, (void *) message.data(), message.length())}; CallJS(isolate, Local::New(isolate, pongPf), 2, argv); }; } /* Close handler is NOT optional for the wrapper */ behavior.close = [closePf = std::move(closePf), isolate](auto *ws, int code, std::string_view message) { HandleScope hs(isolate); Local messageArrayBuffer = ArrayBuffer_New(isolate, (void *) message.data(), message.length()); PerSocketData *perSocketData = (PerSocketData *) ws->getUserData(); Local wsObject = Local::New(isolate, perSocketData->socketPf); /* Invalidate this wsObject */ //wsObject->SetAlignedPointerInInternalField(0, nullptr); setInternalPointer(wsObject, nullptr); /* Only call close handler if we have one set */ Local closeLf = Local::New(isolate, closePf); if (!closeLf->IsUndefined()) { Local argv[3] = {wsObject, Integer::New(isolate, code), messageArrayBuffer}; CallJS(isolate, closeLf, 3, argv); } /* This should technically not be required */ perSocketData->socketPf.Reset(); /* Again, here we clear the buffer to avoid strange bugs */ messageArrayBuffer->Detach(); }; app->template ws(std::string(pattern.getString()), std::move(behavior)); /* Return this */ args.GetReturnValue().Set(args.This()); } /* This method wraps get, post and all http methods */ template void uWS_App_get(F f, const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); /* Pattern */ NativeString pattern(args.GetIsolate(), args[0]); if (pattern.isInvalid(args)) { return; } /* If the handler is null */ if (args[1]->IsNull()) { (app->*f)(std::string(pattern.getString()), nullptr); args.GetReturnValue().Set(args.This()); return; } /* If the handler is String */ if (args[1]->IsArrayBuffer()) { NativeString constantString(args.GetIsolate(), args[1]); if (constantString.isInvalid(args)) { return; } (app->*f)(std::string(pattern.getString()), [response = std::string(constantString.getString().data(), constantString.getString().length())](auto *res, auto *req) { if constexpr (!std::is_same::value) { /* Parse the DeclarativeResponse */ std::string_view remainingInstructions(response.data(), response.length()); while (remainingInstructions.length()) { switch(remainingInstructions[0]) { case 0: { /* opCode END */ uint16_t length; memcpy(&length, remainingInstructions.data() + 1, 2); remainingInstructions.remove_prefix(3); // Skip opCode and length bytes res->end(remainingInstructions.substr(0, length)); remainingInstructions.remove_prefix(length); } break; case 1: { /* opCode WRITE_HEADER */ uint8_t keyLength; memcpy(&keyLength, remainingInstructions.data() + 1, 1); remainingInstructions.remove_prefix(2); // Skip opCode and key length bytes std::string_view keyString(remainingInstructions.data(), keyLength); remainingInstructions.remove_prefix(keyLength); uint8_t valueLength; memcpy(&valueLength, remainingInstructions.data(), 1); remainingInstructions.remove_prefix(1); // Skip value length bytes std::string_view valueString(remainingInstructions.data(), valueLength); remainingInstructions.remove_prefix(valueLength); res->writeHeader(keyString, valueString); } break; case 2: { /* opCode WRITE_BODY */ remainingInstructions.remove_prefix(1); // Skip opCode //res->writeBody(); } break; case 3: { /* opCode WRITE_QUERY_VALUE */ uint8_t keyLength; memcpy(&keyLength, remainingInstructions.data() + 1, 1); remainingInstructions.remove_prefix(2); // Skip opCode and key length bytes std::string_view keyString(remainingInstructions.data(), keyLength); remainingInstructions.remove_prefix(keyLength); res->write(req->getQuery(keyString)); } break; case 4: { /* opCode WRITE_HEADER_VALUE */ uint8_t keyLength; memcpy(&keyLength, remainingInstructions.data() + 1, 1); remainingInstructions.remove_prefix(2); // Skip opCode and key length bytes std::string_view keyString(remainingInstructions.data(), keyLength); remainingInstructions.remove_prefix(keyLength); res->write(req->getHeader(keyString)); } break; case 5: { /* opCode WRITE */ uint16_t length; memcpy(&length, remainingInstructions.data() + 1, 2); remainingInstructions.remove_prefix(3); // Skip opCode and length bytes std::string_view valueString(remainingInstructions.data(), length); remainingInstructions.remove_prefix(length); res->write(valueString); } break; case 6: { /* opCode WRITE_PARAMETER_VALUE */ uint8_t keyLength; memcpy(&keyLength, remainingInstructions.data() + 1, 1); remainingInstructions.remove_prefix(2); // Skip opCode and key length bytes std::string_view keyString(remainingInstructions.data(), keyLength); remainingInstructions.remove_prefix(keyLength); res->write(req->getParameter(keyString)); } break; case 7: { /* opCode WRITE_STATUS */ uint8_t statusLength; memcpy(&statusLength, remainingInstructions.data() + 1, 1); remainingInstructions.remove_prefix(2); // Skip opCode and status length bytes std::string_view statusString(remainingInstructions.data(), statusLength); remainingInstructions.remove_prefix(statusLength); res->writeStatus(statusString); } break; } } } }); args.GetReturnValue().Set(args.This()); return; } /* Handler */ Callback checkedCallback(args.GetIsolate(), args[1]); if (checkedCallback.isInvalid(args)) { return; } NoexceptPersistent cb = checkedCallback.getFunction(); /* This function requires perContextData */ PerContextData *perContextData = (PerContextData *) Local::Cast(args.Data())->Value(); (app->*f)(std::string(pattern.getString()), [cb = std::move(cb), perContextData](auto *res, auto *req) { Isolate *isolate = perContextData->isolate; HandleScope hs(isolate); Local resObject = perContextData->resTemplate[getAppTypeIndex()].Get(isolate)->Clone(); //resObject->SetAlignedPointerInInternalField(0, res); setInternalPointer(resObject, res); Local reqObject = perContextData->reqTemplate[std::is_same::value].Get(isolate)->Clone(); //reqObject->SetAlignedPointerInInternalField(0, req); setInternalPointer(reqObject, req); Local argv[] = {resObject, reqObject}; CallJS(isolate, cb.Get(isolate), 2, argv); /* Properly invalidate req */ //reqObject->SetAlignedPointerInInternalField(0, nullptr); setInternalPointer(reqObject, nullptr); /* µWS itself will terminate if not responded and not attached * onAborted handler, so we can assume it's done */ }); args.GetReturnValue().Set(args.This()); } template void uWS_App_close(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); app->close(); args.GetReturnValue().Set(args.This()); } template void uWS_App_listen_unix(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); /* Require at least two arguments */ if (missingArguments(2, args)) { return; } /* integer options is first (not implemented) */ /* Callback is first */ auto cb = [&args, isolate](auto *token) { /* Return a false boolean if listen failed */ Local argv[] = {token ? Local::Cast(External::New(isolate, token)) : Local::Cast(Boolean::New(isolate, false))}; /* Immediate call cannot be CallJS */ Local::Cast(args[0])->Call(isolate->GetCurrentContext(), isolate->GetCurrentContext()->Global(), 1, argv).IsEmpty(); }; /* Path is last */ std::string path; NativeString h(isolate, args[args.Length() - 1]); if (h.isInvalid(args)) { return; } path = h.getString(); app->listen(std::move(cb), path); args.GetReturnValue().Set(args.This()); } template void uWS_App_listen(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); /* Require at least two arguments */ if (missingArguments(2, args)) { return; } /* Callback is last */ auto cb = [&args, isolate](auto *token) { /* Return a false boolean if listen failed */ Local argv[] = {token ? Local::Cast(External::New(isolate, token)) : Local::Cast(Boolean::New(isolate, false))}; /* Immediate call cannot be CallJS */ Local::Cast(args[args.Length() - 1])->Call(isolate->GetCurrentContext(), isolate->GetCurrentContext()->Global(), 1, argv).IsEmpty(); }; /* Host is first, if present (an empty host still takes that slot) */ std::string host; int firstNumber = 0; if (!args[0]->IsNumber()) { NativeString h(isolate, args[0]); if (h.isInvalid(args)) { return; } host = h.getString(); firstNumber = 1; } /* Port, options are in the middle, if present */ std::vector numbers; for (int i = firstNumber; i < args.Length() - 1; i++) { numbers.push_back(args[i]->Uint32Value(args.GetIsolate()->GetCurrentContext()).ToChecked()); } /* We only use the most complete overload */ app->listen(host, numbers.size() ? numbers[0] : 0, numbers.size() > 1 ? numbers[1] : 0, std::move(cb)); args.GetReturnValue().Set(args.This()); } template void uWS_App_filter(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); /* Handler */ Callback checkedCallback(args.GetIsolate(), args[0]); if (checkedCallback.isInvalid(args)) { return; } NoexceptPersistent cb = checkedCallback.getFunction(); /* This function requires perContextData */ PerContextData *perContextData = (PerContextData *) Local::Cast(args.Data())->Value(); app->filter([cb = std::move(cb), perContextData](auto *res, int count) { Isolate *isolate = perContextData->isolate; HandleScope hs(isolate); Local resObject = perContextData->resTemplate[getAppTypeIndex()].Get(isolate)->Clone(); //resObject->SetAlignedPointerInInternalField(0, res); setInternalPointer(resObject, res); Local argv[] = {resObject, Local::Cast(Integer::New(isolate, count))}; CallJS(isolate, cb.Get(isolate), 2, argv); }); args.GetReturnValue().Set(args.This()); } template void uWS_App_domain(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); /* serverName */ if (missingArguments(1, args)) { return; } NativeString serverName(isolate, args[0]); if (serverName.isInvalid(args)) { return; } app->domain(std::string(serverName.getString())); args.GetReturnValue().Set(args.This()); } template void uWS_App_publish(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); /* topic, message [isBinary, compress] */ if (missingArguments(2, args)) { return; } NativeString topic(isolate, args[0]); if (topic.isInvalid(args)) { return; } NativeString message(isolate, args[1]); if (message.isInvalid(args)) { return; } bool ok = app->publish(topic.getString(), message.getString(), args[2]->BooleanValue(isolate) ? uWS::OpCode::BINARY : uWS::OpCode::TEXT, args[3]->BooleanValue(isolate)); args.GetReturnValue().Set(ok); } template void uWS_App_numSubscribers(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); /* topic */ if (missingArguments(1, args)) { return; } NativeString topic(isolate, args[0]); if (topic.isInvalid(args)) { return; } args.GetReturnValue().Set((uint32_t) app->numSubscribers(topic.getString())); } /* This one modified per-thread static strings temporarily */ std::pair readOptionsObject(const FunctionCallbackInfo &args, int index) { Isolate *isolate = args.GetIsolate(); /* Read the options object if any */ uWS::SocketContextOptions options = {}; thread_local std::string keyFileName, certFileName, passphrase, dhParamsFileName, caFileName, sslCiphers; if (args.Length() > index && !args[index]->IsUndefined() && !args[index]->IsNull()) { if (!args[index]->IsObject()) { args.GetReturnValue().Set(isolate->ThrowException(v8::Exception::Error(String::NewFromUtf8(isolate, "Options must be an object.", NewStringType::kNormal).ToLocalChecked()))); return {}; } Local optionsObject = Local::Cast(args[index]); /* Key file name */ NativeString keyFileNameValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "key_file_name", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()); if (keyFileNameValue.isInvalid(args)) { return {}; } if (keyFileNameValue.getString().length()) { keyFileName = keyFileNameValue.getString(); options.key_file_name = keyFileName.c_str(); } /* Cert file name */ NativeString certFileNameValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "cert_file_name", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()); if (certFileNameValue.isInvalid(args)) { return {}; } if (certFileNameValue.getString().length()) { certFileName = certFileNameValue.getString(); options.cert_file_name = certFileName.c_str(); } /* Passphrase */ NativeString passphraseValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "passphrase", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()); if (passphraseValue.isInvalid(args)) { return {}; } if (passphraseValue.getString().length()) { passphrase = passphraseValue.getString(); options.passphrase = passphrase.c_str(); } /* DH params file name */ NativeString dhParamsFileNameValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "dh_params_file_name", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()); if (dhParamsFileNameValue.isInvalid(args)) { return {}; } if (dhParamsFileNameValue.getString().length()) { dhParamsFileName = dhParamsFileNameValue.getString(); options.dh_params_file_name = dhParamsFileName.c_str(); } /* CA file name */ NativeString caFileNameValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "ca_file_name", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()); if (caFileNameValue.isInvalid(args)) { return {}; } if (caFileNameValue.getString().length()) { caFileName = caFileNameValue.getString(); options.ca_file_name = caFileName.c_str(); } /* ssl_prefer_low_memory_usage */ options.ssl_prefer_low_memory_usage = optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "ssl_prefer_low_memory_usage", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()->BooleanValue(isolate); /* ssl_ciphers */ NativeString sslCiphersValue(isolate, optionsObject->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "ssl_ciphers", NewStringType::kNormal).ToLocalChecked()).ToLocalChecked()); if (sslCiphersValue.isInvalid(args)) { return {}; } if (sslCiphersValue.getString().length()) { sslCiphers = sslCiphersValue.getString(); options.ssl_ciphers = sslCiphers.c_str(); } } return {options, true}; } template void uWS_App_adoptSocket(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); int32_t fd = args[0]->Int32Value(isolate->GetCurrentContext()).ToChecked(); NativeString ip(isolate, args[1]); if (ip.isInvalid(args)) { return; } app->adoptSocket(fd, ip.getString()); args.GetReturnValue().Set(args.This()); } template void uWS_App_removeChildApp(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); double descriptor = args[0]->NumberValue(isolate->GetCurrentContext()).ToChecked(); APP *receivingApp; memcpy(&receivingApp, &descriptor, sizeof(receivingApp)); app->removeChildApp(receivingApp); args.GetReturnValue().Set(args.This()); } template void uWS_App_addChildApp(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); double descriptor = args[0]->NumberValue(isolate->GetCurrentContext()).ToChecked(); APP *receivingApp;// = (APP *) args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked()->GetAlignedPointerFromInternalField(0); memcpy(&receivingApp, &descriptor, sizeof(receivingApp)); /* Todo: check the class type of args[0] must match class type of args.This() */ //if (args[0]) //std::cout << "addChildApp: " << receivingApp << std::endl; app->addChildApp(receivingApp); args.GetReturnValue().Set(args.This()); } template void uWS_App_getDescriptor(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); static_assert(sizeof(double) >= sizeof(app)); //static thread_local std::unordered_set> persistentApps; NoexceptPersistent *persistentApp = new NoexceptPersistent; persistentApp->Reset(args.GetIsolate(), args.This()); //persistentApps.emplace(persistentApp); double descriptor = 0; memcpy(&descriptor, &app, sizeof(app)); //std::cout << "getDescriptor: " << app << std::endl; //std::cout << "Loop: " << app->getLoop() << std::endl; args.GetReturnValue().Set(descriptor); } template void uWS_App_addServerName(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); NativeString hostnamePatternValue(isolate, args[0]); if (hostnamePatternValue.isInvalid(args)) { return; } std::string hostnamePattern; if (hostnamePatternValue.getString().length()) { hostnamePattern = hostnamePatternValue.getString(); } auto [options, valid] = readOptionsObject(args, 1); if (!valid) { return; } app->addServerName(hostnamePattern.c_str(), options); args.GetReturnValue().Set(args.This()); } template void uWS_App_removeServerName(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); NativeString hostnamePatternValue(isolate, args[0]); if (hostnamePatternValue.isInvalid(args)) { return; } std::string hostnamePattern; if (hostnamePatternValue.getString().length()) { hostnamePattern = hostnamePatternValue.getString(); } app->removeServerName(hostnamePattern.c_str()); args.GetReturnValue().Set(args.This()); } template void uWS_App_missingServerName(const FunctionCallbackInfo &args) { APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); Isolate *isolate = args.GetIsolate(); NoexceptPersistent missingPf; missingPf.Reset(args.GetIsolate(), Local::Cast(args[0])); app->missingServerName([missingPf = std::move(missingPf), isolate](const char *hostname) { /* We hand a JavaScript string here */ HandleScope hs(isolate); Local missingLf = Local::New(isolate, missingPf); Local argv[1] = {String::NewFromUtf8(isolate, hostname, NewStringType::kNormal).ToLocalChecked()}; CallJS(isolate, missingLf, 1, argv); }); args.GetReturnValue().Set(args.This()); } template void uWS_App(const FunctionCallbackInfo &args) { Isolate *isolate = args.GetIsolate(); Local appTemplate = FunctionTemplate::New(isolate); appTemplate->SetClassName(String::NewFromUtf8(isolate, std::is_same::value ? "uWS.SSLApp" : "uWS.App", NewStringType::kNormal).ToLocalChecked()); auto [options, valid] = readOptionsObject(args, 0); if (!valid) { return; } APP *app; if constexpr (!std::is_same::value) { /* uSockets copies strings here */ app = new APP(options); /* Throw if we failed to construct the app */ if (app->constructorFailed()) { delete app; args.GetReturnValue().Set(isolate->ThrowException(v8::Exception::Error(String::NewFromUtf8(isolate, "App construction failed", NewStringType::kNormal).ToLocalChecked()))); return; } } else { appTemplate->SetClassName(String::NewFromUtf8(isolate, "uWS.H3App", NewStringType::kNormal).ToLocalChecked()); app = new APP(options); } appTemplate->InstanceTemplate()->SetInternalFieldCount(1); /* All the http methods */ appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "get", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { /* Is this non-SSL? */ if constexpr (std::is_same::value) { /* Did we get 3 arguments (cached registry)? */ if (args.Length() == 3) { /* Grab the cache arguments */ v8::Isolate* isolate = args.GetIsolate(); v8::Local context = isolate->GetCurrentContext(); // 1. Ensure args[2] is an Object if (!args[2]->IsObject()) { isolate->ThrowException(v8::Exception::TypeError( v8::String::NewFromUtf8(isolate, "Cache options must be an object").ToLocalChecked())); return; } v8::Local optionsObj = args[2].template As(); // 2. Create V8 strings for the property names v8::Local lowerKey = v8::String::NewFromUtf8(isolate, "lowerExpiry").ToLocalChecked(); v8::Local upperKey = v8::String::NewFromUtf8(isolate, "upperExpiry").ToLocalChecked(); // 3. Extract properties safely with defaults if missing v8::Local lowerVal; v8::Local upperVal; unsigned int lowerExpiry = 0; unsigned int upperExpiry = 0; if (optionsObj->Get(context, lowerKey).ToLocal(&lowerVal) && lowerVal->IsNumber()) { lowerExpiry = lowerVal->Uint32Value(context).ToChecked(); } if (optionsObj->Get(context, upperKey).ToLocal(&upperVal) && upperVal->IsNumber()) { upperExpiry = upperVal->Uint32Value(context).ToChecked(); } APP *app = (APP *) getInternalPointer(args.This());//->GetAlignedPointerFromInternalField(0); /* Pattern */ NativeString pattern(args.GetIsolate(), args[0]); if (pattern.isInvalid(args)) { return; } /* Handler */ Callback checkedCallback(args.GetIsolate(), args[1]); if (checkedCallback.isInvalid(args)) { return; } NoexceptPersistent cb = checkedCallback.getFunction(); /* This function requires perContextData */ PerContextData *perContextData = (PerContextData *) Local::Cast(args.Data())->Value(); app->get(std::string(pattern.getString()), [cb = std::move(cb), perContextData](auto *res, auto *req) { Isolate *isolate = perContextData->isolate; HandleScope hs(isolate); // this needs to be cachedresponse wrapper (for both cached tcp and cached SSL?) Local resObject = perContextData->resTemplate[/*getAppTypeIndex()*/3].Get(isolate)->Clone(); //resObject->SetAlignedPointerInInternalField(0, res); setInternalPointer(resObject, res); Local reqObject = perContextData->reqTemplate[std::is_same::value].Get(isolate)->Clone(); //reqObject->SetAlignedPointerInInternalField(0, req); setInternalPointer(reqObject, req); Local argv[] = {resObject, reqObject}; CallJS(isolate, cb.Get(isolate), 2, argv); /* Properly invalidate req */ //reqObject->SetAlignedPointerInInternalField(0, nullptr); setInternalPointer(reqObject, nullptr); /* µWS itself will terminate if not responded and not attached * onAborted handler, so we can assume it's done */ }, { .lowerExpiry = lowerExpiry, .upperExpiry = upperExpiry }); args.GetReturnValue().Set(args.This()); } else { /* This is non-SSL but not using cache */ //uWS_App_get(&uWS::TemplatedApp::get, args); uWS_App_get(static_cast *, uWS::HttpRequest *)> &&)>(&APP::get), args); } } else if constexpr (std::is_same::value) { /* This is SSL and not using cache */ //uWS_App_get(&uWS::TemplatedApp::get, args); uWS_App_get(static_cast *, uWS::HttpRequest *)> &&)>(&APP::get), args); } else { /* H3App has no cache variant */ uWS_App_get(&APP::get, args); } }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "post", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::post, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "options", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::options, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "del", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::del, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "patch", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::patch, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "put", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::put, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "head", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::head, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "connect", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::connect, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "trace", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::trace, args); }, args.Data())); /* Any http method */ appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "any", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, [](auto &args) { uWS_App_get(&APP::any, args); }, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "listen", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_listen, args.Data())); if constexpr (!std::is_same::value) { appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "close", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_close, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "listen_unix", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_listen_unix, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "filter", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_filter, args.Data())); /* load balancing */ appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "removeChildAppDescriptor", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_removeChildApp, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "addChildAppDescriptor", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_addChildApp, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "getDescriptor", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_getDescriptor, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "adoptSocket", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_adoptSocket, args.Data())); /* ws, listen */ appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "ws", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_ws, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "publish", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_publish, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "numSubscribers", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_numSubscribers, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "domain", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_domain, args.Data())); /* SNI */ appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "addServerName", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_addServerName, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "removeServerName", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_removeServerName, args.Data())); appTemplate->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "missingServerName", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, uWS_App_missingServerName, args.Data())); } Local localApp = appTemplate->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); //localApp->SetAlignedPointerInInternalField(0, app); setInternalPointer(localApp, app); PerContextData *perContextData = (PerContextData *) Local::Cast(args.Data())->Value(); if constexpr (!std::is_same::value) { /* Add this to our delete list */ if constexpr (std::is_same::value) { perContextData->sslApps.emplace_back(app); } else { perContextData->apps.emplace_back(app); } } args.GetReturnValue().Set(localApp); }