diff options
218 files changed, 14879 insertions, 4397 deletions
diff --git a/core/global_constants.cpp b/core/global_constants.cpp index 04810afe73..5b4dd05dbf 100644 --- a/core/global_constants.cpp +++ b/core/global_constants.cpp @@ -378,6 +378,8 @@ void register_global_constants() { BIND_GLOBAL_ENUM_CONSTANT(BUTTON_LEFT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MIDDLE); + BIND_GLOBAL_ENUM_CONSTANT(BUTTON_XBUTTON1); + BIND_GLOBAL_ENUM_CONSTANT(BUTTON_XBUTTON2); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_UP); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_DOWN); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_LEFT); @@ -385,6 +387,8 @@ void register_global_constants() { BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_LEFT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_MIDDLE); + BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_XBUTTON1); + BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_XBUTTON2); //joypads BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_0); diff --git a/core/io/multiplayer_api.cpp b/core/io/multiplayer_api.cpp index 846c89510e..ffd3ecaed0 100644 --- a/core/io/multiplayer_api.cpp +++ b/core/io/multiplayer_api.cpp @@ -704,7 +704,7 @@ void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1); } -Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to) { +Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) { ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_DATA); ERR_FAIL_COND_V(!network_peer.is_valid(), ERR_UNCONFIGURED); @@ -714,7 +714,10 @@ Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to) { PoolVector<uint8_t>::Read r = p_data.read(); packet_cache[0] = NETWORK_COMMAND_RAW; memcpy(&packet_cache[1], &r[0], p_data.size()); + network_peer->set_target_peer(p_to); + network_peer->set_transfer_mode(p_mode); + return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1); } @@ -770,7 +773,7 @@ Vector<int> MultiplayerAPI::get_network_connected_peers() const { void MultiplayerAPI::_bind_methods() { ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node); - ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST)); + ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE)); ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer); ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer); ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id); diff --git a/core/io/multiplayer_api.h b/core/io/multiplayer_api.h index ef56c4c7f2..e47b1830e8 100644 --- a/core/io/multiplayer_api.h +++ b/core/io/multiplayer_api.h @@ -104,7 +104,7 @@ public: void set_root_node(Node *p_node); void set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer); Ref<NetworkedMultiplayerPeer> get_network_peer() const; - Error send_bytes(PoolVector<uint8_t> p_data, int p_to = NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST); + Error send_bytes(PoolVector<uint8_t> p_data, int p_to = NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST, NetworkedMultiplayerPeer::TransferMode p_mode = NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE); // Called by Node.rpc void rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount); diff --git a/core/os/input_event.cpp b/core/os/input_event.cpp index 4ebb821a2f..ca6446d015 100644 --- a/core/os/input_event.cpp +++ b/core/os/input_event.cpp @@ -509,6 +509,12 @@ String InputEventMouseButton::as_text() const { case BUTTON_WHEEL_RIGHT: button_index_string = "BUTTON_WHEEL_RIGHT"; break; + case BUTTON_XBUTTON1: + button_index_string = "BUTTON_XBUTTON1"; + break; + case BUTTON_XBUTTON2: + button_index_string = "BUTTON_XBUTTON2"; + break; default: button_index_string = itos(get_button_index()); break; @@ -601,6 +607,12 @@ String InputEventMouseMotion::as_text() const { case BUTTON_MASK_RIGHT: button_mask_string = "BUTTON_MASK_RIGHT"; break; + case BUTTON_MASK_XBUTTON1: + button_mask_string = "BUTTON_MASK_XBUTTON1"; + break; + case BUTTON_MASK_XBUTTON2: + button_mask_string = "BUTTON_MASK_XBUTTON2"; + break; default: button_mask_string = itos(get_button_mask()); break; diff --git a/core/os/input_event.h b/core/os/input_event.h index 037649ed60..bd1a85ce29 100644 --- a/core/os/input_event.h +++ b/core/os/input_event.h @@ -53,10 +53,13 @@ enum ButtonList { BUTTON_WHEEL_DOWN = 5, BUTTON_WHEEL_LEFT = 6, BUTTON_WHEEL_RIGHT = 7, + BUTTON_XBUTTON1 = 8, + BUTTON_XBUTTON2 = 9, BUTTON_MASK_LEFT = (1 << (BUTTON_LEFT - 1)), BUTTON_MASK_RIGHT = (1 << (BUTTON_RIGHT - 1)), BUTTON_MASK_MIDDLE = (1 << (BUTTON_MIDDLE - 1)), - + BUTTON_MASK_XBUTTON1 = (1 << (BUTTON_XBUTTON1 - 1)), + BUTTON_MASK_XBUTTON2 = (1 << (BUTTON_XBUTTON2 - 1)) }; enum JoystickList { diff --git a/core/project_settings.cpp b/core/project_settings.cpp index 7f9f4b638a..b1fd66e566 100644 --- a/core/project_settings.cpp +++ b/core/project_settings.cpp @@ -515,7 +515,11 @@ Error ProjectSettings::_load_settings_text(const String p_path) { } } else { // config_version is checked and dropped - set(section + "/" + assign, value); + if (section == String()) { + set(assign, value); + } else { + set(section + "/" + assign, value); + } } } else if (next_tag.name != String()) { section = next_tag.name; diff --git a/core/script_language.cpp b/core/script_language.cpp index acbe3b34db..37ba3cfc62 100644 --- a/core/script_language.cpp +++ b/core/script_language.cpp @@ -29,6 +29,7 @@ /*************************************************************************/ #include "script_language.h" +#include "project_settings.h" ScriptLanguage *ScriptServer::_languages[MAX_LANGUAGES]; int ScriptServer::_language_count = 0; @@ -103,6 +104,20 @@ void ScriptServer::unregister_language(ScriptLanguage *p_language) { void ScriptServer::init_languages() { + { //load global classes + global_classes_clear(); + if (ProjectSettings::get_singleton()->has_setting("_global_script_classes")) { + Array script_classes = ProjectSettings::get_singleton()->get("_global_script_classes"); + + for (int i = 0; i < script_classes.size(); i++) { + Dictionary c = script_classes[i]; + if (!c.has("class") || !c.has("language") || !c.has("path") || !c.has("base")) + continue; + add_global_class(c["class"], c["base"], c["language"], c["path"]); + } + } + } + for (int i = 0; i < _language_count; i++) { _languages[i]->init(); } @@ -113,6 +128,7 @@ void ScriptServer::finish_languages() { for (int i = 0; i < _language_count; i++) { _languages[i]->finish(); } + global_classes_clear(); } void ScriptServer::set_reload_scripts_on_save(bool p_enable) { @@ -139,6 +155,67 @@ void ScriptServer::thread_exit() { } } +HashMap<StringName, ScriptServer::GlobalScriptClass> ScriptServer::global_classes; + +void ScriptServer::global_classes_clear() { + global_classes.clear(); +} + +void ScriptServer::add_global_class(const StringName &p_class, const StringName &p_base, const StringName &p_language, const String &p_path) { + GlobalScriptClass g; + g.language = p_language; + g.path = p_path; + g.base = p_base; + global_classes[p_class] = g; +} +void ScriptServer::remove_global_class(const StringName &p_class) { + global_classes.erase(p_class); +} +bool ScriptServer::is_global_class(const StringName &p_class) { + return global_classes.has(p_class); +} +StringName ScriptServer::get_global_class_language(const StringName &p_class) { + ERR_FAIL_COND_V(!global_classes.has(p_class), StringName()); + return global_classes[p_class].language; +} +String ScriptServer::get_global_class_path(const String &p_class) { + ERR_FAIL_COND_V(!global_classes.has(p_class), String()); + return global_classes[p_class].path; +} + +StringName ScriptServer::get_global_class_base(const String &p_class) { + ERR_FAIL_COND_V(!global_classes.has(p_class), String()); + return global_classes[p_class].base; +} +void ScriptServer::get_global_class_list(List<StringName> *r_global_classes) { + const StringName *K = NULL; + List<StringName> classes; + while ((K = global_classes.next(K))) { + classes.push_back(*K); + } + classes.sort_custom<StringName::AlphCompare>(); + for (List<StringName>::Element *E = classes.front(); E; E = E->next()) { + r_global_classes->push_back(E->get()); + } +} +void ScriptServer::save_global_classes() { + List<StringName> gc; + get_global_class_list(&gc); + Array gcarr; + for (List<StringName>::Element *E = gc.front(); E; E = E->next()) { + Dictionary d; + d["class"] = E->get(); + d["language"] = global_classes[E->get()].language; + d["path"] = global_classes[E->get()].path; + d["base"] = global_classes[E->get()].base; + gcarr.push_back(d); + } + + ProjectSettings::get_singleton()->set("_global_script_classes", gcarr); + ProjectSettings::get_singleton()->save(); +} + +//////////////////// void ScriptInstance::get_property_state(List<Pair<StringName, Variant> > &state) { List<PropertyInfo> pinfo; diff --git a/core/script_language.h b/core/script_language.h index e7748f93e2..2950b35109 100644 --- a/core/script_language.h +++ b/core/script_language.h @@ -54,6 +54,14 @@ class ScriptServer { static bool scripting_enabled; static bool reload_scripts_on_save; + struct GlobalScriptClass { + StringName language; + String path; + String base; + }; + + static HashMap<StringName, GlobalScriptClass> global_classes; + public: static ScriptEditRequestFunction edit_request_func; @@ -70,6 +78,16 @@ public: static void thread_enter(); static void thread_exit(); + static void global_classes_clear(); + static void add_global_class(const StringName &p_class, const StringName &p_base, const StringName &p_language, const String &p_path); + static void remove_global_class(const StringName &p_class); + static bool is_global_class(const StringName &p_class); + static StringName get_global_class_language(const StringName &p_class); + static String get_global_class_path(const String &p_class); + static StringName get_global_class_base(const String &p_class); + static void get_global_class_list(List<StringName> *r_global_classes); + static void save_global_classes(); + static void init_languages(); static void finish_languages(); }; @@ -285,7 +303,10 @@ public: virtual void frame(); - virtual ~ScriptLanguage(){}; + virtual bool handles_global_class_type(const String &p_type) const { return false; } + virtual String get_global_class_name(const String &p_path, String *r_base_type = NULL) const { return String(); } + + virtual ~ScriptLanguage() {} }; extern uint8_t script_encryption_key[32]; diff --git a/doc/classes/CylinderShape.xml b/doc/classes/CylinderShape.xml new file mode 100644 index 0000000000..a63cc8831e --- /dev/null +++ b/doc/classes/CylinderShape.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="CylinderShape" inherits="Shape" category="Core" version="3.1"> + <brief_description> + Cylinder shape for collisions. + </brief_description> + <description> + Cylinder shape for collisions. + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + </methods> + <members> + <member name="height" type="float" setter="set_height" getter="get_height"> + The cylinder's height. + </member> + <member name="radius" type="float" setter="set_radius" getter="get_radius"> + The cylinder's radius. + </member> + </members> + <constants> + </constants> +</class> diff --git a/doc/classes/PhysicsServer.xml b/doc/classes/PhysicsServer.xml index 6efbfdb519..d45a3adc9c 100644 --- a/doc/classes/PhysicsServer.xml +++ b/doc/classes/PhysicsServer.xml @@ -1413,16 +1413,19 @@ <constant name="SHAPE_CAPSULE" value="4" enum="ShapeType"> The [Shape] is a [CapsuleShape]. </constant> - <constant name="SHAPE_CONVEX_POLYGON" value="5" enum="ShapeType"> + <constant name="SHAPE_CYLINDER" value="5" enum="ShapeType"> + The [Shape] is a [CylinderShape]. + </constant> + <constant name="SHAPE_CONVEX_POLYGON" value="6" enum="ShapeType"> The [Shape] is a [ConvexPolygonShape]. </constant> - <constant name="SHAPE_CONCAVE_POLYGON" value="6" enum="ShapeType"> + <constant name="SHAPE_CONCAVE_POLYGON" value="7" enum="ShapeType"> The [Shape] is a [ConcavePolygonShape]. </constant> - <constant name="SHAPE_HEIGHTMAP" value="7" enum="ShapeType"> + <constant name="SHAPE_HEIGHTMAP" value="8" enum="ShapeType"> The [Shape] is a [HeightMapShape]. </constant> - <constant name="SHAPE_CUSTOM" value="8" enum="ShapeType"> + <constant name="SHAPE_CUSTOM" value="9" enum="ShapeType"> This constant is used internally by the engine. Any attempt to create this kind of shape results in an error. </constant> <constant name="AREA_PARAM_GRAVITY" value="0" enum="AreaParameter"> diff --git a/doc/classes/PopupMenu.xml b/doc/classes/PopupMenu.xml index 89d8c43c00..83d1246e2a 100644 --- a/doc/classes/PopupMenu.xml +++ b/doc/classes/PopupMenu.xml @@ -507,6 +507,9 @@ </member> <member name="hide_on_state_item_selection" type="bool" setter="set_hide_on_state_item_selection" getter="is_hide_on_state_item_selection"> </member> + <member name="submenu_popup_delay" type="real" setter="set_submenu_popup_delay" getter="get_submenu_popup_delay"> + Sets the delay time for the submenu item to popup on mouse hovering. If the popup menu is added as a child of another (acting as a submenu), it will inherit the delay time of the parent menu item. Default value: [code]0.3[/code] seconds. + </member> </members> <signals> <signal name="id_focused"> diff --git a/doc/classes/Slider.xml b/doc/classes/Slider.xml index 554842b50e..a0ab4fe878 100644 --- a/doc/classes/Slider.xml +++ b/doc/classes/Slider.xml @@ -15,6 +15,8 @@ <members> <member name="editable" type="bool" setter="set_editable" getter="is_editable"> </member> + <member name="scrollable" type="bool" setter="set_scrollable" getter="is_scrollable"> + </member> <member name="focus_mode" type="int" setter="set_focus_mode" getter="get_focus_mode" enum="Control.FocusMode"> </member> <member name="tick_count" type="int" setter="set_ticks" getter="get_ticks"> diff --git a/doc/classes/Texture.xml b/doc/classes/Texture.xml index 3d3ceca150..eb7cfac87b 100644 --- a/doc/classes/Texture.xml +++ b/doc/classes/Texture.xml @@ -5,6 +5,7 @@ </brief_description> <description> A texture works by registering an image in the video hardware, which then can be used in 3D models or 2D [Sprite] or GUI [Control]. + Textures are often created by loading them from a file. See [method @GDScript.load]. </description> <tutorials> </tutorials> diff --git a/drivers/coreaudio/audio_driver_coreaudio.cpp b/drivers/coreaudio/audio_driver_coreaudio.cpp index 6e451eabcd..ef7858b4ca 100644 --- a/drivers/coreaudio/audio_driver_coreaudio.cpp +++ b/drivers/coreaudio/audio_driver_coreaudio.cpp @@ -52,7 +52,9 @@ OSStatus AudioDriverCoreAudio::output_device_address_cb(AudioObjectID inObjectID } #endif -Error AudioDriverCoreAudio::init_device() { +Error AudioDriverCoreAudio::init() { + mutex = Mutex::create(); + AudioComponentDescription desc; zeromem(&desc, sizeof(desc)); desc.componentType = kAudioUnitType_Output; @@ -69,6 +71,16 @@ Error AudioDriverCoreAudio::init_device() { OSStatus result = AudioComponentInstanceNew(comp, &audio_unit); ERR_FAIL_COND_V(result != noErr, FAILED); +#ifdef OSX_ENABLED + AudioObjectPropertyAddress prop; + prop.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + prop.mScope = kAudioObjectPropertyScopeGlobal; + prop.mElement = kAudioObjectPropertyElementMaster; + + result = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &prop, &output_device_address_cb, this); + ERR_FAIL_COND_V(result != noErr, FAILED); +#endif + AudioStreamBasicDescription strdesc; zeromem(&strdesc, sizeof(strdesc)); @@ -135,42 +147,6 @@ Error AudioDriverCoreAudio::init_device() { return OK; } -Error AudioDriverCoreAudio::finish_device() { - OSStatus result; - - if (active) { - result = AudioOutputUnitStop(audio_unit); - ERR_FAIL_COND_V(result != noErr, FAILED); - - active = false; - } - - result = AudioUnitUninitialize(audio_unit); - ERR_FAIL_COND_V(result != noErr, FAILED); - - return OK; -} - -Error AudioDriverCoreAudio::init() { - OSStatus result; - - mutex = Mutex::create(); - active = false; - channels = 2; - -#ifdef OSX_ENABLED - AudioObjectPropertyAddress prop; - prop.mSelector = kAudioHardwarePropertyDefaultOutputDevice; - prop.mScope = kAudioObjectPropertyScopeGlobal; - prop.mElement = kAudioObjectPropertyElementMaster; - - result = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &prop, &output_device_address_cb, this); - ERR_FAIL_COND_V(result != noErr, FAILED); -#endif - - return init_device(); -}; - OSStatus AudioDriverCoreAudio::output_callback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, @@ -370,6 +346,7 @@ void AudioDriverCoreAudio::set_device(String device) { } if (!found) { + // If we haven't found the desired device get the system default one UInt32 size = sizeof(AudioDeviceID); AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; @@ -406,7 +383,28 @@ bool AudioDriverCoreAudio::try_lock() { void AudioDriverCoreAudio::finish() { OSStatus result; - finish_device(); + lock(); + + AURenderCallbackStruct callback; + zeromem(&callback, sizeof(AURenderCallbackStruct)); + result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, kOutputBus, &callback, sizeof(callback)); + if (result != noErr) { + ERR_PRINT("AudioUnitSetProperty failed"); + } + + if (active) { + result = AudioOutputUnitStop(audio_unit); + if (result != noErr) { + ERR_PRINT("AudioOutputUnitStop failed"); + } + + active = false; + } + + result = AudioUnitUninitialize(audio_unit); + if (result != noErr) { + ERR_PRINT("AudioUnitUninitialize failed"); + } #ifdef OSX_ENABLED AudioObjectPropertyAddress prop; @@ -420,13 +418,13 @@ void AudioDriverCoreAudio::finish() { } #endif - AURenderCallbackStruct callback; - zeromem(&callback, sizeof(AURenderCallbackStruct)); - result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, kOutputBus, &callback, sizeof(callback)); + result = AudioComponentInstanceDispose(audio_unit); if (result != noErr) { - ERR_PRINT("AudioUnitSetProperty failed"); + ERR_PRINT("AudioComponentInstanceDispose failed"); } + unlock(); + if (mutex) { memdelete(mutex); mutex = NULL; diff --git a/drivers/coreaudio/audio_driver_coreaudio.h b/drivers/coreaudio/audio_driver_coreaudio.h index c44e225521..99c910498e 100644 --- a/drivers/coreaudio/audio_driver_coreaudio.h +++ b/drivers/coreaudio/audio_driver_coreaudio.h @@ -68,9 +68,6 @@ class AudioDriverCoreAudio : public AudioDriver { UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); - Error init_device(); - Error finish_device(); - public: const char *get_name() const { return "CoreAudio"; diff --git a/drivers/gles2/rasterizer_canvas_gles2.cpp b/drivers/gles2/rasterizer_canvas_gles2.cpp index cc8e3277b9..d5232a6511 100644 --- a/drivers/gles2/rasterizer_canvas_gles2.cpp +++ b/drivers/gles2/rasterizer_canvas_gles2.cpp @@ -733,6 +733,9 @@ void RasterizerCanvasGLES2::_canvas_item_render_commands(Item *p_item, Item *cur int w = current_clip->final_clip_rect.size.x; int h = current_clip->final_clip_rect.size.y; + if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) + y = current_clip->final_clip_rect.position.y; + glScissor(x, y, w, h); reclip = false; @@ -821,7 +824,10 @@ void RasterizerCanvasGLES2::canvas_render_items(Item *p_item_list, int p_z, cons if (current_clip) { glEnable(GL_SCISSOR_TEST); - glScissor(current_clip->final_clip_rect.position.x, (rt_size.height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.height)), current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); + int y = storage->frame.current_rt->height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.y); + if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) + y = current_clip->final_clip_rect.position.y; + glScissor(current_clip->final_clip_rect.position.x, y, current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); } else { glDisable(GL_SCISSOR_TEST); } @@ -969,7 +975,10 @@ void RasterizerCanvasGLES2::canvas_render_items(Item *p_item_list, int p_z, cons if (reclip) { glEnable(GL_SCISSOR_TEST); - glScissor(current_clip->final_clip_rect.position.x, (rt_size.height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.height)), current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); + int y = storage->frame.current_rt->height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.y); + if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) + y = current_clip->final_clip_rect.position.y; + glScissor(current_clip->final_clip_rect.position.x, y, current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); } p_item_list = p_item_list->next; diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp index c2377e0c3e..f214943bcf 100644 --- a/drivers/gles3/rasterizer_canvas_gles3.cpp +++ b/drivers/gles3/rasterizer_canvas_gles3.cpp @@ -1000,13 +1000,11 @@ void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item, Item *cur glEnable(GL_SCISSOR_TEST); //glScissor(viewport.x+current_clip->final_clip_rect.pos.x,viewport.y+ (viewport.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)), //current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height); - - int x = current_clip->final_clip_rect.position.x; int y = storage->frame.current_rt->height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.y); - int w = current_clip->final_clip_rect.size.x; - int h = current_clip->final_clip_rect.size.y; + if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) + y = current_clip->final_clip_rect.position.y; - glScissor(x, y, w, h); + glScissor(current_clip->final_clip_rect.position.x, y, current_clip->final_clip_rect.size.x, current_clip->final_clip_rect.size.y); reclip = false; } @@ -1141,7 +1139,11 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list, int p_z, cons if (current_clip) { glEnable(GL_SCISSOR_TEST); - glScissor(current_clip->final_clip_rect.position.x, (rt_size.height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.height)), current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); + int y = storage->frame.current_rt->height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.y); + if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) + y = current_clip->final_clip_rect.position.y; + + glScissor(current_clip->final_clip_rect.position.x, y, current_clip->final_clip_rect.size.x, current_clip->final_clip_rect.size.y); } else { @@ -1518,7 +1520,10 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list, int p_z, cons if (reclip) { glEnable(GL_SCISSOR_TEST); - glScissor(current_clip->final_clip_rect.position.x, (rt_size.height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.height)), current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); + int y = storage->frame.current_rt->height - (current_clip->final_clip_rect.position.y + current_clip->final_clip_rect.size.y); + if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) + y = current_clip->final_clip_rect.position.y; + glScissor(current_clip->final_clip_rect.position.x, y, current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height); } p_item_list = p_item_list->next; diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp index 191c587d98..4a3ebf7a7c 100644 --- a/drivers/gles3/rasterizer_storage_gles3.cpp +++ b/drivers/gles3/rasterizer_storage_gles3.cpp @@ -3862,7 +3862,7 @@ void RasterizerStorageGLES3::multimesh_allocate(RID p_multimesh, int p_instances multimesh->data.resize(format_floats * p_instances); - for (int i = 0; i < p_instances; i += format_floats) { + for (int i = 0; i < p_instances * format_floats; i += format_floats) { int color_from = 0; int custom_data_from = 0; diff --git a/drivers/gles3/shaders/tonemap.glsl b/drivers/gles3/shaders/tonemap.glsl index a75871f08e..63475c9039 100644 --- a/drivers/gles3/shaders/tonemap.glsl +++ b/drivers/gles3/shaders/tonemap.glsl @@ -1,28 +1,27 @@ [vertex] - -layout(location=0) in highp vec4 vertex_attrib; -layout(location=4) in vec2 uv_in; +layout (location = 0) in highp vec4 vertex_attrib; +layout (location = 4) in vec2 uv_in; out vec2 uv_interp; -void main() { - +void main() +{ gl_Position = vertex_attrib; + uv_interp = uv_in; -#ifdef V_FLIP - uv_interp.y = 1.0-uv_interp.y; -#endif + #ifdef V_FLIP + uv_interp.y = 1.0f - uv_interp.y; + #endif } [fragment] #if !defined(GLES_OVER_GL) -precision mediump float; + precision mediump float; #endif - in vec2 uv_interp; uniform highp sampler2D source; //texunit:0 @@ -31,297 +30,286 @@ uniform float exposure; uniform float white; #ifdef USE_AUTO_EXPOSURE - -uniform highp sampler2D source_auto_exposure; //texunit:1 -uniform highp float auto_exposure_grey; - + uniform highp sampler2D source_auto_exposure; //texunit:1 + uniform highp float auto_exposure_grey; #endif #if defined(USE_GLOW_LEVEL1) || defined(USE_GLOW_LEVEL2) || defined(USE_GLOW_LEVEL3) || defined(USE_GLOW_LEVEL4) || defined(USE_GLOW_LEVEL5) || defined(USE_GLOW_LEVEL6) || defined(USE_GLOW_LEVEL7) + #define USING_GLOW // only use glow when at least one glow level is selected -uniform highp sampler2D source_glow; //texunit:2 -uniform highp float glow_intensity; - + uniform highp sampler2D source_glow; //texunit:2 + uniform highp float glow_intensity; #endif #ifdef USE_BCS - -uniform vec3 bcs; - + uniform vec3 bcs; #endif #ifdef USE_COLOR_CORRECTION - -uniform sampler2D color_correction; //texunit:3 - + uniform sampler2D color_correction; //texunit:3 #endif - -layout(location = 0) out vec4 frag_color; +layout (location = 0) out vec4 frag_color; #ifdef USE_GLOW_FILTER_BICUBIC + // w0, w1, w2, and w3 are the four cubic B-spline basis functions + float w0(float a) + { + return (1.0f / 6.0f) * (a * (a * (-a + 3.0f) - 3.0f) + 1.0f); + } -// w0, w1, w2, and w3 are the four cubic B-spline basis functions -float w0(float a) -{ - return (1.0/6.0)*(a*(a*(-a + 3.0) - 3.0) + 1.0); -} - -float w1(float a) -{ - return (1.0/6.0)*(a*a*(3.0*a - 6.0) + 4.0); -} - -float w2(float a) -{ - return (1.0/6.0)*(a*(a*(-3.0*a + 3.0) + 3.0) + 1.0); -} - -float w3(float a) -{ - return (1.0/6.0)*(a*a*a); -} - -// g0 and g1 are the two amplitude functions -float g0(float a) -{ - return w0(a) + w1(a); -} + float w1(float a) + { + return (1.0f / 6.0f) * (a * a * (3.0f * a - 6.0f) + 4.0f); + } -float g1(float a) -{ - return w2(a) + w3(a); -} + float w2(float a) + { + return (1.0f / 6.0f) * (a * (a * (-3.0f * a + 3.0f) + 3.0f) + 1.0f); + } -// h0 and h1 are the two offset functions -float h0(float a) -{ - return -1.0 + w1(a) / (w0(a) + w1(a)); -} + float w3(float a) + { + return (1.0f / 6.0f) * (a * a * a); + } -float h1(float a) -{ - return 1.0 + w3(a) / (w2(a) + w3(a)); -} + // g0 and g1 are the two amplitude functions + float g0(float a) + { + return w0(a) + w1(a); + } -uniform ivec2 glow_texture_size; + float g1(float a) + { + return w2(a) + w3(a); + } -vec4 texture2D_bicubic(sampler2D tex, vec2 uv,int p_lod) -{ - float lod=float(p_lod); - vec2 tex_size = vec2(glow_texture_size >> p_lod); - vec2 pixel_size =1.0/tex_size; - uv = uv*tex_size + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - - float g0x = g0(fuv.x); - float g1x = g1(fuv.x); - float h0x = h0(fuv.x); - float h1x = h1(fuv.x); - float h0y = h0(fuv.y); - float h1y = h1(fuv.y); - - vec2 p0 = (vec2(iuv.x + h0x, iuv.y + h0y) - 0.5) * pixel_size; - vec2 p1 = (vec2(iuv.x + h1x, iuv.y + h0y) - 0.5) * pixel_size; - vec2 p2 = (vec2(iuv.x + h0x, iuv.y + h1y) - 0.5) * pixel_size; - vec2 p3 = (vec2(iuv.x + h1x, iuv.y + h1y) - 0.5) * pixel_size; - - return g0(fuv.y) * (g0x * textureLod(tex, p0,lod) + - g1x * textureLod(tex, p1,lod)) + - g1(fuv.y) * (g0x * textureLod(tex, p2,lod) + - g1x * textureLod(tex, p3,lod)); -} + // h0 and h1 are the two offset functions + float h0(float a) + { + return -1.0f + w1(a) / (w0(a) + w1(a)); + } + float h1(float a) + { + return 1.0f + w3(a) / (w2(a) + w3(a)); + } + uniform ivec2 glow_texture_size; -#define GLOW_TEXTURE_SAMPLE(m_tex,m_uv,m_lod) texture2D_bicubic(m_tex,m_uv,m_lod) + vec4 texture2D_bicubic(sampler2D tex, vec2 uv, int p_lod) + { + float lod = float(p_lod); + vec2 tex_size = vec2(glow_texture_size >> p_lod); + vec2 pixel_size = vec2(1.0f) / tex_size; + + uv = uv * tex_size + vec2(0.5f); + + vec2 iuv = floor(uv); + vec2 fuv = fract(uv); + + float g0x = g0(fuv.x); + float g1x = g1(fuv.x); + float h0x = h0(fuv.x); + float h1x = h1(fuv.x); + float h0y = h0(fuv.y); + float h1y = h1(fuv.y); + + vec2 p0 = (vec2(iuv.x + h0x, iuv.y + h0y) - vec2(0.5f)) * pixel_size; + vec2 p1 = (vec2(iuv.x + h1x, iuv.y + h0y) - vec2(0.5f)) * pixel_size; + vec2 p2 = (vec2(iuv.x + h0x, iuv.y + h1y) - vec2(0.5f)) * pixel_size; + vec2 p3 = (vec2(iuv.x + h1x, iuv.y + h1y) - vec2(0.5f)) * pixel_size; + + return g0(fuv.y) * (g0x * textureLod(tex, p0,lod) + + g1x * textureLod(tex, p1,lod)) + + g1(fuv.y) * (g0x * textureLod(tex, p2,lod) + + g1x * textureLod(tex, p3,lod)); + } + #define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) texture2D_bicubic(m_tex, m_uv, m_lod) #else - -#define GLOW_TEXTURE_SAMPLE(m_tex,m_uv,m_lod) textureLod(m_tex,m_uv,float(m_lod)) - + #define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) textureLod(m_tex, m_uv, float(m_lod)) #endif +vec3 tonemap_filmic(vec3 color, float white) +{ + const float A = 0.15f; + const float B = 0.50f; + const float C = 0.10f; + const float D = 0.20f; + const float E = 0.02f; + const float F = 0.30f; + const float W = 11.2f; + + vec3 color_tonemapped = ((color * (A * color + C * B) + D * E) / (color * (A * color + B) + D * F)) - E / F; + float white_tonemapped = ((white * (A * white + C * B) + D * E) / (white * (A * white + B) + D * F)) - E / F; + + return clamp(color_tonemapped / white_tonemapped, vec3(0.0f), vec3(1.0f)); +} -vec3 tonemap_filmic(vec3 color,float white) { - - float A = 0.15; - float B = 0.50; - float C = 0.10; - float D = 0.20; - float E = 0.02; - float F = 0.30; - float W = 11.2; - - vec3 coltn = ((color*(A*color+C*B)+D*E)/(color*(A*color+B)+D*F))-E/F; - float whitetn = ((white*(A*white+C*B)+D*E)/(white*(A*white+B)+D*F))-E/F; +vec3 tonemap_aces(vec3 color, float white) +{ + const float A = 2.51f; + const float B = 0.03f; + const float C = 2.43f; + const float D = 0.59f; + const float E = 0.14f; - return coltn/whitetn; + vec3 color_tonemapped = (color * (A * color + B)) / (color * (C * color + D) + E); + float white_tonemapped = (white * (A * white + B)) / (white * (C * white + D) + E); + return clamp(color_tonemapped / white_tonemapped, vec3(0.0f), vec3(1.0f)); } -vec3 tonemap_aces(vec3 color) { - float a = 2.51f; - float b = 0.03f; - float c = 2.43f; - float d = 0.59f; - float e = 0.14f; - return color = clamp((color*(a*color+b))/(color*(c*color+d)+e),vec3(0.0),vec3(1.0)); +vec3 tonemap_reindhart(vec3 color, float white) +{ + return clamp((color) / (1.0f + color) * (1.0f + (color / (white))), vec3(0.0f), vec3(1.0f)); // whitepoint is probably not in linear space here! } -vec3 tonemap_reindhart(vec3 color,float white) { - - return ( color * ( 1.0 + ( color / ( white) ) ) ) / ( 1.0 + color ); +vec3 linear_to_srgb(vec3 color) // convert linear rgb to srgb, assumes clamped input in range [0;1] +{ + const vec3 a = vec3(0.055f); + return mix((vec3(1.0f) + a) * pow(color.rgb, vec3(1.0f / 2.4f)) - a, 12.92f * color.rgb, lessThan(color.rgb, vec3(0.0031308f))); } -void main() { - - vec4 color = textureLod(source, uv_interp, 0.0); - -#ifdef USE_AUTO_EXPOSURE - - color/=texelFetch(source_auto_exposure,ivec2(0,0),0).r/auto_exposure_grey; -#endif - - color*=exposure; - -#if defined(USE_GLOW_LEVEL1) || defined(USE_GLOW_LEVEL2) || defined(USE_GLOW_LEVEL3) || defined(USE_GLOW_LEVEL4) || defined(USE_GLOW_LEVEL5) || defined(USE_GLOW_LEVEL6) || defined(USE_GLOW_LEVEL7) -#define USING_GLOW -#endif - -#if defined(USING_GLOW) - vec3 glow = vec3(0.0); - -#ifdef USE_GLOW_LEVEL1 - - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,1).rgb; -#endif - -#ifdef USE_GLOW_LEVEL2 - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,2).rgb; -#endif - -#ifdef USE_GLOW_LEVEL3 - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,3).rgb; -#endif - -#ifdef USE_GLOW_LEVEL4 - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,4).rgb; -#endif - -#ifdef USE_GLOW_LEVEL5 - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,5).rgb; -#endif - -#ifdef USE_GLOW_LEVEL6 - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,6).rgb; -#endif - -#ifdef USE_GLOW_LEVEL7 - glow+=GLOW_TEXTURE_SAMPLE(source_glow,uv_interp,7).rgb; -#endif - - - glow *= glow_intensity; +vec3 apply_tonemapping(vec3 color, float white) // inputs are LINEAR, always outputs clamped [0;1] color +{ + #ifdef USE_REINDHART_TONEMAPPER + return tonemap_reindhart(color, white); + #endif -#endif + #ifdef USE_FILMIC_TONEMAPPER + return tonemap_filmic(color, white); + #endif + #ifdef USE_ACES_TONEMAPPER + return tonemap_aces(color, white); + #endif -#ifdef USE_REINDHART_TONEMAPPER + return clamp(color, vec3(0.0f), vec3(1.0f)); // no other seleced -> linear +} - color.rgb = tonemap_reindhart(color.rgb,white); +vec3 gather_glow(sampler2D tex, vec2 uv) // sample all selected glow levels +{ + vec3 glow = vec3(0.0f); -# if defined(USING_GLOW) - glow = tonemap_reindhart(glow,white); -# endif + #ifdef USE_GLOW_LEVEL1 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 1).rgb; + #endif -#endif + #ifdef USE_GLOW_LEVEL2 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 2).rgb; + #endif -#ifdef USE_FILMIC_TONEMAPPER + #ifdef USE_GLOW_LEVEL3 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 3).rgb; + #endif - color.rgb = tonemap_filmic(color.rgb,white); + #ifdef USE_GLOW_LEVEL4 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 4).rgb; + #endif -# if defined(USING_GLOW) - glow = tonemap_filmic(glow,white); -# endif + #ifdef USE_GLOW_LEVEL5 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 5).rgb; + #endif -#endif + #ifdef USE_GLOW_LEVEL6 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 6).rgb; + #endif -#ifdef USE_ACES_TONEMAPPER + #ifdef USE_GLOW_LEVEL7 + glow += GLOW_TEXTURE_SAMPLE(tex, uv, 7).rgb; + #endif - color.rgb = tonemap_aces(color.rgb); + return glow; +} -# if defined(USING_GLOW) - glow = tonemap_aces(glow); -# endif +vec3 apply_glow(vec3 color, vec3 glow) // apply glow using the selected blending mode +{ + #ifdef USE_GLOW_REPLACE + color = glow; + #endif -#endif + #ifdef USE_GLOW_SCREEN + color = max((color + glow) - (color * glow), vec3(0.0)); + #endif -#ifdef KEEP_3D_LINEAR - // leave color as is... -#else - //regular Linear -> SRGB conversion - vec3 a = vec3(0.055); - color.rgb = mix( (vec3(1.0)+a)*pow(color.rgb,vec3(1.0/2.4))-a , 12.92*color.rgb , lessThan(color.rgb,vec3(0.0031308))); -#endif + #ifdef USE_GLOW_SOFTLIGHT + glow = glow * vec3(0.5f) + vec3(0.5f); -#if defined(USING_GLOW) - glow = mix( (vec3(1.0)+a)*pow(glow,vec3(1.0/2.4))-a , 12.92*glow , lessThan(glow,vec3(0.0031308))); -#endif + color.r = (glow.r <= 0.5f) ? (color.r - (1.0f - 2.0f * glow.r) * color.r * (1.0f - color.r)) : (((glow.r > 0.5f) && (color.r <= 0.25f)) ? (color.r + (2.0f * glow.r - 1.0f) * (4.0f * color.r * (4.0f * color.r + 1.0f) * (color.r - 1.0f) + 7.0f * color.r)) : (color.r + (2.0f * glow.r - 1.0f) * (sqrt(color.r) - color.r))); + color.g = (glow.g <= 0.5f) ? (color.g - (1.0f - 2.0f * glow.g) * color.g * (1.0f - color.g)) : (((glow.g > 0.5f) && (color.g <= 0.25f)) ? (color.g + (2.0f * glow.g - 1.0f) * (4.0f * color.g * (4.0f * color.g + 1.0f) * (color.g - 1.0f) + 7.0f * color.g)) : (color.g + (2.0f * glow.g - 1.0f) * (sqrt(color.g) - color.g))); + color.b = (glow.b <= 0.5f) ? (color.b - (1.0f - 2.0f * glow.b) * color.b * (1.0f - color.b)) : (((glow.b > 0.5f) && (color.b <= 0.25f)) ? (color.b + (2.0f * glow.b - 1.0f) * (4.0f * color.b * (4.0f * color.b + 1.0f) * (color.b - 1.0f) + 7.0f * color.b)) : (color.b + (2.0f * glow.b - 1.0f) * (sqrt(color.b) - color.b))); + #endif -//glow needs to be added in SRGB space (together with image space effects) + #if !defined(USE_GLOW_SCREEN) && !defined(USE_GLOW_SOFTLIGHT) && !defined(USE_GLOW_REPLACE) // no other selected -> additive + color += glow; + #endif - color.rgb = clamp(color.rgb,0.0,1.0); + return color; +} -#if defined(USING_GLOW) - glow = clamp(glow,0.0,1.0); -#endif +vec3 apply_bcs(vec3 color, vec3 bcs) +{ + color = mix(vec3(0.0f), color, bcs.x); + color = mix(vec3(0.5f), color, bcs.y); + color = mix(vec3(dot(vec3(1.0f), color) * 0.33333f), color, bcs.z); -#ifdef USE_GLOW_REPLACE + return color; +} - color.rgb = glow; +vec3 apply_color_correction(vec3 color, sampler2D correction_tex) +{ + color.r = texture(correction_tex, vec2(color.r, 0.0f)).r; + color.g = texture(correction_tex, vec2(color.g, 0.0f)).g; + color.b = texture(correction_tex, vec2(color.b, 0.0f)).b; -#endif + return color; +} -#ifdef USE_GLOW_SCREEN +void main() +{ + vec3 color = textureLod(source, uv_interp, 0.0f).rgb; - color.rgb = max((color.rgb + glow) - (color.rgb * glow), vec3(0.0)); + // Exposure -#endif + #ifdef USE_AUTO_EXPOSURE + color /= texelFetch(source_auto_exposure, ivec2(0, 0), 0).r / auto_exposure_grey; + #endif -#ifdef USE_GLOW_SOFTLIGHT + color *= exposure; - { + // Early Tonemap & SRGB Conversion - glow = (glow * 0.5) + 0.5; - color.r = (glow.r <= 0.5) ? (color.r - (1.0 - 2.0 * glow.r) * color.r * (1.0 - color.r)) : (((glow.r > 0.5) && (color.r <= 0.25)) ? (color.r + (2.0 * glow.r - 1.0) * (4.0 * color.r * (4.0 * color.r + 1.0) * (color.r - 1.0) + 7.0 * color.r)) : (color.r + (2.0 * glow.r - 1.0) * (sqrt(color.r) - color.r))); - color.g = (glow.g <= 0.5) ? (color.g - (1.0 - 2.0 * glow.g) * color.g * (1.0 - color.g)) : (((glow.g > 0.5) && (color.g <= 0.25)) ? (color.g + (2.0 * glow.g - 1.0) * (4.0 * color.g * (4.0 * color.g + 1.0) * (color.g - 1.0) + 7.0 * color.g)) : (color.g + (2.0 * glow.g - 1.0) * (sqrt(color.g) - color.g))); - color.b = (glow.b <= 0.5) ? (color.b - (1.0 - 2.0 * glow.b) * color.b * (1.0 - color.b)) : (((glow.b > 0.5) && (color.b <= 0.25)) ? (color.b + (2.0 * glow.b - 1.0) * (4.0 * color.b * (4.0 * color.b + 1.0) * (color.b - 1.0) + 7.0 * color.b)) : (color.b + (2.0 * glow.b - 1.0) * (sqrt(color.b) - color.b))); - } + color = apply_tonemapping(color, white); -#endif + #ifdef KEEP_3D_LINEAR + // leave color as is (-> don't convert to SRGB) + #else + color = linear_to_srgb(color); // regular linear -> SRGB conversion + #endif -#if defined(USING_GLOW) && !defined(USE_GLOW_SCREEN) && !defined(USE_GLOW_SOFTLIGHT) && !defined(USE_GLOW_REPLACE) - //additive - color.rgb+=glow; -#endif + // Glow -#ifdef USE_BCS + #ifdef USING_GLOW + vec3 glow = gather_glow(source_glow, uv_interp) * glow_intensity; - color.rgb = mix(vec3(0.0),color.rgb,bcs.x); - color.rgb = mix(vec3(0.5),color.rgb,bcs.y); - color.rgb = mix(vec3(dot(vec3(1.0),color.rgb)*0.33333),color.rgb,bcs.z); + // high dynamic range -> SRGB + glow = apply_tonemapping(glow, white); + glow = linear_to_srgb(glow); -#endif + color = apply_glow(color, glow); + #endif -#ifdef USE_COLOR_CORRECTION + // Additional effects - color.r = texture(color_correction,vec2(color.r,0.0)).r; - color.g = texture(color_correction,vec2(color.g,0.0)).g; - color.b = texture(color_correction,vec2(color.b,0.0)).b; -#endif + #ifdef USE_BCS + color = apply_bcs(color, bcs); + #endif + #ifdef USE_COLOR_CORRECTION + color = apply_color_correction(color, color_correction); + #endif - frag_color=vec4(color.rgb,1.0); + frag_color = vec4(color, 1.0f); } diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp index a8cbf52cd2..6b2a072e20 100644 --- a/editor/create_dialog.cpp +++ b/editor/create_dialog.cpp @@ -243,6 +243,18 @@ void CreateDialog::_update_search() { _parse_fs(EditorFileSystem::get_singleton()->get_filesystem()); */ + List<StringName> global_classes; + ScriptServer::get_global_class_list(&global_classes); + + Map<String, List<String> > global_class_map; + for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) { + String base = ScriptServer::get_global_class_base(E->get()); + if (!global_class_map.has(base)) { + global_class_map[base] = List<String>(); + } + global_class_map[base].push_back(E->get()); + } + HashMap<String, TreeItem *> types; TreeItem *root = search_options->create_item(); @@ -293,6 +305,32 @@ void CreateDialog::_update_search() { add_type(I->get(), types, root, &to_select); } + if (global_class_map.has(type) && ClassDB::is_parent_class(type, base_type)) { + for (List<String>::Element *J = global_class_map[type].front(); J; J = J->next()) { + bool show = search_box->get_text().is_subsequence_ofi(J->get()); + + if (!show) + continue; + + if (!types.has(type)) + add_type(type, types, root, &to_select); + + TreeItem *ti; + if (types.has(type)) + ti = types[type]; + else + ti = search_options->get_root(); + + TreeItem *item = search_options->create_item(ti); + item->set_metadata(0, J->get()); + item->set_text(0, J->get() + " (" + ScriptServer::get_global_class_path(J->get()).get_file() + ")"); + item->set_icon(0, _get_editor_icon(type)); + if (!to_select || J->get() == search_box->get_text()) { + to_select = item; + } + } + } + if (EditorNode::get_editor_data().get_custom_types().has(type) && ClassDB::is_parent_class(type, base_type)) { //there are custom types based on this... cool. @@ -444,6 +482,17 @@ Object *CreateDialog::instance_selected() { custom = md; if (custom != String()) { + + if (ScriptServer::is_global_class(custom)) { + RES script = ResourceLoader::load(ScriptServer::get_global_class_path(custom)); + ERR_FAIL_COND_V(!script.is_valid(), NULL); + + Object *obj = ClassDB::instance(ScriptServer::get_global_class_base(custom)); + ERR_FAIL_COND_V(!obj, NULL); + + obj->set_script(script.get_ref_ptr()); + return obj; + } return EditorNode::get_editor_data().instance_custom_type(selected->get_text(0), custom); } else { return ClassDB::instance(selected->get_text(0)); diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp index d8ae1da72e..d8ab41fa05 100644 --- a/editor/editor_file_system.cpp +++ b/editor/editor_file_system.cpp @@ -125,6 +125,14 @@ bool EditorFileSystemDirectory::get_file_import_is_valid(int p_idx) const { return files[p_idx]->import_valid; } +String EditorFileSystemDirectory::get_file_script_class_name(int p_idx) const { + return files[p_idx]->script_class_name; +} + +String EditorFileSystemDirectory::get_file_script_class_extends(int p_idx) const { + return files[p_idx]->script_class_extends; +} + StringName EditorFileSystemDirectory::get_file_type(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), ""); @@ -149,6 +157,8 @@ void EditorFileSystemDirectory::_bind_methods() { ClassDB::bind_method(D_METHOD("get_file", "idx"), &EditorFileSystemDirectory::get_file); ClassDB::bind_method(D_METHOD("get_file_path", "idx"), &EditorFileSystemDirectory::get_file_path); ClassDB::bind_method(D_METHOD("get_file_type", "idx"), &EditorFileSystemDirectory::get_file_type); + ClassDB::bind_method(D_METHOD("get_file_script_class_name", "idx"), &EditorFileSystemDirectory::get_file_script_class_name); + ClassDB::bind_method(D_METHOD("get_file_script_class_extends", "idx"), &EditorFileSystemDirectory::get_file_script_class_extends); ClassDB::bind_method(D_METHOD("get_file_import_is_valid", "idx"), &EditorFileSystemDirectory::get_file_import_is_valid); ClassDB::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name); ClassDB::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path); @@ -189,7 +199,7 @@ void EditorFileSystem::_scan_filesystem() { String project = ProjectSettings::get_singleton()->get_resource_path(); - String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_cache3"); + String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_cache4"); FileAccess *f = FileAccess::open(fscache, FileAccess::READ); if (f) { @@ -209,7 +219,7 @@ void EditorFileSystem::_scan_filesystem() { } else { Vector<String> split = l.split("::"); - ERR_CONTINUE(split.size() != 6); + ERR_CONTINUE(split.size() != 7); String name = split[0]; String file; @@ -221,8 +231,10 @@ void EditorFileSystem::_scan_filesystem() { fc.modification_time = split[2].to_int64(); fc.import_modification_time = split[3].to_int64(); fc.import_valid = split[4].to_int64() != 0; + fc.script_class_name = split[5].get_slice("<>", 0); + fc.script_class_extends = split[5].get_slice("<>", 1); - String deps = split[5].strip_edges(); + String deps = split[6].strip_edges(); if (deps.length()) { Vector<String> dp = deps.split("<>"); for (int i = 0; i < dp.size(); i++) { @@ -239,7 +251,7 @@ void EditorFileSystem::_scan_filesystem() { memdelete(f); } - String update_cache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update3"); + String update_cache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4"); if (FileAccess::exists(update_cache)) { { @@ -287,7 +299,7 @@ void EditorFileSystem::_scan_filesystem() { } void EditorFileSystem::_save_filesystem_cache() { - String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_cache3"); + String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_cache4"); FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE); if (f == NULL) { @@ -563,6 +575,7 @@ void EditorFileSystem::scan() { scanning = false; emit_signal("filesystem_changed"); emit_signal("sources_changed", sources_changed.size() > 0); + _queue_update_script_classes(); } else { @@ -706,6 +719,9 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess fi->modified_time = fc->modification_time; fi->import_modified_time = fc->import_modification_time; fi->import_valid = fc->import_valid; + fi->script_class_name = fc->script_class_name; + fi->script_class_extends = fc->script_class_extends; + if (fc->type == String()) { fi->type = ResourceLoader::get_resource_type(path); //there is also the chance that file type changed due to reimport, must probably check this somehow here (or kind of note it for next time in another file?) @@ -715,6 +731,7 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess } else { fi->type = ResourceFormatImporter::get_singleton()->get_resource_type(path); + fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends); fi->modified_time = 0; fi->import_modified_time = 0; fi->import_valid = ResourceLoader::is_import_valid(path); @@ -734,9 +751,12 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess fi->deps = fc->deps; fi->import_modified_time = 0; fi->import_valid = true; + fi->script_class_name = fc->script_class_name; + fi->script_class_extends = fc->script_class_extends; } else { //new or modified time fi->type = ResourceLoader::get_resource_type(path); + fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends); fi->deps = _get_dependencies(path); fi->modified_time = mt; fi->import_modified_time = 0; @@ -835,6 +855,7 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const fi->modified_time = FileAccess::get_modified_time(path); fi->import_modified_time = 0; fi->type = ResourceLoader::get_resource_type(path); + fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends); fi->import_valid = ResourceLoader::is_import_valid(path); { @@ -1044,6 +1065,7 @@ void EditorFileSystem::_notification(int p_what) { if (_update_scan_actions()) emit_signal("filesystem_changed"); emit_signal("sources_changed", sources_changed.size() > 0); + _queue_update_script_classes(); } } else if (!scanning) { @@ -1059,6 +1081,7 @@ void EditorFileSystem::_notification(int p_what) { _update_scan_actions(); emit_signal("filesystem_changed"); emit_signal("sources_changed", sources_changed.size() > 0); + _queue_update_script_classes(); } } } break; @@ -1087,7 +1110,7 @@ void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, for (int i = 0; i < p_dir->files.size(); i++) { - String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + itos(p_dir->files[i]->modified_time) + "::" + itos(p_dir->files[i]->import_modified_time) + "::" + itos(p_dir->files[i]->import_valid); + String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + itos(p_dir->files[i]->modified_time) + "::" + itos(p_dir->files[i]->import_modified_time) + "::" + itos(p_dir->files[i]->import_valid) + "::" + p_dir->files[i]->script_class_name + "<>" + p_dir->files[i]->script_class_extends; s += "::"; for (int j = 0; j < p_dir->files[i]->deps.size(); j++) { @@ -1268,7 +1291,7 @@ EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p void EditorFileSystem::_save_late_updated_files() { //files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file - String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update3"); + String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4"); FileAccessRef f = FileAccess::open(fscache, FileAccess::WRITE); for (Set<String>::Element *E = late_update_files.front(); E; E = E->next()) { f->store_line(E->get()); @@ -1293,6 +1316,67 @@ Vector<String> EditorFileSystem::_get_dependencies(const String &p_path) { return ret; } +String EditorFileSystem::_get_global_script_class(const String &p_type, const String &p_path, String *r_extends) const { + + for (int i = 0; i < ScriptServer::get_language_count(); i++) { + if (ScriptServer::get_language(i)->handles_global_class_type(p_type)) { + String global_name; + String extends; + + global_name = ScriptServer::get_language(i)->get_global_class_name(p_path, &extends); + *r_extends = extends; + return global_name; + } + } + *r_extends = String(); + return String(); +} + +void EditorFileSystem::_scan_script_classes(EditorFileSystemDirectory *p_dir) { + int filecount = p_dir->files.size(); + const EditorFileSystemDirectory::FileInfo *const *files = p_dir->files.ptr(); + for (int i = 0; i < filecount; i++) { + if (files[i]->script_class_name == String()) { + continue; + } + + String lang; + for (int j = 0; j < ScriptServer::get_language_count(); j++) { + if (ScriptServer::get_language(j)->handles_global_class_type(files[i]->type)) { + lang = ScriptServer::get_language(j)->get_name(); + } + } + + ScriptServer::add_global_class(files[i]->script_class_name, files[i]->script_class_extends, lang, p_dir->get_file_path(i)); + } + for (int i = 0; i < p_dir->get_subdir_count(); i++) { + _scan_script_classes(p_dir->get_subdir(i)); + } +} + +void EditorFileSystem::update_script_classes() { + + if (!update_script_classes_queued) + return; + + update_script_classes_queued = false; + ScriptServer::global_classes_clear(); + if (get_filesystem()) { + _scan_script_classes(get_filesystem()); + } + + ScriptServer::save_global_classes(); +} + +void EditorFileSystem::_queue_update_script_classes() { + if (update_script_classes_queued) { + return; + } + + update_script_classes_queued = true; + call_deferred("update_script_classes"); +} + void EditorFileSystem::update_file(const String &p_file) { EditorFileSystemDirectory *fs = NULL; @@ -1311,7 +1395,9 @@ void EditorFileSystem::update_file(const String &p_file) { memdelete(fs->files[cpos]); fs->files.remove(cpos); } + call_deferred("emit_signal", "filesystem_changed"); //update later + _queue_update_script_classes(); return; } @@ -1351,6 +1437,7 @@ void EditorFileSystem::update_file(const String &p_file) { } fs->files[cpos]->type = type; + fs->files[cpos]->script_class_name = _get_global_script_class(type, p_file, &fs->files[cpos]->script_class_extends); fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); fs->files[cpos]->deps = _get_dependencies(p_file); fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file); @@ -1359,6 +1446,7 @@ void EditorFileSystem::update_file(const String &p_file) { EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); call_deferred("emit_signal", "filesystem_changed"); //update later + _queue_update_script_classes(); } void EditorFileSystem::_reimport_file(const String &p_file) { @@ -1611,6 +1699,7 @@ void EditorFileSystem::_bind_methods() { ClassDB::bind_method(D_METHOD("update_file", "path"), &EditorFileSystem::update_file); ClassDB::bind_method(D_METHOD("get_filesystem_path", "path"), &EditorFileSystem::get_filesystem_path); ClassDB::bind_method(D_METHOD("get_file_type", "path"), &EditorFileSystem::get_file_type); + ClassDB::bind_method(D_METHOD("update_script_classes"), &EditorFileSystem::update_script_classes); ADD_SIGNAL(MethodInfo("filesystem_changed")); ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(Variant::BOOL, "exist"))); @@ -1664,6 +1753,7 @@ EditorFileSystem::EditorFileSystem() { memdelete(da); scan_total = 0; + update_script_classes_queued = false; } EditorFileSystem::~EditorFileSystem() { diff --git a/editor/editor_file_system.h b/editor/editor_file_system.h index a587d2879a..1aa35f4782 100644 --- a/editor/editor_file_system.h +++ b/editor/editor_file_system.h @@ -58,6 +58,8 @@ class EditorFileSystemDirectory : public Object { bool import_valid; Vector<String> deps; bool verified; //used for checking changes + String script_class_name; + String script_class_extends; }; struct FileInfoSort { @@ -86,6 +88,8 @@ public: StringName get_file_type(int p_idx) const; Vector<String> get_file_deps(int p_idx) const; bool get_file_import_is_valid(int p_idx) const; + String get_file_script_class_name(int p_idx) const; //used for scripts + String get_file_script_class_extends(int p_idx) const; //used for scripts EditorFileSystemDirectory *get_parent(); @@ -157,6 +161,8 @@ class EditorFileSystem : public Node { uint64_t import_modification_time; Vector<String> deps; bool import_valid; + String script_class_name; + String script_class_extends; }; HashMap<String, FileCache> file_cache; @@ -215,6 +221,12 @@ class EditorFileSystem : public Node { } }; + void _scan_script_classes(EditorFileSystemDirectory *p_dir); + volatile bool update_script_classes_queued; + void _queue_update_script_classes(); + + String _get_global_script_class(const String &p_type, const String &p_path, String *r_extends) const; + protected: void _notification(int p_what); static void _bind_methods(); @@ -237,6 +249,8 @@ public: void reimport_files(const Vector<String> &p_files); + void update_script_classes(); + EditorFileSystem(); ~EditorFileSystem(); }; diff --git a/editor/editor_fonts.cpp b/editor/editor_fonts.cpp index 26f16e282e..8e0d92267c 100644 --- a/editor/editor_fonts.cpp +++ b/editor/editor_fonts.cpp @@ -31,6 +31,7 @@ #include "editor_fonts.h" #include "builtin_fonts.gen.h" +#include "core/os/dir_access.h" #include "editor_scale.h" #include "editor_settings.h" #include "scene/resources/default_theme/default_theme.h" @@ -114,28 +115,34 @@ static Ref<BitmapFont> make_font(int p_height, int p_ascent, int p_valign, int p MAKE_FALLBACKS(m_name); void editor_register_fonts(Ref<Theme> p_theme) { + DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + /* Custom font */ DynamicFontData::Hinting font_hinting = (DynamicFontData::Hinting)(int)EditorSettings::get_singleton()->get("interface/editor/main_font_hinting"); String custom_font_path = EditorSettings::get_singleton()->get("interface/editor/main_font"); Ref<DynamicFontData> CustomFont; - if (custom_font_path.length() > 0) { + if (custom_font_path.length() > 0 && dir->file_exists(custom_font_path)) { CustomFont.instance(); CustomFont->set_hinting(font_hinting); CustomFont->set_font_path(custom_font_path); CustomFont->set_force_autohinter(true); //just looks better..i think? + } else { + EditorSettings::get_singleton()->set_manually("interface/editor/main_font", ""); } /* Custom Bold font */ String custom_font_path_bold = EditorSettings::get_singleton()->get("interface/editor/main_font_bold"); Ref<DynamicFontData> CustomFontBold; - if (custom_font_path_bold.length() > 0) { + if (custom_font_path_bold.length() > 0 && dir->file_exists(custom_font_path_bold)) { CustomFontBold.instance(); CustomFontBold->set_hinting(font_hinting); CustomFontBold->set_font_path(custom_font_path_bold); CustomFontBold->set_force_autohinter(true); //just looks better..i think? + } else { + EditorSettings::get_singleton()->set_manually("interface/editor/main_font_bold", ""); } /* Custom source code font */ @@ -143,12 +150,16 @@ void editor_register_fonts(Ref<Theme> p_theme) { String custom_font_path_source = EditorSettings::get_singleton()->get("interface/editor/code_font"); DynamicFontData::Hinting font_source_hinting = (DynamicFontData::Hinting)(int)EditorSettings::get_singleton()->get("interface/editor/code_font_hinting"); Ref<DynamicFontData> CustomFontSource; - if (custom_font_path_source.length() > 0) { + if (custom_font_path_source.length() > 0 && dir->file_exists(custom_font_path_source)) { CustomFontSource.instance(); CustomFontSource->set_hinting(font_source_hinting); CustomFontSource->set_font_path(custom_font_path_source); + } else { + EditorSettings::get_singleton()->set_manually("interface/editor/code_font", ""); } + memdelete(dir); + /* Droid Sans */ Ref<DynamicFontData> DefaultFont; diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index d8ce2bc024..17f383c8ae 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -92,7 +92,7 @@ void EditorProperty::_notification(int p_what) { Rect2 bottom_rect; { - int child_room = size.width / 2; + int child_room = size.width * (1.0 - split_ratio); Ref<Font> font = get_font("font", "Tree"); int height = font->get_height(); @@ -691,6 +691,15 @@ bool EditorProperty::is_selectable() const { return selectable; } +void EditorProperty::set_name_split_ratio(float p_ratio) { + split_ratio = p_ratio; +} + +float EditorProperty::get_name_split_ratio() const { + + return split_ratio; +} + void EditorProperty::set_object_and_property(Object *p_object, const StringName &p_property) { object = p_object; property = p_property; @@ -744,6 +753,7 @@ void EditorProperty::_bind_methods() { EditorProperty::EditorProperty() { + split_ratio = 0.5; selectable = true; text_size = 0; read_only = false; @@ -1114,6 +1124,30 @@ EditorInspectorSection::EditorInspectorSection() { Ref<EditorInspectorPlugin> EditorInspector::inspector_plugins[MAX_PLUGINS]; int EditorInspector::inspector_plugin_count = 0; +EditorProperty *EditorInspector::instantiate_property_editor(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage) { + + for (int i = inspector_plugin_count - 1; i >= 0; i--) { + + inspector_plugins[i]->parse_property(p_object, p_type, p_path, p_hint, p_hint_text, p_usage); + if (inspector_plugins[i]->added_editors.size()) { + for (int j = 1; j < inspector_plugins[i]->added_editors.size(); j++) { //only keep first one + memdelete(inspector_plugins[i]->added_editors[j].property_editor); + } + + EditorProperty *prop = Object::cast_to<EditorProperty>(inspector_plugins[i]->added_editors[0].property_editor); + if (prop) { + + inspector_plugins[i]->added_editors.clear(); + return prop; + } else { + memdelete(inspector_plugins[i]->added_editors[0].property_editor); + inspector_plugins[i]->added_editors.clear(); + } + } + } + return NULL; +} + void EditorInspector::add_inspector_plugin(const Ref<EditorInspectorPlugin> &p_plugin) { ERR_FAIL_COND(inspector_plugin_count == MAX_PLUGINS); diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h index 383cb458ec..b7a492f114 100644 --- a/editor/editor_inspector.h +++ b/editor/editor_inspector.h @@ -76,6 +76,8 @@ private: bool selected; int selected_focusable; + float split_ratio; + Vector<Control *> focusables; Control *label_reference; Control *bottom_editor; @@ -134,6 +136,9 @@ public: void set_selectable(bool p_selectable); bool is_selectable() const; + void set_name_split_ratio(float p_ratio); + float get_name_split_ratio() const; + void set_object_and_property(Object *p_object, const StringName &p_property); EditorProperty(); }; @@ -285,6 +290,8 @@ public: static void remove_inspector_plugin(const Ref<EditorInspectorPlugin> &p_plugin); static void cleanup_plugins(); + static EditorProperty *instantiate_property_editor(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage); + void set_undo_redo(UndoRedo *p_undo_redo); String get_selected_path() const; diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 8d039f8cc0..70bc090bc4 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -116,6 +116,7 @@ #include "editor/plugins/theme_editor_plugin.h" #include "editor/plugins/tile_map_editor_plugin.h" #include "editor/plugins/tile_set_editor_plugin.h" +#include "editor/plugins/visual_shader_editor_plugin.h" #include "editor/pvrtc_compress.h" #include "editor/register_exporters.h" #include "editor/script_editor_debugger.h" @@ -3860,7 +3861,7 @@ ToolButton *EditorNode::add_bottom_panel_item(String p_text, Control *p_item) { tb->set_focus_mode(Control::FOCUS_NONE); bottom_panel_vb->add_child(p_item); bottom_panel_hb->raise(); - bottom_panel_hb->add_child(tb); + bottom_panel_hb_editors->add_child(tb); p_item->set_v_size_flags(Control::SIZE_EXPAND_FILL); p_item->hide(); BottomPanelItem bpi; @@ -3924,7 +3925,7 @@ void EditorNode::remove_bottom_panel_item(Control *p_item) { _bottom_panel_switch(false, 0); } bottom_panel_vb->remove_child(bottom_panel_items[i].control); - bottom_panel_hb->remove_child(bottom_panel_items[i].button); + bottom_panel_hb_editors->remove_child(bottom_panel_items[i].button); memdelete(bottom_panel_items[i].button); bottom_panel_items.remove(i); break; @@ -3954,6 +3955,11 @@ void EditorNode::_bottom_panel_switch(bool p_enable, int p_idx) { } center_split->set_dragger_visibility(SplitContainer::DRAGGER_VISIBLE); center_split->set_collapsed(false); + if (bottom_panel_raise->is_pressed()) { + top_split->hide(); + } + bottom_panel_raise->show(); + } else { bottom_panel->add_style_override("panel", gui_base->get_stylebox("panel", "TabContainer")); for (int i = 0; i < bottom_panel_items.size(); i++) { @@ -3963,6 +3969,10 @@ void EditorNode::_bottom_panel_switch(bool p_enable, int p_idx) { } center_split->set_dragger_visibility(SplitContainer::DRAGGER_HIDDEN); center_split->set_collapsed(true); + bottom_panel_raise->hide(); + if (bottom_panel_raise->is_pressed()) { + top_split->show(); + } } } @@ -4372,6 +4382,17 @@ Vector<Ref<EditorResourceConversionPlugin> > EditorNode::find_resource_conversio return ret; } +void EditorNode::_bottom_panel_raise_toggled(bool p_pressed) { + + if (p_pressed) { + top_split->hide(); + bottom_panel_raise->set_icon(gui_base->get_icon("ShrinkBottomDock", "EditorIcons")); + } else { + top_split->show(); + bottom_panel_raise->set_icon(gui_base->get_icon("ExpandBottomDock", "EditorIcons")); + } +} + void EditorNode::_bind_methods() { ClassDB::bind_method("_menu_option", &EditorNode::_menu_option); @@ -4440,6 +4461,7 @@ void EditorNode::_bind_methods() { ClassDB::bind_method(D_METHOD("_dim_timeout"), &EditorNode::_dim_timeout); ClassDB::bind_method(D_METHOD("_resources_reimported"), &EditorNode::_resources_reimported); + ClassDB::bind_method(D_METHOD("_bottom_panel_raise_toggled"), &EditorNode::_bottom_panel_raise_toggled); ADD_SIGNAL(MethodInfo("play_pressed")); ADD_SIGNAL(MethodInfo("pause_pressed")); @@ -4605,6 +4627,10 @@ EditorNode::EditorNode() { Ref<EditorInspectorRootMotionPlugin> rmp; rmp.instance(); EditorInspector::add_inspector_plugin(rmp); + + Ref<EditorInspectorShaderModePlugin> smp; + smp.instance(); + EditorInspector::add_inspector_plugin(smp); } _pvrtc_register_compressors(); @@ -4646,7 +4672,8 @@ EditorNode::EditorNode() { EDITOR_DEF("interface/scene_tabs/show_thumbnail_on_hover", true); EDITOR_DEF("interface/inspector/capitalize_properties", true); EDITOR_DEF("interface/inspector/disable_folding", false); - EDITOR_DEF("interface/inspector/open_resources_in_new_inspector", false); + EDITOR_DEF("interface/inspector/open_resources_in_current_inspector", true); + EDITOR_DEF("interface/inspector/resources_types_to_open_in_new_inspector", "Material,Mesh"); EDITOR_DEF("run/auto_save/save_before_running", true); theme_base = memnew(Control); @@ -5263,6 +5290,19 @@ EditorNode::EditorNode() { bottom_panel_hb = memnew(HBoxContainer); bottom_panel_vb->add_child(bottom_panel_hb); + bottom_panel_hb_editors = memnew(HBoxContainer); + bottom_panel_hb_editors->set_h_size_flags(Control::SIZE_EXPAND_FILL); + bottom_panel_hb->add_child(bottom_panel_hb_editors); + bottom_panel_raise = memnew(ToolButton); + bottom_panel_raise->set_icon(gui_base->get_icon("ExpandBottomDock", "EditorIcons")); + + bottom_panel_raise->set_shortcut(ED_SHORTCUT("editor/bottom_panel_expand", TTR("Expand Bottom Panel"), KEY_MASK_SHIFT | KEY_F12)); + + bottom_panel_hb->add_child(bottom_panel_raise); + bottom_panel_raise->hide(); + bottom_panel_raise->set_toggle_mode(true); + bottom_panel_raise->connect("toggled", this, "_bottom_panel_raise_toggled"); + log = memnew(EditorLog); ToolButton *output_button = add_bottom_panel_item(TTR("Output"), log); log->set_tool_button(output_button); @@ -5367,8 +5407,7 @@ EditorNode::EditorNode() { raise_bottom_panel_item(AnimationPlayerEditor::singleton); add_editor_plugin(memnew(ShaderEditorPlugin(this))); - // FIXME: Disabled for Godot 3.0 as made incompatible, it needs to be ported to the new API. - //add_editor_plugin(memnew(ShaderGraphEditorPlugin(this))); + add_editor_plugin(memnew(VisualShaderEditorPlugin(this))); add_editor_plugin(memnew(AnimationNodeBlendTreeEditorPlugin(this))); add_editor_plugin(memnew(AnimationNodeBlendSpace1DEditorPlugin(this))); add_editor_plugin(memnew(AnimationNodeBlendSpace2DEditorPlugin(this))); diff --git a/editor/editor_node.h b/editor/editor_node.h index a5f975784c..7aa060fe14 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -377,7 +377,11 @@ private: PanelContainer *bottom_panel; HBoxContainer *bottom_panel_hb; + HBoxContainer *bottom_panel_hb_editors; VBoxContainer *bottom_panel_vb; + ToolButton *bottom_panel_raise; + + void _bottom_panel_raise_toggled(bool); EditorInterface *editor_interface; diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp index 064569dea0..1f45902008 100644 --- a/editor/editor_properties.cpp +++ b/editor/editor_properties.cpp @@ -405,6 +405,10 @@ void EditorPropertyEnum::setup(const Vector<String> &p_options) { } } +void EditorPropertyEnum::set_option_button_clip(bool p_enable) { + options->set_clip_text(p_enable); +} + void EditorPropertyEnum::_bind_methods() { ClassDB::bind_method(D_METHOD("_option_selected"), &EditorPropertyEnum::_option_selected); @@ -2000,7 +2004,7 @@ void EditorPropertyResource::_sub_inspector_object_id_selected(int p_id) { void EditorPropertyResource::_open_editor_pressed() { RES res = get_edited_object()->get(get_edited_property()); if (res.is_valid()) { - EditorNode::get_singleton()->edit_item(res.ptr()); + EditorNode::get_singleton()->edit_resource(res.ptr()); } } @@ -2266,6 +2270,10 @@ void EditorPropertyResource::drop_data_fw(const Point2 &p_point, const Variant & } } +void EditorPropertyResource::set_use_sub_inspector(bool p_enable) { + use_sub_inspector = p_enable; +} + void EditorPropertyResource::_bind_methods() { ClassDB::bind_method(D_METHOD("_file_selected"), &EditorPropertyResource::_file_selected); @@ -2288,7 +2296,8 @@ EditorPropertyResource::EditorPropertyResource() { sub_inspector = NULL; sub_inspector_vbox = NULL; - use_sub_inspector = !bool(EDITOR_GET("interface/inspector/open_resources_in_new_inspector")); + use_sub_inspector = bool(EDITOR_GET("interface/inspector/open_resources_in_current_inspector")); + HBoxContainer *hbc = memnew(HBoxContainer); add_child(hbc); assign = memnew(Button); @@ -2691,6 +2700,22 @@ bool EditorInspectorDefaultPlugin::parse_property(Object *p_object, Variant::Typ case Variant::OBJECT: { EditorPropertyResource *editor = memnew(EditorPropertyResource); editor->setup(p_hint == PROPERTY_HINT_RESOURCE_TYPE ? p_hint_text : "Resource"); + + if (p_hint == PROPERTY_HINT_RESOURCE_TYPE) { + String open_in_new = EDITOR_GET("interface/inspector/resources_types_to_open_in_new_inspector"); + for (int i = 0; i < open_in_new.get_slice_count(","); i++) { + String type = open_in_new.get_slicec(',', i).strip_edges(); + for (int j = 0; j < p_hint_text.get_slice_count(","); j++) { + String inherits = p_hint_text.get_slicec(',', j); + + if (ClassDB::is_parent_class(inherits, type)) { + + editor->set_use_sub_inspector(false); + } + } + } + } + add_property_editor(p_path, editor); } break; diff --git a/editor/editor_properties.h b/editor/editor_properties.h index c67eccb60e..ecccd7274d 100644 --- a/editor/editor_properties.h +++ b/editor/editor_properties.h @@ -178,6 +178,7 @@ protected: public: void setup(const Vector<String> &p_options); virtual void update_property(); + void set_option_button_clip(bool p_enable); EditorPropertyEnum(); }; @@ -531,6 +532,8 @@ public: void collapse_all_folding(); void expand_all_folding(); + void set_use_sub_inspector(bool p_enable); + EditorPropertyResource(); }; diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp index f212b60c8c..c7a33de3f1 100644 --- a/editor/editor_spin_slider.cpp +++ b/editor/editor_spin_slider.cpp @@ -162,7 +162,7 @@ void EditorSpinSlider::_notification(int p_what) { draw_style_box(sb, Rect2(Vector2(), get_size())); Ref<Font> font = get_font("font", "LineEdit"); - int avail_width = get_size().width - sb->get_minimum_size().width - sb->get_minimum_size().width; + int avail_width = get_size().width - sb->get_minimum_size().width; avail_width -= font->get_string_size(label).width; Ref<Texture> updown = get_icon("updown", "SpinBox"); diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index 98402d8df5..0534a398f4 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -72,10 +72,11 @@ static Ref<StyleBoxFlat> make_flat_stylebox(Color p_color, float p_margin_left = return style; } -static Ref<StyleBoxLine> make_line_stylebox(Color p_color, int p_thickness = 1, float p_grow = 1, bool p_vertical = false) { +static Ref<StyleBoxLine> make_line_stylebox(Color p_color, int p_thickness = 1, float p_grow_begin = 1, float p_grow_end = 1, bool p_vertical = false) { Ref<StyleBoxLine> style(memnew(StyleBoxLine)); style->set_color(p_color); - style->set_grow(p_grow); + style->set_grow_begin(p_grow_begin); + style->set_grow_end(p_grow_end); style->set_thickness(p_thickness); style->set_vertical(p_vertical); return style; @@ -462,9 +463,20 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { Ref<StyleBoxLine> style_popup_separator(memnew(StyleBoxLine)); style_popup_separator->set_color(separator_color); - style_popup_separator->set_grow(popup_margin_size - MAX(EDSCALE, border_width)); + style_popup_separator->set_grow_begin(popup_margin_size - MAX(EDSCALE, border_width)); + style_popup_separator->set_grow_end(popup_margin_size - MAX(EDSCALE, border_width)); style_popup_separator->set_thickness(MAX(EDSCALE, border_width)); + Ref<StyleBoxLine> style_popup_labeled_separator_left(memnew(StyleBoxLine)); + style_popup_labeled_separator_left->set_grow_begin(popup_margin_size - MAX(EDSCALE, border_width)); + style_popup_labeled_separator_left->set_color(separator_color); + style_popup_labeled_separator_left->set_thickness(MAX(EDSCALE, border_width)); + + Ref<StyleBoxLine> style_popup_labeled_separator_right(memnew(StyleBoxLine)); + style_popup_labeled_separator_right->set_grow_end(popup_margin_size - MAX(EDSCALE, border_width)); + style_popup_labeled_separator_right->set_color(separator_color); + style_popup_labeled_separator_right->set_thickness(MAX(EDSCALE, border_width)); + Ref<StyleBoxEmpty> style_empty = make_empty_stylebox(default_margin_size, default_margin_size, default_margin_size, default_margin_size); // Tabs @@ -578,6 +590,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { theme->set_icon("arrow", "OptionButton", theme->get_icon("GuiOptionArrow", "EditorIcons")); theme->set_constant("arrow_margin", "OptionButton", default_margin_size * EDSCALE); theme->set_constant("modulate_arrow", "OptionButton", true); + theme->set_constant("hseparation", "OptionButton", 4 * EDSCALE); // CheckButton theme->set_stylebox("normal", "CheckButton", style_menu); @@ -626,6 +639,9 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { Ref<StyleBoxFlat> style_popup_menu = style_popup; theme->set_stylebox("panel", "PopupMenu", style_popup_menu); theme->set_stylebox("separator", "PopupMenu", style_popup_separator); + theme->set_stylebox("labeled_separator_left", "PopupMenu", style_popup_labeled_separator_left); + theme->set_stylebox("labeled_separator_right", "PopupMenu", style_popup_labeled_separator_right); + theme->set_color("font_color", "PopupMenu", font_color); theme->set_color("font_color_hover", "PopupMenu", font_color_hl); theme->set_color("font_color_accel", "PopupMenu", font_color_disabled); @@ -780,7 +796,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { // Separators theme->set_stylebox("separator", "HSeparator", make_line_stylebox(separator_color, border_width)); - theme->set_stylebox("separator", "VSeparator", make_line_stylebox(separator_color, border_width, 0, true)); + theme->set_stylebox("separator", "VSeparator", make_line_stylebox(separator_color, border_width, 0, 0, true)); // Debugger @@ -1005,6 +1021,8 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { theme->set_constant("title_h_offset", "GraphNode", -16 * EDSCALE); theme->set_constant("close_h_offset", "GraphNode", 20 * EDSCALE); theme->set_constant("close_offset", "GraphNode", 20 * EDSCALE); + theme->set_constant("separation", "GraphNode", 1 * EDSCALE); + theme->set_icon("close", "GraphNode", theme->get_icon("GuiCloseCustomizable", "EditorIcons")); theme->set_icon("resizer", "GraphNode", theme->get_icon("GuiResizer", "EditorIcons")); theme->set_icon("port", "GraphNode", theme->get_icon("GuiGraphNodePort", "EditorIcons")); diff --git a/editor/icons/icon_cylinder_shape.svg b/editor/icons/icon_cylinder_shape.svg new file mode 100644 index 0000000000..abda347ec5 --- /dev/null +++ b/editor/icons/icon_cylinder_shape.svg @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg width="16" height="16" version="1.1" viewBox="0 0 14.999999 14.999999" xmlns="http://www.w3.org/2000/svg"> +<rect fill="#68b6ff" width="13.171325" height="7.6993308" x="0.89037383" y="3.6879442"/> +<ellipse fill="#a2d2ff" cx="7.4772978" cy="3.7229116" rx="6.5864792" ry="2.820821"/> +<ellipse fill="#68b6ff" cx="7.4746876" cy="11.34481" rx="6.5864792" ry="2.8208208"/> +</svg> diff --git a/editor/icons/icon_expand_bottom_dock.svg b/editor/icons/icon_expand_bottom_dock.svg new file mode 100644 index 0000000000..5a1760f377 --- /dev/null +++ b/editor/icons/icon_expand_bottom_dock.svg @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_expand_bottom_dock.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1853" + inkscape:window-height="1016" + id="namedview8" + showgrid="false" + inkscape:zoom="20.85965" + inkscape:cx="9.4509357" + inkscape:cy="6.016355" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="1" + inkscape:current-layer="svg6" /> + <path + style="fill:#e0e0e0" + d="M 4.2130251,4.516057 0.6774912,8.0515909 H 3.2131761 V 13.025308 H 5.2130155 V 8.0515909 H 7.7487004 L 4.2131665,4.516057 Z" + id="path829" + inkscape:connector-curvature="0" + sodipodi:nodetypes="ccccccccc" /> + <path + inkscape:connector-curvature="0" + id="path831" + d="M 11.907306,4.6119359 8.3717718,8.1474698 h 2.5356852 v 4.9737172 h 1.999839 V 8.1474698 h 2.535685 L 11.907447,4.6119359 Z" + style="fill:#e0e0e0" + sodipodi:nodetypes="ccccccccc" /> + <rect + style="fill:#e0e0e0;fill-opacity:1" + id="rect855" + width="14" + height="1.8305085" + x="1.2881356" + y="1.3700738" /> +</svg> diff --git a/editor/icons/icon_shrink_bottom_dock.svg b/editor/icons/icon_shrink_bottom_dock.svg new file mode 100644 index 0000000000..c1e8c1bfdb --- /dev/null +++ b/editor/icons/icon_shrink_bottom_dock.svg @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_shrink_bottom_dock.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1853" + inkscape:window-height="1016" + id="namedview8" + showgrid="false" + inkscape:zoom="20.85965" + inkscape:cx="9.4509357" + inkscape:cy="6.016355" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="1" + inkscape:current-layer="svg6" /> + <path + style="fill:#e0e0e0" + d="M 11.907447,9.9752038 15.442981,6.4396699 H 12.907296 V 1.4659528 h -1.999839 l 0,4.9737171 -2.5356852,0 3.5355342,3.5355339 z" + id="path829" + inkscape:connector-curvature="0" + sodipodi:nodetypes="ccccccccc" /> + <path + inkscape:connector-curvature="0" + id="path831" + d="M 4.2131662,9.8793249 7.7487004,6.343791 H 5.2130152 V 1.3700738 H 3.2131762 V 6.343791 h -2.535685 l 3.535534,3.5355339 z" + style="fill:#e0e0e0" + sodipodi:nodetypes="ccccccccc" /> + <rect + style="fill:#e0e0e0;fill-opacity:1" + id="rect855" + width="14" + height="1.8305085" + x="-14.832336" + y="-13.121187" + transform="scale(-1)" /> +</svg> diff --git a/editor/icons/icon_visual_shader.svg b/editor/icons/icon_visual_shader.svg new file mode 100644 index 0000000000..e2c4f128b2 --- /dev/null +++ b/editor/icons/icon_visual_shader.svg @@ -0,0 +1,105 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg20" + sodipodi:docname="icon_visual_shader.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata26"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs24" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="640" + inkscape:window-height="480" + id="namedview22" + showgrid="false" + inkscape:zoom="14.75" + inkscape:cx="8" + inkscape:cy="8" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg20" /> + <g + id="g18" + transform="matrix(1,0,0,0.50605327,0,0.49394673)"> + <path + d="M 2,1 C 1.44774,1.0001 1.00006,1.4477 1,2 v 12 c 5.52e-5,0.5523 0.44774,0.9999 1,1 h 12 c 0.55226,-10e-5 0.99994,-0.4477 1,-1 V 6 L 10,1 Z m 1,2 h 6 v 3 c 0,0.554 0.44599,1 1,1 h 3 v 6 H 3 Z" + id="path2" + inkscape:connector-curvature="0" + style="fill:#e0e0e0" /> + <path + d="m 10,11 h 2 v 1 h -2 z" + id="path4" + inkscape:connector-curvature="0" + style="fill:#9f70ff" /> + <path + d="M 4,6 H 6 V 7 H 4 Z" + id="path6" + inkscape:connector-curvature="0" + style="fill:#ffeb70" /> + <path + d="m 8,8 h 4 V 9 H 8 Z" + id="path8" + inkscape:connector-curvature="0" + style="fill:#9dff70" /> + <path + d="M 7,6 H 8 V 7 H 7 Z" + id="path10" + inkscape:connector-curvature="0" + style="fill:#70deff" /> + <path + d="m 4,11 h 5 v 1 H 4 Z" + id="path12" + inkscape:connector-curvature="0" + style="fill:#ff70ac" /> + <path + d="M 4,4 H 7 V 5 H 4 Z" + id="path14" + inkscape:connector-curvature="0" + style="fill:#ff7070" /> + <path + d="M 4,8 H 7 V 9 H 4 Z" + id="path16" + inkscape:connector-curvature="0" + style="fill:#70ffb9" /> + </g> + <path + inkscape:connector-curvature="0" + style="fill:#e0e0e0" + d="m 2.8642321,9 v 6 h 2 a 3,3 0 0 0 3,-3 V 9 h -2 v 3 a 1,1 0 0 1 -1,1 V 9 Z" + id="path1394" /> + <path + inkscape:connector-curvature="0" + style="fill:#e0e0e0" + d="m 10.864232,9 a 2,2 0 0 0 -1.7323999,1 2,2 0 0 0 0,2 2,2 0 0 0 1.7323999,1 H 8.8642321 v 2 h 1.9999999 a 2,2 0 0 0 1.7324,-1 2,2 0 0 0 0,-2 2,2 0 0 0 -1.7324,-1 h 2 V 9 Z" + id="path30" /> +</svg> diff --git a/editor/plugins/animation_blend_tree_editor_plugin.cpp b/editor/plugins/animation_blend_tree_editor_plugin.cpp index 3efb2736b5..c00ad451fa 100644 --- a/editor/plugins/animation_blend_tree_editor_plugin.cpp +++ b/editor/plugins/animation_blend_tree_editor_plugin.cpp @@ -246,7 +246,7 @@ void AnimationNodeBlendTreeEditor::_add_node(int p_idx) { Point2 instance_pos = graph->get_scroll_ofs() + graph->get_size() * 0.5; - anode->set_position(instance_pos); + anode->set_position(instance_pos / EDSCALE); String base_name = add_options[p_idx].name; int base = 1; diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index aa4673f41e..876da7f61a 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -1872,6 +1872,7 @@ void ScriptEditor::save_all_scripts() { } _update_script_names(); + EditorFileSystem::get_singleton()->update_script_classes(); } void ScriptEditor::apply_scripts() const { diff --git a/editor/plugins/shader_editor_plugin.cpp b/editor/plugins/shader_editor_plugin.cpp index 9b31e1a421..4b7f27c0c1 100644 --- a/editor/plugins/shader_editor_plugin.cpp +++ b/editor/plugins/shader_editor_plugin.cpp @@ -130,9 +130,9 @@ void ShaderTextEditor::_load_theme_settings() { } } - for (const Set<String>::Element *E = ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())).front(); E; E = E->next()) { + for (int i = 0; i < ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())).size(); i++) { - keywords.push_back(E->get()); + keywords.push_back(ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode()))[i]); } } diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp new file mode 100644 index 0000000000..9a351c26fa --- /dev/null +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -0,0 +1,1217 @@ +#include "visual_shader_editor_plugin.h" + +#include "core/io/resource_loader.h" +#include "core/project_settings.h" +#include "editor/editor_properties.h" +#include "os/input.h" +#include "os/keyboard.h" +#include "scene/animation/animation_player.h" +#include "scene/gui/menu_button.h" +#include "scene/gui/panel.h" +#include "scene/main/viewport.h" + +Control *VisualShaderNodePlugin::create_editor(const Ref<VisualShaderNode> &p_node) { + + if (get_script_instance()) { + return get_script_instance()->call("create_editor", p_node); + } + return NULL; +} + +void VisualShaderNodePlugin::_bind_methods() { + + BIND_VMETHOD(MethodInfo(Variant::OBJECT, "create_editor", PropertyInfo(Variant::OBJECT, "for_node", PROPERTY_HINT_RESOURCE_TYPE, "VisualShaderNode"))); +} + +/////////////////// + +void VisualShaderEditor::edit(VisualShader *p_visual_shader) { + + if (p_visual_shader) { + visual_shader = Ref<VisualShader>(p_visual_shader); + } else { + visual_shader.unref(); + } + + if (visual_shader.is_null()) { + hide(); + } else { + _update_graph(); + } +} + +void VisualShaderEditor::add_plugin(const Ref<VisualShaderNodePlugin> &p_plugin) { + if (plugins.find(p_plugin) != -1) + return; + plugins.push_back(p_plugin); +} + +void VisualShaderEditor::remove_plugin(const Ref<VisualShaderNodePlugin> &p_plugin) { + plugins.erase(p_plugin); +} + +void VisualShaderEditor::add_custom_type(const String &p_name, const String &p_category, const Ref<Script> &p_script) { + + for (int i = 0; i < add_options.size(); i++) { + ERR_FAIL_COND(add_options[i].script == p_script); + } + + AddOption ao; + ao.name = p_name; + ao.script = p_script; + ao.category = p_category; + add_options.push_back(ao); + + _update_options_menu(); +} + +void VisualShaderEditor::remove_custom_type(const Ref<Script> &p_script) { + + for (int i = 0; i < add_options.size(); i++) { + if (add_options[i].script == p_script) { + add_options.remove(i); + return; + } + } + + _update_options_menu(); +} + +void VisualShaderEditor::_update_options_menu() { + + String prev_category; + add_node->get_popup()->clear(); + for (int i = 0; i < add_options.size(); i++) { + if (prev_category != add_options[i].category) { + add_node->get_popup()->add_separator(add_options[i].category); + } + add_node->get_popup()->add_item(add_options[i].name, i); + prev_category = add_options[i].category; + } +} + +Size2 VisualShaderEditor::get_minimum_size() const { + + return Size2(10, 200); +} + +void VisualShaderEditor::_draw_color_over_button(Object *obj, Color p_color) { + + Button *button = Object::cast_to<Button>(obj); + if (!button) + return; + + Ref<StyleBox> normal = get_stylebox("normal", "Button"); + button->draw_rect(Rect2(normal->get_offset(), button->get_size() - normal->get_minimum_size()), p_color); +} + +static Ref<StyleBoxEmpty> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1) { + Ref<StyleBoxEmpty> style(memnew(StyleBoxEmpty)); + style->set_default_margin(MARGIN_LEFT, p_margin_left * EDSCALE); + style->set_default_margin(MARGIN_RIGHT, p_margin_right * EDSCALE); + style->set_default_margin(MARGIN_BOTTOM, p_margin_bottom * EDSCALE); + style->set_default_margin(MARGIN_TOP, p_margin_top * EDSCALE); + return style; +} + +void VisualShaderEditor::_update_graph() { + + if (updating) + return; + + graph->set_scroll_ofs(visual_shader->get_graph_offset() * EDSCALE); + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + graph->clear_connections(); + //erase all nodes + for (int i = 0; i < graph->get_child_count(); i++) { + + if (Object::cast_to<GraphNode>(graph->get_child(i))) { + memdelete(graph->get_child(i)); + i--; + } + } + + static const Color type_color[3] = { + Color::html("#61daf4"), + Color::html("#d67dee"), + Color::html("#f6a86e") + }; + + List<VisualShader::Connection> connections; + visual_shader->get_node_connections(type, &connections); + + Ref<StyleBoxEmpty> label_style = make_empty_stylebox(2, 1, 2, 1); + + Vector<int> nodes = visual_shader->get_node_list(type); + + for (int n_i = 0; n_i < nodes.size(); n_i++) { + + Vector2 position = visual_shader->get_node_position(type, nodes[n_i]); + Ref<VisualShaderNode> vsnode = visual_shader->get_node(type, nodes[n_i]); + + GraphNode *node = memnew(GraphNode); + graph->add_child(node); + + /*if (!vsnode->is_connected("changed", this, "_node_changed")) { + vsnode->connect("changed", this, "_node_changed", varray(vsnode->get_instance_id()), CONNECT_DEFERRED); + }*/ + + node->set_offset(position); + + node->set_title(vsnode->get_caption()); + node->set_name(itos(nodes[n_i])); + + if (nodes[n_i] >= 2) { + node->set_show_close_button(true); + node->connect("close_request", this, "_delete_request", varray(nodes[n_i]), CONNECT_DEFERRED); + } + + node->connect("dragged", this, "_node_dragged", varray(nodes[n_i])); + + Control *custom_editor = NULL; + int port_offset = 0; + + Ref<VisualShaderNodeUniform> uniform = vsnode; + if (uniform.is_valid()) { + LineEdit *uniform_name = memnew(LineEdit); + uniform_name->set_text(uniform->get_uniform_name()); + node->add_child(uniform_name); + uniform_name->connect("text_entered", this, "_line_edit_changed", varray(uniform_name, nodes[n_i])); + uniform_name->connect("focus_exited", this, "_line_edit_focus_out", varray(uniform_name, nodes[n_i])); + + if (vsnode->get_input_port_count() == 0 && vsnode->get_output_port_count() == 1 && vsnode->get_output_port_name(0) == "") { + //shortcut + VisualShaderNode::PortType port_right = vsnode->get_output_port_type(0); + node->set_slot(0, false, VisualShaderNode::PORT_TYPE_SCALAR, Color(), true, port_right, type_color[port_right]); + continue; + } + port_offset++; + } + + for (int i = 0; i < plugins.size(); i++) { + custom_editor = plugins[i]->create_editor(vsnode); + if (custom_editor) { + break; + } + } + + if (custom_editor && vsnode->get_output_port_count() > 0 && vsnode->get_output_port_name(0) == "" && (vsnode->get_input_port_count() == 0 || vsnode->get_input_port_name(0) == "")) { + //will be embedded in first port + } else if (custom_editor) { + port_offset++; + node->add_child(custom_editor); + custom_editor = NULL; + } + + for (int i = 0; i < MAX(vsnode->get_input_port_count(), vsnode->get_output_port_count()); i++) { + + if (vsnode->is_port_separator(i)) { + node->add_child(memnew(HSeparator)); + port_offset++; + } + + bool valid_left = i < vsnode->get_input_port_count(); + VisualShaderNode::PortType port_left = VisualShaderNode::PORT_TYPE_SCALAR; + bool port_left_used = false; + String name_left; + if (valid_left) { + name_left = vsnode->get_input_port_name(i); + port_left = vsnode->get_input_port_type(i); + for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { + if (E->get().to_node == nodes[n_i] && E->get().to_port == i) { + port_left_used = true; + } + } + } + + bool valid_right = i < vsnode->get_output_port_count(); + VisualShaderNode::PortType port_right = VisualShaderNode::PORT_TYPE_SCALAR; + String name_right; + if (valid_right) { + name_right = vsnode->get_output_port_name(i); + port_right = vsnode->get_output_port_type(i); + } + + HBoxContainer *hb = memnew(HBoxContainer); + + Variant default_value; + + if (valid_left && !port_left_used) { + default_value = vsnode->get_input_port_default_value(i); + } + + if (default_value.get_type() != Variant::NIL) { // only a label + Button *button = memnew(Button); + hb->add_child(button); + button->connect("pressed", this, "_edit_port_default_input", varray(button, nodes[n_i], i)); + + switch (default_value.get_type()) { + + case Variant::COLOR: { + button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); + button->connect("draw", this, "_draw_color_over_button", varray(button, default_value)); + } break; + case Variant::INT: + case Variant::REAL: { + button->set_text(String::num(default_value, 4)); + } break; + case Variant::VECTOR3: { + Vector3 v = default_value; + button->set_text(String::num(v.x, 3) + "," + String::num(v.y, 3) + "," + String::num(v.z, 3)); + } break; + default: {} + } + } + + if (i == 0 && custom_editor) { + + hb->add_child(custom_editor); + custom_editor->set_h_size_flags(SIZE_EXPAND_FILL); + } else { + + if (valid_left) { + + Label *label = memnew(Label); + label->set_text(name_left); + label->add_style_override("normal", label_style); //more compact + hb->add_child(label); + } + + hb->add_spacer(); + + if (valid_right) { + + Label *label = memnew(Label); + label->set_text(name_right); + label->set_align(Label::ALIGN_RIGHT); + label->add_style_override("normal", label_style); //more compact + hb->add_child(label); + } + } + + if (valid_right && edit_type->get_selected() == VisualShader::TYPE_FRAGMENT) { + TextureButton *preview = memnew(TextureButton); + preview->set_toggle_mode(true); + preview->set_normal_texture(get_icon("GuiVisibilityHidden", "EditorIcons")); + preview->set_pressed_texture(get_icon("GuiVisibilityVisible", "EditorIcons")); + preview->set_v_size_flags(SIZE_SHRINK_CENTER); + + if (vsnode->get_output_port_for_preview() == i) { + preview->set_pressed(true); + } + + preview->connect("pressed", this, "_preview_select_port", varray(nodes[n_i], i), CONNECT_DEFERRED); + hb->add_child(preview); + } + + node->add_child(hb); + + node->set_slot(i + port_offset, valid_left, port_left, type_color[port_left], valid_right, port_right, type_color[port_right]); + } + + if (vsnode->get_output_port_for_preview() >= 0) { + VisualShaderNodePortPreview *port_preview = memnew(VisualShaderNodePortPreview); + port_preview->setup(visual_shader, type, nodes[n_i], vsnode->get_output_port_for_preview()); + port_preview->set_h_size_flags(SIZE_SHRINK_CENTER); + node->add_child(port_preview); + } + + String error = vsnode->get_warning(visual_shader->get_mode(), type); + if (error != String()) { + Label *error_label = memnew(Label); + error_label->add_color_override("font_color", get_color("error_color", "Editor")); + error_label->set_text(error); + node->add_child(error_label); + } + } + + for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { + + int from = E->get().from_node; + int from_idx = E->get().from_port; + int to = E->get().to_node; + int to_idx = E->get().to_port; + + graph->connect_node(itos(from), from_idx, itos(to), to_idx); + } +} + +void VisualShaderEditor::_preview_select_port(int p_node, int p_port) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + Ref<VisualShaderNode> node = visual_shader->get_node(type, p_node); + if (node.is_null()) { + return; + } + + if (node->get_output_port_for_preview() == p_port) { + p_port = -1; //toggle it + } + undo_redo->create_action("Set Uniform Name"); + undo_redo->add_do_method(node.ptr(), "set_output_port_for_preview", p_port); + undo_redo->add_undo_method(node.ptr(), "set_output_port_for_preview", node->get_output_port_for_preview()); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); +} + +void VisualShaderEditor::_line_edit_changed(const String &p_text, Object *line_edit, int p_node_id) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + Ref<VisualShaderNodeUniform> node = visual_shader->get_node(type, p_node_id); + ERR_FAIL_COND(!node.is_valid()); + + String validated_name = visual_shader->validate_uniform_name(p_text, node); + + updating = true; + undo_redo->create_action("Set Uniform Name"); + undo_redo->add_do_method(node.ptr(), "set_uniform_name", validated_name); + undo_redo->add_undo_method(node.ptr(), "set_uniform_name", node->get_uniform_name()); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); + updating = false; + + Object::cast_to<LineEdit>(line_edit)->set_text(validated_name); +} + +void VisualShaderEditor::_line_edit_focus_out(Object *line_edit, int p_node_id) { + + String text = Object::cast_to<LineEdit>(line_edit)->get_text(); + _line_edit_changed(text, line_edit, p_node_id); +} + +void VisualShaderEditor::_port_edited() { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + Variant value = property_editor->get_variant(); + Ref<VisualShaderNode> vsn = visual_shader->get_node(type, editing_node); + ERR_FAIL_COND(!vsn.is_valid()); + + undo_redo->create_action("Set Input Default Port"); + undo_redo->add_do_method(vsn.ptr(), "set_input_port_default_value", editing_port, value); + undo_redo->add_undo_method(vsn.ptr(), "set_input_port_default_value", editing_port, vsn->get_input_port_default_value(editing_port)); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); + + property_editor->hide(); +} + +void VisualShaderEditor::_edit_port_default_input(Object *p_button, int p_node, int p_port) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + Ref<VisualShaderNode> vsn = visual_shader->get_node(type, p_node); + + Button *button = Object::cast_to<Button>(p_button); + ERR_FAIL_COND(!button); + Variant value = vsn->get_input_port_default_value(p_port); + property_editor->set_global_position(button->get_global_position() + Vector2(0, button->get_size().height)); + property_editor->edit(NULL, "", value.get_type(), value, 0, ""); + property_editor->popup(); + editing_node = p_node; + editing_port = p_port; +} + +void VisualShaderEditor::_add_node(int p_idx) { + + ERR_FAIL_INDEX(p_idx, add_options.size()); + + Ref<VisualShaderNode> vsnode; + + if (add_options[p_idx].type != String()) { + VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instance(add_options[p_idx].type)); + ERR_FAIL_COND(!vsn); + vsnode = Ref<VisualShaderNode>(vsn); + } else { + ERR_FAIL_COND(add_options[p_idx].script.is_null()); + String base_type = add_options[p_idx].script->get_instance_base_type(); + VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instance(base_type)); + ERR_FAIL_COND(!vsn); + vsnode = Ref<VisualShaderNode>(vsn); + vsnode->set_script(add_options[p_idx].script.get_ref_ptr()); + } + + Point2 position = (graph->get_scroll_ofs() + graph->get_size() * 0.5) / EDSCALE; + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + int id_to_use = visual_shader->get_valid_node_id(type); + + undo_redo->create_action("Add Node to Visual Shader"); + undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, vsnode, position, id_to_use); + undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_to_use); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); +} + +void VisualShaderEditor::_node_dragged(const Vector2 &p_from, const Vector2 &p_to, int p_node) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + updating = true; + undo_redo->create_action("Node Moved"); + undo_redo->add_do_method(visual_shader.ptr(), "set_node_position", type, p_node, p_to); + undo_redo->add_undo_method(visual_shader.ptr(), "set_node_position", type, p_node, p_from); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); + updating = false; +} + +void VisualShaderEditor::_connection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + int from = p_from.to_int(); + int to = p_to.to_int(); + + if (!visual_shader->can_connect_nodes(type, from, p_from_index, to, p_to_index)) { + EditorNode::get_singleton()->show_warning(TTR("Unable to connect, port may be in use or connection may be invalid.")); + return; + } + + undo_redo->create_action("Nodes Connected"); + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); +} + +void VisualShaderEditor::_disconnection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index) { + + graph->disconnect_node(p_from, p_from_index, p_to, p_to_index); + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + int from = p_from.to_int(); + int to = p_to.to_int(); + + //updating = true; seems graph edit can handle this, no need to protect + undo_redo->create_action("Nodes Disconnected"); + undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); + //updating = false; +} + +void VisualShaderEditor::_connection_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_position) { +} + +void VisualShaderEditor::_delete_request(int which) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + undo_redo->create_action("Delete Node"); + undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, which); + undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, visual_shader->get_node(type, which), visual_shader->get_node_position(type, which), which); + + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().from_node == which || E->get().to_node == which) { + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + } + + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); +} + +void VisualShaderEditor::_node_selected(Object *p_node) { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + GraphNode *gn = Object::cast_to<GraphNode>(p_node); + ERR_FAIL_COND(!gn); + + int id = String(gn->get_name()).to_int(); + + Ref<VisualShaderNode> vsnode = visual_shader->get_node(type, id); + ERR_FAIL_COND(!vsnode.is_valid()); + + //do not rely on this, makes editor more complex + //EditorNode::get_singleton()->push_item(vsnode.ptr(), "", true); +} + +void VisualShaderEditor::_input(const Ref<InputEvent> p_event) { + if (graph->has_focus()) { + Ref<InputEventMouseButton> mb = p_event; + + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_RIGHT) { + add_node->get_popup()->set_position(get_viewport()->get_mouse_position()); + add_node->get_popup()->show_modal(); + } + } +} + +void VisualShaderEditor::_notification(int p_what) { + + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + + error_panel->add_style_override("panel", get_stylebox("bg", "Tree")); + error_label->add_color_override("font_color", get_color("error_color", "Editor")); + } + + if (p_what == NOTIFICATION_PROCESS) { + } +} + +void VisualShaderEditor::_scroll_changed(const Vector2 &p_scroll) { + if (updating) + return; + updating = true; + visual_shader->set_graph_offset(p_scroll / EDSCALE); + updating = false; +} + +void VisualShaderEditor::_node_changed(int p_id) { + if (updating) + return; + + if (is_visible_in_tree()) { + _update_graph(); + } +} + +void VisualShaderEditor::_duplicate_nodes() { + + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + + List<int> nodes; + + for (int i = 0; i < graph->get_child_count(); i++) { + + if (Object::cast_to<GraphNode>(graph->get_child(i))) { + int id = String(graph->get_child(i)->get_name()).to_int(); + Ref<VisualShaderNode> node = visual_shader->get_node(type, id); + Ref<VisualShaderNodeOutput> output = node; + if (output.is_valid()) //cant duplicate output + continue; + if (node.is_valid()) { + nodes.push_back(id); + } + } + } + + if (nodes.empty()) + return; + + undo_redo->create_action("Duplicate Nodes"); + + int base_id = visual_shader->get_valid_node_id(type); + int id_from = base_id; + Map<int, int> connection_remap; + + for (List<int>::Element *E = nodes.front(); E; E = E->next()) { + + connection_remap[E->get()] = id_from; + Ref<VisualShaderNode> node = visual_shader->get_node(type, E->get()); + + Ref<VisualShaderNode> dupli = node->duplicate(); + + undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, dupli, visual_shader->get_node_position(type, E->get()) + Vector2(10, 10) * EDSCALE, id_from); + undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_from); + + id_from++; + } + + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (connection_remap.has(E->get().from_node) && connection_remap.has(E->get().to_node)) { + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, connection_remap[E->get().from_node], E->get().from_port, connection_remap[E->get().to_node], E->get().to_port); + } + } + + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); + + //reselect + for (int i = 0; i < graph->get_child_count(); i++) { + + if (Object::cast_to<GraphNode>(graph->get_child(i))) { + int id = String(graph->get_child(i)->get_name()).to_int(); + if (nodes.find(id)) { + Object::cast_to<GraphNode>(graph->get_child(i))->set_selected(true); + } else { + Object::cast_to<GraphNode>(graph->get_child(i))->set_selected(false); + } + } + } +} + +void VisualShaderEditor::_mode_selected(int p_id) { + _update_graph(); +} + +void VisualShaderEditor::_input_select_item(Ref<VisualShaderNodeInput> input, String name) { + + String prev_name = input->get_input_name(); + + if (name == prev_name) + return; + + bool type_changed = input->get_input_type_by_name(name) != input->get_input_type_by_name(prev_name); + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action("Visual Shader Input Type Changed"); + + undo_redo->add_do_method(input.ptr(), "set_input_name", name); + undo_redo->add_undo_method(input.ptr(), "set_input_name", prev_name); + + if (type_changed) { + //restore connections if type changed + VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + int id = visual_shader->find_node_id(type, input); + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().from_node == id) { + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + } + } + + undo_redo->add_do_method(VisualShaderEditor::get_singleton(), "_update_graph"); + undo_redo->add_undo_method(VisualShaderEditor::get_singleton(), "_update_graph"); + + undo_redo->commit_action(); +} + +void VisualShaderEditor::_bind_methods() { + + ClassDB::bind_method("_update_graph", &VisualShaderEditor::_update_graph); + ClassDB::bind_method("_add_node", &VisualShaderEditor::_add_node); + ClassDB::bind_method("_node_dragged", &VisualShaderEditor::_node_dragged); + ClassDB::bind_method("_connection_request", &VisualShaderEditor::_connection_request); + ClassDB::bind_method("_disconnection_request", &VisualShaderEditor::_disconnection_request); + ClassDB::bind_method("_node_selected", &VisualShaderEditor::_node_selected); + ClassDB::bind_method("_scroll_changed", &VisualShaderEditor::_scroll_changed); + ClassDB::bind_method("_delete_request", &VisualShaderEditor::_delete_request); + ClassDB::bind_method("_node_changed", &VisualShaderEditor::_node_changed); + ClassDB::bind_method("_edit_port_default_input", &VisualShaderEditor::_edit_port_default_input); + ClassDB::bind_method("_port_edited", &VisualShaderEditor::_port_edited); + ClassDB::bind_method("_connection_to_empty", &VisualShaderEditor::_connection_to_empty); + ClassDB::bind_method("_line_edit_focus_out", &VisualShaderEditor::_line_edit_focus_out); + ClassDB::bind_method("_line_edit_changed", &VisualShaderEditor::_line_edit_changed); + ClassDB::bind_method("_duplicate_nodes", &VisualShaderEditor::_duplicate_nodes); + ClassDB::bind_method("_mode_selected", &VisualShaderEditor::_mode_selected); + ClassDB::bind_method("_input_select_item", &VisualShaderEditor::_input_select_item); + ClassDB::bind_method("_preview_select_port", &VisualShaderEditor::_preview_select_port); + ClassDB::bind_method("_input", &VisualShaderEditor::_input); +} + +VisualShaderEditor *VisualShaderEditor::singleton = NULL; + +VisualShaderEditor::VisualShaderEditor() { + + singleton = this; + updating = false; + + graph = memnew(GraphEdit); + add_child(graph); + graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_SCALAR); + graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_VECTOR); + graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_TRANSFORM); + //graph->add_valid_left_disconnect_type(0); + graph->set_v_size_flags(SIZE_EXPAND_FILL); + graph->connect("connection_request", this, "_connection_request", varray(), CONNECT_DEFERRED); + graph->connect("disconnection_request", this, "_disconnection_request", varray(), CONNECT_DEFERRED); + graph->connect("node_selected", this, "_node_selected"); + graph->connect("scroll_offset_changed", this, "_scroll_changed"); + graph->connect("duplicate_nodes_request", this, "_duplicate_nodes"); + graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR); + graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR); + //graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_SCALAR); + graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR); + graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShaderNode::PORT_TYPE_TRANSFORM); + + VSeparator *vs = memnew(VSeparator); + graph->get_zoom_hbox()->add_child(vs); + graph->get_zoom_hbox()->move_child(vs, 0); + + edit_type = memnew(OptionButton); + edit_type->add_item(TTR("Vertex")); + edit_type->add_item(TTR("Fragment")); + edit_type->add_item(TTR("Light")); + edit_type->select(1); + edit_type->connect("item_selected", this, "_mode_selected"); + graph->get_zoom_hbox()->add_child(edit_type); + graph->get_zoom_hbox()->move_child(edit_type, 0); + + add_node = memnew(MenuButton); + graph->get_zoom_hbox()->add_child(add_node); + add_node->set_text(TTR("Add Node..")); + graph->get_zoom_hbox()->move_child(add_node, 0); + add_node->get_popup()->connect("id_pressed", this, "_add_node"); + + add_options.push_back(AddOption("Scalar", "Constants", "VisualShaderNodeScalarConstant")); + add_options.push_back(AddOption("Vector", "Constants", "VisualShaderNodeVec3Constant")); + add_options.push_back(AddOption("Color", "Constants", "VisualShaderNodeColorConstant")); + add_options.push_back(AddOption("Transform", "Constants", "VisualShaderNodeTransformConstant")); + add_options.push_back(AddOption("Texture", "Constants", "VisualShaderNodeTexture")); + add_options.push_back(AddOption("CubeMap", "Constants", "VisualShaderNodeCubeMap")); + add_options.push_back(AddOption("ScalarOp", "Operators", "VisualShaderNodeScalarOp")); + add_options.push_back(AddOption("VectorOp", "Operators", "VisualShaderNodeVectorOp")); + add_options.push_back(AddOption("ColorOp", "Operators", "VisualShaderNodeColorOp")); + add_options.push_back(AddOption("TransformMult", "Operators", "VisualShaderNodeTransformMult")); + add_options.push_back(AddOption("TransformVecMult", "Operators", "VisualShaderNodeTransformVecMult")); + add_options.push_back(AddOption("ScalarFunc", "Functions", "VisualShaderNodeScalarFunc")); + add_options.push_back(AddOption("VectorFunc", "Functions", "VisualShaderNodeVectorFunc")); + add_options.push_back(AddOption("DotProduct", "Functions", "VisualShaderNodeDotProduct")); + add_options.push_back(AddOption("VectorLen", "Functions", "VisualShaderNodeVectorLen")); + add_options.push_back(AddOption("ScalarInterp", "Interpolation", "VisualShaderNodeScalarInterp")); + add_options.push_back(AddOption("VectorInterp", "Interpolation", "VisualShaderNodeVectorInterp")); + add_options.push_back(AddOption("VectorConstruct", "Construct", "VisualShaderNodeVectorConstruct")); + add_options.push_back(AddOption("TransformConstruct", "Construct", "VisualShaderNodeTransformConstruct")); + add_options.push_back(AddOption("VectorDestruct", "Destruct", "VisualShaderNodeVectorDestruct")); + add_options.push_back(AddOption("TransformDestruct", "Destruct", "VisualShaderNodeTransformDestruct")); + add_options.push_back(AddOption("Scalar", "Uniforms", "VisualShaderNodeScalarUniform")); + add_options.push_back(AddOption("Vector", "Uniforms", "VisualShaderNodeVec3Uniform")); + add_options.push_back(AddOption("Color", "Uniforms", "VisualShaderNodeColorUniform")); + add_options.push_back(AddOption("Transform", "Uniforms", "VisualShaderNodeTransformUniform")); + add_options.push_back(AddOption("Texture", "Uniforms", "VisualShaderNodeTextureUniform")); + add_options.push_back(AddOption("CubeMap", "Uniforms", "VisualShaderNodeCubeMapUniform")); + add_options.push_back(AddOption("Input", "Inputs", "VisualShaderNodeInput")); + + _update_options_menu(); + + error_panel = memnew(PanelContainer); + add_child(error_panel); + error_label = memnew(Label); + error_panel->add_child(error_label); + error_label->set_text("eh"); + error_panel->hide(); + + undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + Ref<VisualShaderNodePluginDefault> default_plugin; + default_plugin.instance(); + add_plugin(default_plugin); + + property_editor = memnew(CustomPropertyEditor); + add_child(property_editor); + + property_editor->connect("variant_changed", this, "_port_edited"); +} + +void VisualShaderEditorPlugin::edit(Object *p_object) { + + visual_shader_editor->edit(Object::cast_to<VisualShader>(p_object)); +} + +bool VisualShaderEditorPlugin::handles(Object *p_object) const { + + return p_object->is_class("VisualShader"); +} + +void VisualShaderEditorPlugin::make_visible(bool p_visible) { + + if (p_visible) { + //editor->hide_animation_player_editors(); + //editor->animation_panel_make_visible(true); + button->show(); + editor->make_bottom_panel_item_visible(visual_shader_editor); + visual_shader_editor->set_process_input(true); + //visual_shader_editor->set_process(true); + } else { + + if (visual_shader_editor->is_visible_in_tree()) + editor->hide_bottom_panel(); + button->hide(); + visual_shader_editor->set_process_input(false); + //visual_shader_editor->set_process(false); + } +} + +VisualShaderEditorPlugin::VisualShaderEditorPlugin(EditorNode *p_node) { + + editor = p_node; + visual_shader_editor = memnew(VisualShaderEditor); + visual_shader_editor->set_custom_minimum_size(Size2(0, 300)); + + button = editor->add_bottom_panel_item(TTR("VisualShader"), visual_shader_editor); + button->hide(); +} + +VisualShaderEditorPlugin::~VisualShaderEditorPlugin() { +} + +//////////////// + +class VisualShaderNodePluginInputEditor : public OptionButton { + GDCLASS(VisualShaderNodePluginInputEditor, OptionButton) + + Ref<VisualShaderNodeInput> input; + +protected: + static void _bind_methods() { + ClassDB::bind_method("_item_selected", &VisualShaderNodePluginInputEditor::_item_selected); + } + +public: + void _notification(int p_what) { + if (p_what == NOTIFICATION_READY) { + connect("item_selected", this, "_item_selected"); + } + } + + void _item_selected(int p_item) { + VisualShaderEditor::get_singleton()->call_deferred("_input_select_item", input, get_item_text(p_item)); + } + + void setup(const Ref<VisualShaderNodeInput> &p_input) { + input = p_input; + Ref<Texture> type_icon[3] = { + EditorNode::get_singleton()->get_gui_base()->get_icon("float", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_icon("Vector3", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_icon("Transform", "EditorIcons"), + }; + + add_item("[None]"); + int to_select = -1; + for (int i = 0; i < input->get_input_index_count(); i++) { + if (input->get_input_name() == input->get_input_index_name(i)) { + to_select = i + 1; + } + add_icon_item(type_icon[input->get_input_index_type(i)], input->get_input_index_name(i)); + } + + if (to_select >= 0) { + select(to_select); + } + } +}; + +class VisualShaderNodePluginDefaultEditor : public VBoxContainer { + GDCLASS(VisualShaderNodePluginDefaultEditor, VBoxContainer) +public: + void _property_changed(const String &prop, const Variant &p_value) { + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + updating = true; + undo_redo->create_action("Edit Visual Property: " + prop, UndoRedo::MERGE_ENDS); + undo_redo->add_do_property(node.ptr(), prop, p_value); + undo_redo->add_undo_property(node.ptr(), prop, node->get(prop)); + undo_redo->commit_action(); + updating = false; + } + + void _node_changed() { + if (updating) + return; + for (int i = 0; i < properties.size(); i++) { + properties[i]->update_property(); + } + } + + void _refresh_request() { + VisualShaderEditor::get_singleton()->call_deferred("_update_graph"); + } + + bool updating; + Ref<VisualShaderNode> node; + Vector<EditorProperty *> properties; + + void setup(Vector<EditorProperty *> p_properties, const Vector<StringName> &p_names, Ref<VisualShaderNode> p_node) { + updating = false; + node = p_node; + properties = p_properties; + + for (int i = 0; i < p_properties.size(); i++) { + + add_child(p_properties[i]); + + properties[i]->connect("property_changed", this, "_property_changed"); + properties[i]->set_object_and_property(node.ptr(), p_names[i]); + properties[i]->update_property(); + properties[i]->set_name_split_ratio(0); + } + node->connect("changed", this, "_node_changed"); + node->connect("editor_refresh_request", this, "_refresh_request", varray(), CONNECT_DEFERRED); + } + + static void _bind_methods() { + ClassDB::bind_method("_property_changed", &VisualShaderNodePluginDefaultEditor::_property_changed); + ClassDB::bind_method("_node_changed", &VisualShaderNodePluginDefaultEditor::_node_changed); + ClassDB::bind_method("_refresh_request", &VisualShaderNodePluginDefaultEditor::_refresh_request); + } +}; + +Control *VisualShaderNodePluginDefault::create_editor(const Ref<VisualShaderNode> &p_node) { + + if (p_node->is_class("VisualShaderNodeInput")) { + //create input + VisualShaderNodePluginInputEditor *input_editor = memnew(VisualShaderNodePluginInputEditor); + input_editor->setup(p_node); + return input_editor; + } + + Vector<StringName> properties = p_node->get_editable_properties(); + if (properties.size() == 0) { + return NULL; + } + + List<PropertyInfo> props; + p_node->get_property_list(&props); + + Vector<PropertyInfo> pinfo; + + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + + for (int i = 0; i < properties.size(); i++) { + if (E->get().name == String(properties[i])) { + pinfo.push_back(E->get()); + } + } + } + + if (pinfo.size() == 0) + return NULL; + + properties.clear(); + + Ref<VisualShaderNode> node = p_node; + Vector<EditorProperty *> editors; + + for (int i = 0; i < pinfo.size(); i++) { + + EditorProperty *prop = EditorInspector::instantiate_property_editor(node.ptr(), pinfo[i].type, pinfo[i].name, pinfo[i].hint, pinfo[i].hint_string, pinfo[i].usage); + if (!prop) + return NULL; + + if (Object::cast_to<EditorPropertyResource>(prop)) { + Object::cast_to<EditorPropertyResource>(prop)->set_use_sub_inspector(false); + prop->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + } else if (Object::cast_to<EditorPropertyTransform>(prop)) { + prop->set_custom_minimum_size(Size2(250 * EDSCALE, 0)); + } else if (Object::cast_to<EditorPropertyFloat>(prop) || Object::cast_to<EditorPropertyVector3>(prop)) { + prop->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + } else if (Object::cast_to<EditorPropertyEnum>(prop)) { + prop->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + Object::cast_to<EditorPropertyEnum>(prop)->set_option_button_clip(false); + } + + editors.push_back(prop); + properties.push_back(pinfo[i].name); + } + VisualShaderNodePluginDefaultEditor *editor = memnew(VisualShaderNodePluginDefaultEditor); + editor->setup(editors, properties, p_node); + return editor; +} + +void EditorPropertyShaderMode::_option_selected(int p_which) { + + //will not use this, instead will do all the logic setting manually + //emit_signal("property_changed", get_edited_property(), p_which); + + Ref<VisualShader> visual_shader(Object::cast_to<VisualShader>(get_edited_object())); + + if (visual_shader->get_mode() == p_which) + return; + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action("Visual Shader Mode Changed"); + //do is easy + undo_redo->add_do_method(visual_shader.ptr(), "set_mode", p_which); + undo_redo->add_undo_method(visual_shader.ptr(), "set_mode", visual_shader->get_mode()); + //now undo is hell + + //1. restore connections to output + for (int i = 0; i < VisualShader::TYPE_MAX; i++) { + + VisualShader::Type type = VisualShader::Type(i); + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().to_node == VisualShader::NODE_ID_OUTPUT) { + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + } + } + //2. restore input indices + for (int i = 0; i < VisualShader::TYPE_MAX; i++) { + + VisualShader::Type type = VisualShader::Type(i); + Vector<int> nodes = visual_shader->get_node_list(type); + for (int i = 0; i < nodes.size(); i++) { + Ref<VisualShaderNodeInput> input = visual_shader->get_node(type, nodes[i]); + if (!input.is_valid()) { + continue; + } + + undo_redo->add_undo_method(input.ptr(), "set_input_name", input->get_input_name()); + } + } + + //3. restore enums and flags + List<PropertyInfo> props; + visual_shader->get_property_list(&props); + + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + + if (E->get().name.begins_with("flags/") || E->get().name.begins_with("modes/")) { + undo_redo->add_undo_property(visual_shader.ptr(), E->get().name, visual_shader->get(E->get().name)); + } + } + + //update graph + undo_redo->add_do_method(VisualShaderEditor::get_singleton(), "_update_graph"); + undo_redo->add_undo_method(VisualShaderEditor::get_singleton(), "_update_graph"); + + undo_redo->commit_action(); +} + +void EditorPropertyShaderMode::update_property() { + + int which = get_edited_object()->get(get_edited_property()); + options->select(which); +} + +void EditorPropertyShaderMode::setup(const Vector<String> &p_options) { + for (int i = 0; i < p_options.size(); i++) { + options->add_item(p_options[i], i); + } +} + +void EditorPropertyShaderMode::set_option_button_clip(bool p_enable) { + options->set_clip_text(p_enable); +} + +void EditorPropertyShaderMode::_bind_methods() { + + ClassDB::bind_method(D_METHOD("_option_selected"), &EditorPropertyShaderMode::_option_selected); +} + +EditorPropertyShaderMode::EditorPropertyShaderMode() { + options = memnew(OptionButton); + options->set_clip_text(true); + add_child(options); + add_focusable(options); + options->connect("item_selected", this, "_option_selected"); +} + +bool EditorInspectorShaderModePlugin::can_handle(Object *p_object) { + return true; //can handle everything +} + +void EditorInspectorShaderModePlugin::parse_begin(Object *p_object) { + //do none +} + +bool EditorInspectorShaderModePlugin::parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage) { + + if (p_path == "mode" && p_object->is_class("VisualShader") && p_type == Variant::INT) { + + EditorPropertyShaderMode *editor = memnew(EditorPropertyShaderMode); + Vector<String> options = p_hint_text.split(","); + editor->setup(options); + add_property_editor(p_path, editor); + + return true; + } + + return false; //can be overriden, although it will most likely be last anyway +} + +void EditorInspectorShaderModePlugin::parse_end() { + //do none +} +////////////////////////////////// + +void VisualShaderNodePortPreview::_shader_changed() { + if (shader.is_null()) { + return; + } + + Vector<VisualShader::DefaultTextureParam> default_textures; + String shader_code = shader->generate_preview_shader(type, node, port, default_textures); + + Ref<Shader> preview_shader; + preview_shader.instance(); + preview_shader->set_code(shader_code); + for (int i = 0; i < default_textures.size(); i++) { + preview_shader->set_default_texture_param(default_textures[i].name, default_textures[i].param); + } + + Ref<ShaderMaterial> material; + material.instance(); + material->set_shader(preview_shader); + + //find if a material is also being edited and copy parameters to this one + + for (int i = EditorNode::get_singleton()->get_editor_history()->get_path_size() - 1; i >= 0; i--) { + Object *object = ObjectDB::get_instance(EditorNode::get_singleton()->get_editor_history()->get_path_object(i)); + if (!object) + continue; + ShaderMaterial *src_mat = Object::cast_to<ShaderMaterial>(object); + if (src_mat && src_mat->get_shader().is_valid()) { + + List<PropertyInfo> params; + src_mat->get_shader()->get_param_list(¶ms); + for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) { + material->set(E->get().name, src_mat->get(E->get().name)); + } + } + } + + set_material(material); +} + +void VisualShaderNodePortPreview::setup(const Ref<VisualShader> &p_shader, VisualShader::Type p_type, int p_node, int p_port) { + + shader = p_shader; + shader->connect("changed", this, "_shader_changed"); + type = p_type; + port = p_port; + node = p_node; + update(); + _shader_changed(); +} + +Size2 VisualShaderNodePortPreview::get_minimum_size() const { + return Size2(100, 100) * EDSCALE; +} + +void VisualShaderNodePortPreview::_notification(int p_what) { + if (p_what == NOTIFICATION_DRAW) { + Vector<Vector2> points; + Vector<Vector2> uvs; + Vector<Color> colors; + points.push_back(Vector2()); + uvs.push_back(Vector2(0, 0)); + colors.push_back(Color(1, 1, 1, 1)); + points.push_back(Vector2(get_size().width, 0)); + uvs.push_back(Vector2(1, 0)); + colors.push_back(Color(1, 1, 1, 1)); + points.push_back(get_size()); + uvs.push_back(Vector2(1, 1)); + colors.push_back(Color(1, 1, 1, 1)); + points.push_back(Vector2(0, get_size().height)); + uvs.push_back(Vector2(0, 1)); + colors.push_back(Color(1, 1, 1, 1)); + + draw_primitive(points, colors, uvs); + } +} + +void VisualShaderNodePortPreview::_bind_methods() { + ClassDB::bind_method("_shader_changed", &VisualShaderNodePortPreview::_shader_changed); +} + +VisualShaderNodePortPreview::VisualShaderNodePortPreview() { +} diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h new file mode 100644 index 0000000000..f86374ff6b --- /dev/null +++ b/editor/plugins/visual_shader_editor_plugin.h @@ -0,0 +1,187 @@ +#ifndef VISUAL_SHADER_EDITOR_PLUGIN_H +#define VISUAL_SHADER_EDITOR_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "editor/property_editor.h" +#include "scene/gui/button.h" +#include "scene/gui/graph_edit.h" +#include "scene/gui/popup.h" +#include "scene/gui/tree.h" +#include "scene/resources/visual_shader.h" + +class VisualShaderNodePlugin : public Reference { + + GDCLASS(VisualShaderNodePlugin, Reference) +protected: + static void _bind_methods(); + +public: + virtual Control *create_editor(const Ref<VisualShaderNode> &p_node); +}; + +class VisualShaderEditor : public VBoxContainer { + + GDCLASS(VisualShaderEditor, VBoxContainer); + + CustomPropertyEditor *property_editor; + int editing_node; + int editing_port; + + Ref<VisualShader> visual_shader; + GraphEdit *graph; + MenuButton *add_node; + + OptionButton *edit_type; + + PanelContainer *error_panel; + Label *error_label; + + UndoRedo *undo_redo; + + void _update_graph(); + + struct AddOption { + String name; + String category; + String type; + Ref<Script> script; + AddOption(const String &p_name = String(), const String &p_category = String(), const String &p_type = String()) { + name = p_name; + type = p_type; + category = p_category; + } + }; + + Vector<AddOption> add_options; + + void _draw_color_over_button(Object *obj, Color p_color); + + void _add_node(int p_idx); + void _update_options_menu(); + + static VisualShaderEditor *singleton; + + void _node_dragged(const Vector2 &p_from, const Vector2 &p_to, int p_node); + bool updating; + + void _connection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index); + void _disconnection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index); + + void _scroll_changed(const Vector2 &p_scroll); + void _node_selected(Object *p_node); + + void _delete_request(int); + + void _removed_from_graph(); + + void _node_changed(int p_id); + + void _edit_port_default_input(Object *p_button, int p_node, int p_port); + void _port_edited(); + + void _connection_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_position); + + void _line_edit_changed(const String &p_text, Object *line_edit, int p_node_id); + void _line_edit_focus_out(Object *line_edit, int p_node_id); + + void _duplicate_nodes(); + + Vector<Ref<VisualShaderNodePlugin> > plugins; + + void _mode_selected(int p_id); + + void _input_select_item(Ref<VisualShaderNodeInput> input, String name); + + void _preview_select_port(int p_node, int p_port); + void _input(const Ref<InputEvent> p_event); + +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + void add_plugin(const Ref<VisualShaderNodePlugin> &p_plugin); + void remove_plugin(const Ref<VisualShaderNodePlugin> &p_plugin); + + static VisualShaderEditor *get_singleton() { return singleton; } + + void add_custom_type(const String &p_name, const String &p_category, const Ref<Script> &p_script); + void remove_custom_type(const Ref<Script> &p_script); + + virtual Size2 get_minimum_size() const; + void edit(VisualShader *p_visual_shader); + VisualShaderEditor(); +}; + +class VisualShaderEditorPlugin : public EditorPlugin { + + GDCLASS(VisualShaderEditorPlugin, EditorPlugin); + + VisualShaderEditor *visual_shader_editor; + EditorNode *editor; + Button *button; + +public: + virtual String get_name() const { return "VisualShader"; } + bool has_main_screen() const { return false; } + virtual void edit(Object *p_object); + virtual bool handles(Object *p_object) const; + virtual void make_visible(bool p_visible); + + VisualShaderEditorPlugin(EditorNode *p_node); + ~VisualShaderEditorPlugin(); +}; + +class VisualShaderNodePluginDefault : public VisualShaderNodePlugin { + + GDCLASS(VisualShaderNodePluginDefault, VisualShaderNodePlugin) + +public: + virtual Control *create_editor(const Ref<VisualShaderNode> &p_node); +}; + +class EditorPropertyShaderMode : public EditorProperty { + GDCLASS(EditorPropertyShaderMode, EditorProperty) + OptionButton *options; + + void _option_selected(int p_which); + +protected: + static void _bind_methods(); + +public: + void setup(const Vector<String> &p_options); + virtual void update_property(); + void set_option_button_clip(bool p_enable); + EditorPropertyShaderMode(); +}; + +class EditorInspectorShaderModePlugin : public EditorInspectorPlugin { + GDCLASS(EditorInspectorShaderModePlugin, EditorInspectorPlugin) + +public: + virtual bool can_handle(Object *p_object); + virtual void parse_begin(Object *p_object); + virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage); + virtual void parse_end(); +}; + +class VisualShaderNodePortPreview : public Control { + GDCLASS(VisualShaderNodePortPreview, Control) + Ref<VisualShader> shader; + VisualShader::Type type; + int node; + int port; + void _shader_changed(); //must regen +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + virtual Size2 get_minimum_size() const; + void setup(const Ref<VisualShader> &p_shader, VisualShader::Type p_type, int p_node, int p_port); + VisualShaderNodePortPreview(); +}; + +#endif // VISUAL_SHADER_EDITOR_PLUGIN_H diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp index d867d1b137..8c7565a441 100644 --- a/editor/project_settings_editor.cpp +++ b/editor/project_settings_editor.cpp @@ -452,10 +452,10 @@ void ProjectSettingsEditor::_add_item(int p_item, Ref<InputEvent> p_exiting_even device_index->add_item(TTR("Middle Button")); device_index->add_item(TTR("Wheel Up Button")); device_index->add_item(TTR("Wheel Down Button")); - device_index->add_item(TTR("Button 6")); - device_index->add_item(TTR("Button 7")); - device_index->add_item(TTR("Button 8")); - device_index->add_item(TTR("Button 9")); + device_index->add_item(TTR("Wheel Left Button")); + device_index->add_item(TTR("Wheel Right Button")); + device_index->add_item(TTR("X Button 1")); + device_index->add_item(TTR("X Button 2")); device_input->popup_centered_minsize(Size2(350, 95) * EDSCALE); Ref<InputEventMouseButton> mb = p_exiting_event; diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp index 77ee65879b..2ffaa0ca12 100644 --- a/editor/scene_tree_dock.cpp +++ b/editor/scene_tree_dock.cpp @@ -551,6 +551,32 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { reparent_dialog->set_current(nodeset); } break; + case TOOL_MAKE_ROOT: { + + List<Node *> nodes = editor_selection->get_selected_node_list(); + ERR_FAIL_COND(nodes.size() != 1); + + Node *node = nodes.front()->get(); + Node *root = get_tree()->get_edited_scene_root(); + + if (node == root) + return; + + editor_data->get_undo_redo().create_action("Make node as Root"); + _node_replace_owner(root, node, node, MODE_DO); + editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node); + editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", node); + editor_data->get_undo_redo().add_do_method(node, "set_filename", root->get_filename()); + + editor_data->get_undo_redo().add_undo_method(node, "set_filename", String()); + editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", root); + editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node); + _node_replace_owner(root, node, root, MODE_UNDO); + editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); + editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree"); + editor_data->get_undo_redo().add_undo_reference(root); + editor_data->get_undo_redo().commit_action(); + } break; case TOOL_MULTI_EDIT: { Node *root = EditorNode::get_singleton()->get_edited_scene(); @@ -757,6 +783,26 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { } } } break; + case TOOL_CREATE_2D_SCENE: + case TOOL_CREATE_3D_SCENE: + case TOOL_CREATE_USER_INTERFACE: { + + Node *new_node; + switch (p_tool) { + case TOOL_CREATE_2D_SCENE: new_node = memnew(Node2D); break; + case TOOL_CREATE_3D_SCENE: new_node = memnew(Spatial); break; + case TOOL_CREATE_USER_INTERFACE: new_node = memnew(Control); break; + } + + editor_data->get_undo_redo().create_action("New Scene Root"); + editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", new_node); + editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); + editor_data->get_undo_redo().add_do_reference(new_node); + editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", (Object *)NULL); + editor_data->get_undo_redo().commit_action(); + + } break; + default: { if (p_tool >= EDIT_SUBRESOURCE_BASE) { @@ -803,6 +849,35 @@ void SceneTreeDock::_notification(int p_what) { EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed", this, "_selection_changed"); + create_root_dialog->add_child(memnew(Label(TTR("Create Root Node:")))); + + Button *button_2d = memnew(Button); + create_root_dialog->add_child(button_2d); + + button_2d->set_text(TTR("2D Scene")); + button_2d->set_icon(get_icon("Node2D", "EditorIcons")); + button_2d->connect("pressed", this, "_tool_selected", make_binds(TOOL_CREATE_2D_SCENE, false)); + + Button *button_3d = memnew(Button); + create_root_dialog->add_child(button_3d); + button_3d->set_text(TTR("3D Scene")); + button_3d->set_icon(get_icon("Spatial", "EditorIcons")); + button_3d->connect("pressed", this, "_tool_selected", make_binds(TOOL_CREATE_3D_SCENE, false)); + + Button *button_ui = memnew(Button); + create_root_dialog->add_child(button_ui); + button_ui->set_text(TTR("User Interface")); + button_ui->set_icon(get_icon("Control", "EditorIcons")); + button_ui->connect("pressed", this, "_tool_selected", make_binds(TOOL_CREATE_USER_INTERFACE, false)); + + Button *button_custom = memnew(Button); + create_root_dialog->add_child(button_custom); + button_custom->set_text(TTR("Custom Node")); + button_custom->set_icon(get_icon("Add", "EditorIcons")); + button_custom->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false)); + + create_root_dialog->add_spacer(); + } break; case NOTIFICATION_ENTER_TREE: { @@ -820,21 +895,49 @@ void SceneTreeDock::_notification(int p_what) { filter->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); } break; + case NOTIFICATION_PROCESS: { + + bool show_create_root = bool(EDITOR_GET("interface/editors/show_scene_tree_root_selection")) && get_tree()->get_edited_scene_root() == NULL; + + if (show_create_root != create_root_dialog->is_visible_in_tree()) { + if (show_create_root) { + create_root_dialog->show(); + scene_tree->hide(); + } else { + create_root_dialog->hide(); + scene_tree->show(); + } + } + + } break; } } -void SceneTreeDock::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root) { +void SceneTreeDock::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root, ReplaceOwnerMode p_mode) { if (p_base != p_node) { if (p_node->get_owner() == p_base) { UndoRedo *undo_redo = &editor_data->get_undo_redo(); - undo_redo->add_do_method(p_node, "set_owner", p_root); - undo_redo->add_undo_method(p_node, "set_owner", p_base); + switch (p_mode) { + case MODE_BIDI: { + undo_redo->add_do_method(p_node, "set_owner", p_root); + undo_redo->add_undo_method(p_node, "set_owner", p_base); + + } break; + case MODE_DO: { + undo_redo->add_do_method(p_node, "set_owner", p_root); + + } break; + case MODE_UNDO: { + undo_redo->add_undo_method(p_node, "set_owner", p_root); + + } break; + } } } for (int i = 0; i < p_node->get_child_count(); i++) { - _node_replace_owner(p_base, p_node->get_child(i), p_root); + _node_replace_owner(p_base, p_node->get_child(i), p_root, p_mode); } } @@ -1904,6 +2007,8 @@ void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT); if (selection.size() == 1) { + + menu->add_icon_shortcut(get_icon("NewRoot", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/make_root"), TOOL_MAKE_ROOT); menu->add_separator(); menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE); menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM); @@ -2090,6 +2195,7 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel ED_SHORTCUT("scene_tree/move_down", TTR("Move Down"), KEY_MASK_CMD | KEY_DOWN); ED_SHORTCUT("scene_tree/duplicate", TTR("Duplicate"), KEY_MASK_CMD | KEY_D); ED_SHORTCUT("scene_tree/reparent", TTR("Reparent")); + ED_SHORTCUT("scene_tree/make_root", TTR("Make Scene Root")); ED_SHORTCUT("scene_tree/merge_from_scene", TTR("Merge From Scene")); ED_SHORTCUT("scene_tree/save_branch_as_scene", TTR("Save Branch as Scene")); ED_SHORTCUT("scene_tree/copy_node_path", TTR("Copy Node Path"), KEY_MASK_CMD | KEY_C); @@ -2153,6 +2259,10 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel remote_tree = NULL; button_hb->hide(); + create_root_dialog = memnew(VBoxContainer); + vbc->add_child(create_root_dialog); + create_root_dialog->hide(); + scene_tree = memnew(SceneTreeEditor(false, true, true)); vbc->add_child(scene_tree); @@ -2227,4 +2337,7 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel add_child(clear_inherit_confirm); set_process_input(true); + set_process(true); + + EDITOR_DEF("interface/editors/show_scene_tree_root_selection", true); } diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h index 17deab25de..fd74611bde 100644 --- a/editor/scene_tree_dock.h +++ b/editor/scene_tree_dock.h @@ -68,6 +68,7 @@ class SceneTreeDock : public VBoxContainer { TOOL_MOVE_DOWN, TOOL_DUPLICATE, TOOL_REPARENT, + TOOL_MAKE_ROOT, TOOL_NEW_SCENE_FROM, TOOL_MERGE_FROM_SCENE, TOOL_MULTI_EDIT, @@ -80,7 +81,12 @@ class SceneTreeDock : public VBoxContainer { TOOL_SCENE_OPEN, TOOL_SCENE_CLEAR_INHERITANCE, TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM, - TOOL_SCENE_OPEN_INHERITED + TOOL_SCENE_OPEN_INHERITED, + + TOOL_CREATE_2D_SCENE, + TOOL_CREATE_3D_SCENE, + TOOL_CREATE_USER_INTERFACE, + }; enum { @@ -134,13 +140,22 @@ class SceneTreeDock : public VBoxContainer { Node *edited_scene; EditorNode *editor; + VBoxContainer *create_root_dialog; + void _add_children_to_popup(Object *p_obj, int p_depth); void _node_reparent(NodePath p_path, bool p_keep_global_xform); void _do_reparent(Node *p_new_parent, int p_position_in_parent, Vector<Node *> p_nodes, bool p_keep_global_xform); void _set_owners(Node *p_owner, const Array &p_nodes); - void _node_replace_owner(Node *p_base, Node *p_node, Node *p_root); + + enum ReplaceOwnerMode { + MODE_BIDI, + MODE_DO, + MODE_UNDO + }; + + void _node_replace_owner(Node *p_base, Node *p_node, Node *p_root, ReplaceOwnerMode p_mode = MODE_BIDI); void _load_request(const String &p_path); void _script_open_request(const Ref<Script> &p_script); diff --git a/editor/spatial_editor_gizmos.cpp b/editor/spatial_editor_gizmos.cpp index 17f3b4886e..3b0ac8864a 100644 --- a/editor/spatial_editor_gizmos.cpp +++ b/editor/spatial_editor_gizmos.cpp @@ -36,6 +36,7 @@ #include "scene/resources/box_shape.h" #include "scene/resources/capsule_shape.h" #include "scene/resources/convex_polygon_shape.h" +#include "scene/resources/cylinder_shape.h" #include "scene/resources/plane_shape.h" #include "scene/resources/primitive_meshes.h" #include "scene/resources/ray_shape.h" @@ -1934,6 +1935,11 @@ String CollisionShapeSpatialGizmo::get_handle_name(int p_idx) const { return p_idx == 0 ? "Radius" : "Height"; } + if (Object::cast_to<CylinderShape>(*s)) { + + return p_idx == 0 ? "Radius" : "Height"; + } + if (Object::cast_to<RayShape>(*s)) { return "Length"; @@ -1965,6 +1971,12 @@ Variant CollisionShapeSpatialGizmo::get_handle_value(int p_idx) const { return p_idx == 0 ? cs->get_radius() : cs->get_height(); } + if (Object::cast_to<CylinderShape>(*s)) { + + Ref<CylinderShape> cs = s; + return p_idx == 0 ? cs->get_radius() : cs->get_height(); + } + if (Object::cast_to<RayShape>(*s)) { Ref<RayShape> cs = s; @@ -2045,6 +2057,24 @@ void CollisionShapeSpatialGizmo::set_handle(int p_idx, Camera *p_camera, const P else if (p_idx == 1) cs->set_height(d * 2.0); } + + if (Object::cast_to<CylinderShape>(*s)) { + + Vector3 axis; + axis[p_idx == 0 ? 0 : 1] = 1.0; + Ref<CylinderShape> cs = s; + Vector3 ra, rb; + Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); + float d = axis.dot(ra); + + if (d < 0.001) + d = 0.001; + + if (p_idx == 0) + cs->set_radius(d); + else if (p_idx == 1) + cs->set_height(d * 2.0); + } } void CollisionShapeSpatialGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) { Ref<Shape> s = cs->get_shape(); @@ -2106,6 +2136,31 @@ void CollisionShapeSpatialGizmo::commit_handle(int p_idx, const Variant &p_resto ur->commit_action(); } + if (Object::cast_to<CylinderShape>(*s)) { + + Ref<CylinderShape> ss = s; + if (p_cancel) { + if (p_idx == 0) + ss->set_radius(p_restore); + else + ss->set_height(p_restore); + return; + } + + UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo(); + if (p_idx == 0) { + ur->create_action(TTR("Change Cylinder Shape Radius")); + ur->add_do_method(ss.ptr(), "set_radius", ss->get_radius()); + ur->add_undo_method(ss.ptr(), "set_radius", p_restore); + } else { + ur->create_action(TTR("Change Cylinder Shape Height")); + ur->add_do_method(ss.ptr(), "set_height", ss->get_height()); + ur->add_undo_method(ss.ptr(), "set_height", p_restore); + } + + ur->commit_action(); + } + if (Object::cast_to<RayShape>(*s)) { Ref<RayShape> ss = s; @@ -2282,6 +2337,67 @@ void CollisionShapeSpatialGizmo::redraw() { add_handles(handles); } + if (Object::cast_to<CylinderShape>(*s)) { + + Ref<CylinderShape> cs = s; + float radius = cs->get_radius(); + float height = cs->get_height(); + + Vector<Vector3> points; + + Vector3 d(0, height * 0.5, 0); + for (int i = 0; i < 360; i++) { + + float ra = Math::deg2rad((float)i); + float rb = Math::deg2rad((float)i + 1); + Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius; + Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius; + + points.push_back(Vector3(a.x, 0, a.y) + d); + points.push_back(Vector3(b.x, 0, b.y) + d); + + points.push_back(Vector3(a.x, 0, a.y) - d); + points.push_back(Vector3(b.x, 0, b.y) - d); + + if (i % 90 == 0) { + + points.push_back(Vector3(a.x, 0, a.y) + d); + points.push_back(Vector3(a.x, 0, a.y) - d); + } + } + + add_lines(points, material); + + Vector<Vector3> collision_segments; + + for (int i = 0; i < 64; i++) { + + float ra = i * Math_PI * 2.0 / 64.0; + float rb = (i + 1) * Math_PI * 2.0 / 64.0; + Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius; + Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius; + + collision_segments.push_back(Vector3(a.x, 0, a.y) + d); + collision_segments.push_back(Vector3(b.x, 0, b.y) + d); + + collision_segments.push_back(Vector3(a.x, 0, a.y) - d); + collision_segments.push_back(Vector3(b.x, 0, b.y) - d); + + if (i % 16 == 0) { + + collision_segments.push_back(Vector3(a.x, 0, a.y) + d); + collision_segments.push_back(Vector3(a.x, 0, a.y) - d); + } + } + + add_collision_segments(collision_segments); + + Vector<Vector3> handles; + handles.push_back(Vector3(cs->get_radius(), 0, 0)); + handles.push_back(Vector3(0, cs->get_height() * 0.5, 0)); + add_handles(handles); + } + if (Object::cast_to<PlaneShape>(*s)) { Ref<PlaneShape> ps = s; diff --git a/main/tests/test_shader_lang.cpp b/main/tests/test_shader_lang.cpp index 63032597ed..7103b436e1 100644 --- a/main/tests/test_shader_lang.cpp +++ b/main/tests/test_shader_lang.cpp @@ -321,8 +321,8 @@ MainLoop *test() { dt["fragment"].built_ins["ALBEDO"] = SL::TYPE_VEC3; dt["fragment"].can_discard = true; - Set<String> rm; - rm.insert("popo"); + Vector<StringName> rm; + rm.push_back("popo"); Set<String> types; types.insert("spatial"); diff --git a/misc/dist/ios_xcode/godot_ios/godot_ios-Info.plist b/misc/dist/ios_xcode/godot_ios/godot_ios-Info.plist index 70932c1943..6907ae4a9d 100644 --- a/misc/dist/ios_xcode/godot_ios/godot_ios-Info.plist +++ b/misc/dist/ios_xcode/godot_ios/godot_ios-Info.plist @@ -41,11 +41,15 @@ <array> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationPortraitUpsideDown</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationPortraitUpsideDown</string> </array> $additional_plist_content </dict> diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index 769119a0dc..919731b52b 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -53,7 +53,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, err = FAILED; } - if (bits_per_pixel != 24 || bits_per_pixel != 32) { + if (!(bits_per_pixel == 24 || bits_per_pixel == 32)) { err = FAILED; } diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index 6246a295ec..54431f93f1 100644 --- a/modules/bullet/bullet_physics_server.cpp +++ b/modules/bullet/bullet_physics_server.cpp @@ -113,6 +113,10 @@ RID BulletPhysicsServer::shape_create(ShapeType p_shape) { shape = bulletnew(CapsuleShapeBullet); } break; + case SHAPE_CYLINDER: { + + shape = bulletnew(CylinderShapeBullet); + } break; case SHAPE_CONVEX_POLYGON: { shape = bulletnew(ConvexPolygonShapeBullet); diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp index 2494063c22..2fc96a77b5 100644 --- a/modules/bullet/rigid_body_bullet.cpp +++ b/modules/bullet/rigid_body_bullet.cpp @@ -226,6 +226,7 @@ void RigidBodyBullet::KinematicUtilities::copyAllOwnerShapes() { case PhysicsServer::SHAPE_SPHERE: case PhysicsServer::SHAPE_BOX: case PhysicsServer::SHAPE_CAPSULE: + case PhysicsServer::SHAPE_CYLINDER: case PhysicsServer::SHAPE_CONVEX_POLYGON: case PhysicsServer::SHAPE_RAY: { shapes[i].shape = static_cast<btConvexShape *>(shape_wrapper->shape->create_bt_shape(owner_scale * shape_wrapper->scale, safe_margin)); diff --git a/modules/bullet/shape_bullet.cpp b/modules/bullet/shape_bullet.cpp index 76d9614465..92e7c2df98 100644 --- a/modules/bullet/shape_bullet.cpp +++ b/modules/bullet/shape_bullet.cpp @@ -113,6 +113,10 @@ btCapsuleShapeZ *ShapeBullet::create_shape_capsule(btScalar radius, btScalar hei return bulletnew(btCapsuleShapeZ(radius, height)); } +btCylinderShape *ShapeBullet::create_shape_cylinder(btScalar radius, btScalar height) { + return bulletnew(btCylinderShape(btVector3(radius, height / 2.0, radius))); +} + btConvexPointCloudShape *ShapeBullet::create_shape_convex(btAlignedObjectArray<btVector3> &p_vertices, const btVector3 &p_local_scaling) { return bulletnew(btConvexPointCloudShape(&p_vertices[0], p_vertices.size(), p_local_scaling)); } @@ -254,6 +258,39 @@ btCollisionShape *CapsuleShapeBullet::create_bt_shape(const btVector3 &p_implici return prepare(ShapeBullet::create_shape_capsule(radius * p_implicit_scale[0] + p_margin, height * p_implicit_scale[1] + p_margin)); } +/* Cylinder */ + +CylinderShapeBullet::CylinderShapeBullet() : + ShapeBullet() {} + +void CylinderShapeBullet::set_data(const Variant &p_data) { + Dictionary d = p_data; + ERR_FAIL_COND(!d.has("radius")); + ERR_FAIL_COND(!d.has("height")); + setup(d["height"], d["radius"]); +} + +Variant CylinderShapeBullet::get_data() const { + Dictionary d; + d["radius"] = radius; + d["height"] = height; + return d; +} + +PhysicsServer::ShapeType CylinderShapeBullet::get_type() const { + return PhysicsServer::SHAPE_CYLINDER; +} + +void CylinderShapeBullet::setup(real_t p_height, real_t p_radius) { + radius = p_radius; + height = p_height; + notifyShapeChanged(); +} + +btCollisionShape *CylinderShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_margin) { + return prepare(ShapeBullet::create_shape_cylinder(radius * p_implicit_scale[0] + p_margin, height * p_implicit_scale[1] + p_margin)); +} + /* Convex polygon */ ConvexPolygonShapeBullet::ConvexPolygonShapeBullet() : diff --git a/modules/bullet/shape_bullet.h b/modules/bullet/shape_bullet.h index abeea0f9ce..16a5ac1fc6 100644 --- a/modules/bullet/shape_bullet.h +++ b/modules/bullet/shape_bullet.h @@ -82,6 +82,7 @@ public: static class btSphereShape *create_shape_sphere(btScalar radius); static class btBoxShape *create_shape_box(const btVector3 &boxHalfExtents); static class btCapsuleShapeZ *create_shape_capsule(btScalar radius, btScalar height); + static class btCylinderShape *create_shape_cylinder(btScalar radius, btScalar height); /// IMPORTANT: Remember to delete the shape interface by calling: delete my_shape->getMeshInterface(); static class btConvexPointCloudShape *create_shape_convex(btAlignedObjectArray<btVector3> &p_vertices, const btVector3 &p_local_scaling = btVector3(1, 1, 1)); static class btScaledBvhTriangleMeshShape *create_shape_concave(btBvhTriangleMeshShape *p_mesh_shape, const btVector3 &p_local_scaling = btVector3(1, 1, 1)); @@ -158,6 +159,25 @@ private: void setup(real_t p_height, real_t p_radius); }; +class CylinderShapeBullet : public ShapeBullet { + + real_t height; + real_t radius; + +public: + CylinderShapeBullet(); + + _FORCE_INLINE_ real_t get_height() { return height; } + _FORCE_INLINE_ real_t get_radius() { return radius; } + virtual void set_data(const Variant &p_data); + virtual Variant get_data() const; + virtual PhysicsServer::ShapeType get_type() const; + virtual btCollisionShape *create_bt_shape(const btVector3 &p_implicit_scale, real_t p_margin = 0); + +private: + void setup(real_t p_height, real_t p_radius); +}; + class ConvexPolygonShapeBullet : public ShapeBullet { public: diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index f23e7854a5..b3ebd4fe4b 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -1739,6 +1739,7 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { "assert", "breakpoint", "class", + "class_name", "extends", "is", "func", @@ -1788,6 +1789,50 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { } } +bool GDScriptLanguage::handles_global_class_type(const String &p_type) const { + + return p_type == "GDScript"; +} + +String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type) const { + + PoolVector<uint8_t> sourcef; + Error err; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err) { + return String(); + } + + int len = f->get_len(); + sourcef.resize(len + 1); + PoolVector<uint8_t>::Write w = sourcef.write(); + int r = f->get_buffer(w.ptr(), len); + f->close(); + memdelete(f); + ERR_FAIL_COND_V(r != len, String()); + w[len] = 0; + + String s; + if (s.parse_utf8((const char *)w.ptr())) { + return String(); + } + + GDScriptParser parser; + + parser.parse(s, p_path.get_base_dir(), true, p_path); + + if (parser.get_parse_tree() && parser.get_parse_tree()->type == GDScriptParser::Node::TYPE_CLASS) { + + const GDScriptParser::ClassNode *c = static_cast<const GDScriptParser::ClassNode *>(parser.get_parse_tree()); + if (r_base_type && c->extends_used && c->extends_class.size() == 1) { + *r_base_type = c->extends_class[0]; //todo, should work much better + } + return c->name; + } + + return String(); +} + GDScriptLanguage::GDScriptLanguage() { calls = 0; diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index a35b0a10d5..d1c57a0330 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -439,6 +439,11 @@ public: virtual void get_recognized_extensions(List<String> *p_extensions) const; + /* GLOBAL CLASSES */ + + virtual bool handles_global_class_type(const String &p_type) const; + virtual String get_global_class_name(const String &p_path, String *r_base_type = NULL) const; + GDScriptLanguage(); ~GDScriptLanguage(); }; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 85c36647a1..7ce19859ca 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -278,6 +278,41 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: return idx | (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root) } + /* TRY GLOBAL CLASSES */ + + if (ScriptServer::is_global_class(identifier)) { + + const GDScriptParser::ClassNode *class_node = codegen.class_node; + while (class_node->owner) { + class_node = class_node->owner; + } + + if (class_node->name == identifier) { + _set_error("Using own name in class file is not allowed (creates a cyclic reference)", p_expression); + return -1; + } + + RES res = ResourceLoader::load(ScriptServer::get_global_class_path(identifier)); + if (res.is_null()) { + _set_error("Can't load global class " + String(identifier) + ", cyclic reference?", p_expression); + return -1; + } + + Variant key = res; + int idx; + + if (!codegen.constant_map.has(key)) { + + idx = codegen.constant_map.size(); + codegen.constant_map[key] = idx; + + } else { + idx = codegen.constant_map[key]; + } + + return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //make it a local constant (faster access) + } + #ifdef TOOLS_ENABLED if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) { diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 9650563ee6..d62112d3f1 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -3112,6 +3112,28 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } } break; + case GDScriptTokenizer::TK_PR_CLASS_NAME: { + + if (p_class->owner) { + _set_error("'class_name' is only valid for the main class namespace."); + return; + } + if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) { + + _set_error("'class_name' syntax: 'class_name <UniqueName>'"); + return; + } + + p_class->name = tokenizer->get_token_identifier(1); + + if (self_path != String() && ScriptServer::is_global_class(p_class->name) && ScriptServer::get_global_class_path(p_class->name) != self_path) { + _set_error("Unique global class '" + p_class->name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); + return; + } + + tokenizer->advance(2); + + } break; case GDScriptTokenizer::TK_PR_TOOL: { if (p_class->tool) { @@ -3138,6 +3160,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { name = tokenizer->get_token_identifier(1); tokenizer->advance(2); + if (ScriptServer::is_global_class(name)) { + _set_error("Can't override name of unique global class '" + name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); + return; + } + ClassNode *newclass = alloc_node<ClassNode>(); newclass->initializer = alloc_node<BlockNode>(); newclass->initializer->parent_class = newclass; diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index 3c8e1ddbe4..9517b95f3f 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -91,6 +91,7 @@ const char *GDScriptTokenizer::token_names[TK_MAX] = { "match", "func", "class", + "class_name", "extends", "is", "onready", @@ -187,6 +188,7 @@ static const _kws _keyword_list[] = { //func { GDScriptTokenizer::TK_PR_FUNCTION, "func" }, { GDScriptTokenizer::TK_PR_CLASS, "class" }, + { GDScriptTokenizer::TK_PR_CLASS_NAME, "class_name" }, { GDScriptTokenizer::TK_PR_EXTENDS, "extends" }, { GDScriptTokenizer::TK_PR_IS, "is" }, { GDScriptTokenizer::TK_PR_ONREADY, "onready" }, @@ -1137,7 +1139,7 @@ void GDScriptTokenizerText::advance(int p_amount) { ////////////////////////////////////////////////////////////////////////////////////////////////////// -#define BYTECODE_VERSION 12 +#define BYTECODE_VERSION 13 Error GDScriptTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) { diff --git a/modules/gdscript/gdscript_tokenizer.h b/modules/gdscript/gdscript_tokenizer.h index c4f1f9fd94..c1f611fe73 100644 --- a/modules/gdscript/gdscript_tokenizer.h +++ b/modules/gdscript/gdscript_tokenizer.h @@ -96,6 +96,7 @@ public: TK_CF_MATCH, TK_PR_FUNCTION, TK_PR_CLASS, + TK_PR_CLASS_NAME, TK_PR_EXTENDS, TK_PR_IS, TK_PR_ONREADY, diff --git a/modules/mbedtls/SCsub b/modules/mbedtls/SCsub index 38198c9105..40540a857f 100755 --- a/modules/mbedtls/SCsub +++ b/modules/mbedtls/SCsub @@ -11,6 +11,7 @@ if env['builtin_mbedtls']: "aes.c", "aesni.c", "arc4.c", + "aria.c", "asn1parse.c", "asn1write.c", "base64.c", @@ -55,6 +56,7 @@ if env['builtin_mbedtls']: "pk_wrap.c", "pkwrite.c", "platform.c", + "platform_util.c", "ripemd160.c", "rsa.c", "rsa_internal.c", diff --git a/modules/mono/SCsub b/modules/mono/SCsub index 89a3caf4e4..c69a3c9ba6 100644 --- a/modules/mono/SCsub +++ b/modules/mono/SCsub @@ -97,7 +97,7 @@ def find_msbuild_unix(filename): hint_dirs = ['/opt/novell/mono/bin'] if sys.platform == 'darwin': - hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin'] + hint_dirs + hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin', '/usr/local/var/homebrew/linked/mono/bin'] + hint_dirs for hint_dir in hint_dirs: hint_path = os.path.join(hint_dir, filename) diff --git a/modules/mono/editor/godotsharp_builds.cpp b/modules/mono/editor/godotsharp_builds.cpp index 156a01ff5a..b3b259e851 100644 --- a/modules/mono/editor/godotsharp_builds.cpp +++ b/modules/mono/editor/godotsharp_builds.cpp @@ -64,6 +64,7 @@ String _find_build_engine_on_unix(const String &p_name) { const char *locations[] = { #ifdef OSX_ENABLED "/Library/Frameworks/Mono.framework/Versions/Current/bin/", + "/usr/local/var/homebrew/linked/mono/bin/", #endif "/opt/novell/mono/bin/" }; diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp index 7391bed699..d4fa88afa7 100644 --- a/modules/tga/image_loader_tga.cpp +++ b/modules/tga/image_loader_tga.cpp @@ -250,8 +250,9 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force if (tga_header.image_width <= 0 || tga_header.image_height <= 0) err = FAILED; - if (tga_header.pixel_depth != 8 && tga_header.pixel_depth != 24 && tga_header.pixel_depth != 32) + if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) { err = FAILED; + } if (err == OK) { f->seek(f->get_position() + tga_header.id_length); diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index 0618064ea6..873cc293c9 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -3389,6 +3389,7 @@ VisualScriptEditor::VisualScriptEditor() { graph = memnew(GraphEdit); add_child(graph); + graph->set_v_size_flags(Control::SIZE_EXPAND_FILL); graph->set_anchors_and_margins_preset(Control::PRESET_WIDE); graph->connect("node_selected", this, "_node_selected"); graph->connect("_begin_node_move", this, "_begin_node_move"); diff --git a/platform/android/AndroidManifest.xml.template b/platform/android/AndroidManifest.xml.template index 21dfb87e1c..81f4c15849 100644 --- a/platform/android/AndroidManifest.xml.template +++ b/platform/android/AndroidManifest.xml.template @@ -35,171 +35,6 @@ $$ADD_APPLICATION_CHUNKS$$ <uses-feature android:glEsVersion="0x00020000" android:required="true" /> $$ADD_PERMISSION_CHUNKS$$ -<uses-permission android:name="godot.ACCESS_CHECKIN_PROPERTIES"/> -<uses-permission android:name="godot.ACCESS_COARSE_LOCATION"/> -<uses-permission android:name="godot.ACCESS_FINE_LOCATION"/> -<uses-permission android:name="godot.ACCESS_LOCATION_EXTRA_COMMANDS"/> -<uses-permission android:name="godot.ACCESS_MOCK_LOCATION"/> -<uses-permission android:name="godot.ACCESS_NETWORK_STATE"/> -<uses-permission android:name="godot.ACCESS_SURFACE_FLINGER"/> -<uses-permission android:name="godot.ACCESS_WIFI_STATE"/> -<uses-permission android:name="godot.ACCOUNT_MANAGER"/> -<uses-permission android:name="godot.ADD_VOICEMAIL"/> -<uses-permission android:name="godot.AUTHENTICATE_ACCOUNTS"/> -<uses-permission android:name="godot.BATTERY_STATS"/> -<uses-permission android:name="godot.BIND_ACCESSIBILITY_SERVICE"/> -<uses-permission android:name="godot.BIND_APPWIDGET"/> -<uses-permission android:name="godot.BIND_DEVICE_ADMIN"/> -<uses-permission android:name="godot.BIND_INPUT_METHOD"/> -<uses-permission android:name="godot.BIND_NFC_SERVICE"/> -<uses-permission android:name="godot.BIND_NOTIFICATION_LISTENER_SERVICE"/> -<uses-permission android:name="godot.BIND_PRINT_SERVICE"/> -<uses-permission android:name="godot.BIND_REMOTEVIEWS"/> -<uses-permission android:name="godot.BIND_TEXT_SERVICE"/> -<uses-permission android:name="godot.BIND_VPN_SERVICE"/> -<uses-permission android:name="godot.BIND_WALLPAPER"/> -<uses-permission android:name="godot.BLUETOOTH"/> -<uses-permission android:name="godot.BLUETOOTH_ADMIN"/> -<uses-permission android:name="godot.BLUETOOTH_PRIVILEGED"/> -<uses-permission android:name="godot.BRICK"/> -<uses-permission android:name="godot.BROADCAST_PACKAGE_REMOVED"/> -<uses-permission android:name="godot.BROADCAST_SMS"/> -<uses-permission android:name="godot.BROADCAST_STICKY"/> -<uses-permission android:name="godot.BROADCAST_WAP_PUSH"/> -<uses-permission android:name="godot.CALL_PHONE"/> -<uses-permission android:name="godot.CALL_PRIVILEGED"/> -<uses-permission android:name="godot.CAMERA"/> -<uses-permission android:name="godot.CAPTURE_AUDIO_OUTPUT"/> -<uses-permission android:name="godot.CAPTURE_SECURE_VIDEO_OUTPUT"/> -<uses-permission android:name="godot.CAPTURE_VIDEO_OUTPUT"/> -<uses-permission android:name="godot.CHANGE_COMPONENT_ENABLED_STATE"/> -<uses-permission android:name="godot.CHANGE_CONFIGURATION"/> -<uses-permission android:name="godot.CHANGE_NETWORK_STATE"/> -<uses-permission android:name="godot.CHANGE_WIFI_MULTICAST_STATE"/> -<uses-permission android:name="godot.CHANGE_WIFI_STATE"/> -<uses-permission android:name="godot.CLEAR_APP_CACHE"/> -<uses-permission android:name="godot.CLEAR_APP_USER_DATA"/> -<uses-permission android:name="godot.CONTROL_LOCATION_UPDATES"/> -<uses-permission android:name="godot.DELETE_CACHE_FILES"/> -<uses-permission android:name="godot.DELETE_PACKAGES"/> -<uses-permission android:name="godot.DEVICE_POWER"/> -<uses-permission android:name="godot.DIAGNOSTIC"/> -<uses-permission android:name="godot.DISABLE_KEYGUARD"/> -<uses-permission android:name="godot.DUMP"/> -<uses-permission android:name="godot.EXPAND_STATUS_BAR"/> -<uses-permission android:name="godot.FACTORY_TEST"/> -<uses-permission android:name="godot.FLASHLIGHT"/> -<uses-permission android:name="godot.FORCE_BACK"/> -<uses-permission android:name="godot.GET_ACCOUNTS"/> -<uses-permission android:name="godot.GET_PACKAGE_SIZE"/> -<uses-permission android:name="godot.GET_TASKS"/> -<uses-permission android:name="godot.GET_TOP_ACTIVITY_INFO"/> -<uses-permission android:name="godot.GLOBAL_SEARCH"/> -<uses-permission android:name="godot.HARDWARE_TEST"/> -<uses-permission android:name="godot.INJECT_EVENTS"/> -<uses-permission android:name="godot.INSTALL_LOCATION_PROVIDER"/> -<uses-permission android:name="godot.INSTALL_PACKAGES"/> -<uses-permission android:name="godot.INSTALL_SHORTCUT"/> -<uses-permission android:name="godot.INTERNAL_SYSTEM_WINDOW"/> -<uses-permission android:name="godot.INTERNET"/> -<uses-permission android:name="godot.KILL_BACKGROUND_PROCESSES"/> -<uses-permission android:name="godot.LOCATION_HARDWARE"/> -<uses-permission android:name="godot.MANAGE_ACCOUNTS"/> -<uses-permission android:name="godot.MANAGE_APP_TOKENS"/> -<uses-permission android:name="godot.MANAGE_DOCUMENTS"/> -<uses-permission android:name="godot.MASTER_CLEAR"/> -<uses-permission android:name="godot.MEDIA_CONTENT_CONTROL"/> -<uses-permission android:name="godot.MODIFY_AUDIO_SETTINGS"/> -<uses-permission android:name="godot.MODIFY_PHONE_STATE"/> -<uses-permission android:name="godot.MOUNT_FORMAT_FILESYSTEMS"/> -<uses-permission android:name="godot.MOUNT_UNMOUNT_FILESYSTEMS"/> -<uses-permission android:name="godot.NFC"/> -<uses-permission android:name="godot.PERSISTENT_ACTIVITY"/> -<uses-permission android:name="godot.PROCESS_OUTGOING_CALLS"/> -<uses-permission android:name="godot.READ_CALENDAR"/> -<uses-permission android:name="godot.READ_CALL_LOG"/> -<uses-permission android:name="godot.READ_CONTACTS"/> -<uses-permission android:name="godot.READ_EXTERNAL_STORAGE"/> -<uses-permission android:name="godot.READ_FRAME_BUFFER"/> -<uses-permission android:name="godot.READ_HISTORY_BOOKMARKS"/> -<uses-permission android:name="godot.READ_INPUT_STATE"/> -<uses-permission android:name="godot.READ_LOGS"/> -<uses-permission android:name="godot.READ_PHONE_STATE"/> -<uses-permission android:name="godot.READ_PROFILE"/> -<uses-permission android:name="godot.READ_SMS"/> -<uses-permission android:name="godot.READ_SOCIAL_STREAM"/> -<uses-permission android:name="godot.READ_SYNC_SETTINGS"/> -<uses-permission android:name="godot.READ_SYNC_STATS"/> -<uses-permission android:name="godot.READ_USER_DICTIONARY"/> -<uses-permission android:name="godot.REBOOT"/> -<uses-permission android:name="godot.RECEIVE_BOOT_COMPLETED"/> -<uses-permission android:name="godot.RECEIVE_MMS"/> -<uses-permission android:name="godot.RECEIVE_SMS"/> -<uses-permission android:name="godot.RECEIVE_WAP_PUSH"/> -<uses-permission android:name="godot.RECORD_AUDIO"/> -<uses-permission android:name="godot.REORDER_TASKS"/> -<uses-permission android:name="godot.RESTART_PACKAGES"/> -<uses-permission android:name="godot.SEND_RESPOND_VIA_MESSAGE"/> -<uses-permission android:name="godot.SEND_SMS"/> -<uses-permission android:name="godot.SET_ACTIVITY_WATCHER"/> -<uses-permission android:name="godot.SET_ALARM"/> -<uses-permission android:name="godot.SET_ALWAYS_FINISH"/> -<uses-permission android:name="godot.SET_ANIMATION_SCALE"/> -<uses-permission android:name="godot.SET_DEBUG_APP"/> -<uses-permission android:name="godot.SET_ORIENTATION"/> -<uses-permission android:name="godot.SET_POINTER_SPEED"/> -<uses-permission android:name="godot.SET_PREFERRED_APPLICATIONS"/> -<uses-permission android:name="godot.SET_PROCESS_LIMIT"/> -<uses-permission android:name="godot.SET_TIME"/> -<uses-permission android:name="godot.SET_TIME_ZONE"/> -<uses-permission android:name="godot.SET_WALLPAPER"/> -<uses-permission android:name="godot.SET_WALLPAPER_HINTS"/> -<uses-permission android:name="godot.SIGNAL_PERSISTENT_PROCESSES"/> -<uses-permission android:name="godot.STATUS_BAR"/> -<uses-permission android:name="godot.SUBSCRIBED_FEEDS_READ"/> -<uses-permission android:name="godot.SUBSCRIBED_FEEDS_WRITE"/> -<uses-permission android:name="godot.SYSTEM_ALERT_WINDOW"/> -<uses-permission android:name="godot.TRANSMIT_IR"/> -<uses-permission android:name="godot.UNINSTALL_SHORTCUT"/> -<uses-permission android:name="godot.UPDATE_DEVICE_STATS"/> -<uses-permission android:name="godot.USE_CREDENTIALS"/> -<uses-permission android:name="godot.USE_SIP"/> -<uses-permission android:name="godot.VIBRATE"/> -<uses-permission android:name="godot.WAKE_LOCK"/> -<uses-permission android:name="godot.WRITE_APN_SETTINGS"/> -<uses-permission android:name="godot.WRITE_CALENDAR"/> -<uses-permission android:name="godot.WRITE_CALL_LOG"/> -<uses-permission android:name="godot.WRITE_CONTACTS"/> -<uses-permission android:name="godot.WRITE_EXTERNAL_STORAGE"/> -<uses-permission android:name="godot.WRITE_GSERVICES"/> -<uses-permission android:name="godot.WRITE_HISTORY_BOOKMARKS"/> -<uses-permission android:name="godot.WRITE_PROFILE"/> -<uses-permission android:name="godot.WRITE_SECURE_SETTINGS"/> -<uses-permission android:name="godot.WRITE_SETTINGS"/> -<uses-permission android:name="godot.WRITE_SMS"/> -<uses-permission android:name="godot.WRITE_SOCIAL_STREAM"/> -<uses-permission android:name="godot.WRITE_SYNC_SETTINGS"/> -<uses-permission android:name="godot.WRITE_USER_DICTIONARY"/> -<uses-permission android:name="godot.custom.0"/> -<uses-permission android:name="godot.custom.1"/> -<uses-permission android:name="godot.custom.2"/> -<uses-permission android:name="godot.custom.3"/> -<uses-permission android:name="godot.custom.4"/> -<uses-permission android:name="godot.custom.5"/> -<uses-permission android:name="godot.custom.6"/> -<uses-permission android:name="godot.custom.7"/> -<uses-permission android:name="godot.custom.8"/> -<uses-permission android:name="godot.custom.9"/> -<uses-permission android:name="godot.custom.10"/> -<uses-permission android:name="godot.custom.11"/> -<uses-permission android:name="godot.custom.12"/> -<uses-permission android:name="godot.custom.13"/> -<uses-permission android:name="godot.custom.14"/> -<uses-permission android:name="godot.custom.15"/> -<uses-permission android:name="godot.custom.16"/> -<uses-permission android:name="godot.custom.17"/> -<uses-permission android:name="godot.custom.18"/> -<uses-permission android:name="godot.custom.19"/> <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="27"/> diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp index 9e6377f4fe..c3ff157f99 100644 --- a/platform/android/export/export.cpp +++ b/platform/android/export/export.cpp @@ -570,7 +570,7 @@ class EditorExportAndroid : public EditorExportPlatform { // const int CHUNK_RESOURCEIDS = 0x00080180; const int CHUNK_STRINGS = 0x001C0001; // const int CHUNK_XML_END_NAMESPACE = 0x00100101; - // const int CHUNK_XML_END_TAG = 0x00100103; + const int CHUNK_XML_END_TAG = 0x00100103; // const int CHUNK_XML_START_NAMESPACE = 0x00100100; const int CHUNK_XML_START_TAG = 0x00100102; // const int CHUNK_XML_TEXT = 0x00100104; @@ -601,24 +601,28 @@ class EditorExportAndroid : public EditorExportPlatform { bool screen_support_large = p_preset->get("screen/support_large"); bool screen_support_xlarge = p_preset->get("screen/support_xlarge"); - String user_perms[MAX_USER_PERMISSIONS]; - - for (int i = 0; i < MAX_USER_PERMISSIONS; i++) { - - user_perms[i] = p_preset->get("user_permissions/" + itos(i)); - } - - Set<String> perms; + Vector<String> perms; const char **aperms = android_perms; while (*aperms) { bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower()); if (enabled) - perms.insert(String(*aperms)); + perms.push_back("android.permission." + String(*aperms)); aperms++; } + for (int i = 0; i < MAX_USER_PERMISSIONS; i++) { + String user_perm = p_preset->get("user_permissions/" + itos(i)); + if (user_perm.strip_edges() != "" && user_perm.strip_edges() != "False") + perms.push_back(user_perm.strip_edges()); + } + + if (p_give_internet) { + if (perms.find("android.permission.INTERNET") == -1) + perms.push_back("android.permission.INTERNET"); + } + while (ofs < (uint32_t)p_manifest.size()) { uint32_t chunk = decode_uint32(&p_manifest[ofs]); @@ -741,27 +745,6 @@ class EditorExportAndroid : public EditorExportPlatform { print_line("version number: " + itos(decode_uint32(&p_manifest[iofs + 16]))); } - if (tname == "uses-permission" && /*nspace=="android" &&*/ attrname == "name") { - - if (value.begins_with("godot.custom")) { - - int which = value.get_slice(".", 2).to_int(); - if (which >= 0 && which < MAX_USER_PERMISSIONS && user_perms[which].strip_edges() != "") { - - string_table[attr_value] = user_perms[which].strip_edges(); - } - - } else if (value.begins_with("godot.")) { - String perm = value.get_slice(".", 1); - - if (perms.has(perm) || (p_give_internet && perm == "INTERNET")) { - - print_line("PERM: " + perm); - string_table[attr_value] = "android.permission." + perm; - } - } - } - if (tname == "supports-screens") { if (attrname == "smallScreens") { @@ -786,6 +769,91 @@ class EditorExportAndroid : public EditorExportPlatform { } } break; + case CHUNK_XML_END_TAG: { + int iofs = ofs + 8; + uint32_t name = decode_uint32(&p_manifest[iofs + 12]); + String tname = string_table[name]; + + if (tname == "manifest") { + print_line("Found manifest end"); + + // save manifest ending so we can restore it + Vector<uint8_t> manifest_end; + uint32_t manifest_cur_size = p_manifest.size(); + uint32_t node_size = size; + + manifest_end.resize(p_manifest.size() - ofs); + memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size()); + + int32_t attr_name_string = string_table.find("name"); + ERR_EXPLAIN("Template does not have 'name' attribute"); + ERR_FAIL_COND(attr_name_string == -1); + + int32_t ns_android_string = string_table.find("android"); + ERR_EXPLAIN("Template does not have 'android' namespace"); + ERR_FAIL_COND(ns_android_string == -1); + + int32_t attr_uses_permission_string = string_table.find("uses-permission"); + if (attr_uses_permission_string == -1) { + string_table.push_back("uses-permission"); + attr_uses_permission_string = string_table.size() - 1; + } + + for (int i = 0; i < perms.size(); ++i) { + print_line("Adding permission " + perms[i]); + + manifest_cur_size += 56 + 24; // node + end node + p_manifest.resize(manifest_cur_size); + + // Add permission to the string pool + int32_t perm_string = string_table.find(perms[i]); + if (perm_string == -1) { + string_table.push_back(perms[i]); + perm_string = string_table.size() - 1; + } + + // start tag + encode_uint16(0x102, &p_manifest[ofs]); // type + encode_uint16(16, &p_manifest[ofs + 2]); // headersize + encode_uint32(56, &p_manifest[ofs + 4]); // size + encode_uint32(0, &p_manifest[ofs + 8]); // lineno + encode_uint32(-1, &p_manifest[ofs + 12]); // comment + encode_uint32(-1, &p_manifest[ofs + 16]); // ns + encode_uint32(attr_uses_permission_string, &p_manifest[ofs + 20]); // name + encode_uint16(20, &p_manifest[ofs + 24]); // attr_start + encode_uint16(20, &p_manifest[ofs + 26]); // attr_size + encode_uint16(1, &p_manifest[ofs + 28]); // num_attrs + encode_uint16(0, &p_manifest[ofs + 30]); // id_index + encode_uint16(0, &p_manifest[ofs + 32]); // class_index + encode_uint16(0, &p_manifest[ofs + 34]); // style_index + + // attribute + encode_uint32(ns_android_string, &p_manifest[ofs + 36]); // ns + encode_uint32(attr_name_string, &p_manifest[ofs + 40]); // 'name' + encode_uint32(perm_string, &p_manifest[ofs + 44]); // raw_value + encode_uint16(8, &p_manifest[ofs + 48]); // typedvalue_size + p_manifest[ofs + 50] = 0; // typedvalue_always0 + p_manifest[ofs + 51] = 0x03; // typedvalue_type (string) + encode_uint32(perm_string, &p_manifest[ofs + 52]); // typedvalue reference + + ofs += 56; + + // end tag + encode_uint16(0x103, &p_manifest[ofs]); // type + encode_uint16(16, &p_manifest[ofs + 2]); // headersize + encode_uint32(24, &p_manifest[ofs + 4]); // size + encode_uint32(0, &p_manifest[ofs + 8]); // lineno + encode_uint32(-1, &p_manifest[ofs + 12]); // comment + encode_uint32(-1, &p_manifest[ofs + 16]); // ns + encode_uint32(attr_uses_permission_string, &p_manifest[ofs + 20]); // name + + ofs += 24; + } + + // copy footer back in + memcpy(&p_manifest[ofs], manifest_end.ptr(), manifest_end.size()); + } + } break; } ofs += size; @@ -806,17 +874,17 @@ class EditorExportAndroid : public EditorExportPlatform { encode_uint32(ofs, &ret[string_table_begins + i * 4]); ofs += string_table[i].length() * 2 + 2 + 2; - //print_line("ofs: "+itos(i)+": "+itos(ofs)); } + ret.resize(ret.size() + ofs); - uint8_t *chars = &ret[ret.size() - ofs]; + string_data_offset = ret.size() - ofs; + uint8_t *chars = &ret[string_data_offset]; for (int i = 0; i < string_table.size(); i++) { String s = string_table[i]; - //print_line("savint string :"+s); encode_uint16(s.length(), chars); chars += 2; - for (int j = 0; j < s.length(); j++) { //include zero? + for (int j = 0; j < s.length(); j++) { encode_uint16(s[j], chars); chars += 2; } @@ -828,6 +896,7 @@ class EditorExportAndroid : public EditorExportPlatform { ret.push_back(stable_extra[i]); } + //pad while (ret.size() % 4) ret.push_back(0); @@ -843,6 +912,8 @@ class EditorExportAndroid : public EditorExportPlatform { encode_uint32(ret.size(), &ret[4]); //update new file size encode_uint32(new_stable_end - 8, &ret[12]); //update new string table size + encode_uint32(string_table.size(), &ret[16]); //update new number of strings + encode_uint32(string_data_offset - 8, &ret[28]); //update new string data offset //print_line("file size: "+itos(ret.size())); diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp index f618c80a77..4caf4bd933 100644 --- a/platform/iphone/os_iphone.cpp +++ b/platform/iphone/os_iphone.cpp @@ -64,11 +64,6 @@ OSIPhone *OSIPhone::get_singleton() { return (OSIPhone *)OS::get_singleton(); }; -uint8_t OSIPhone::get_orientations() const { - - return supported_orientations; -}; - extern int gl_view_base_fb; // from gl_view.mm void OSIPhone::set_data_dir(String p_dir) { @@ -100,12 +95,6 @@ void OSIPhone::initialize_core() { Error OSIPhone::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { - supported_orientations = 0; - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal", true) ? 1 : 0) << LandscapeLeft); - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal_flipped", false) ? 1 : 0) << LandscapeRight); - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical", false) ? 1 : 0) << PortraitDown); - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical_flipped", false) ? 1 : 0) << PortraitUp); - RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h index 7d73a6fe5c..8dc1ae6dc2 100644 --- a/platform/iphone/os_iphone.h +++ b/platform/iphone/os_iphone.h @@ -47,14 +47,6 @@ class OSIPhone : public OS_Unix { -public: - enum Orientations { - PortraitDown, - PortraitUp, - LandscapeLeft, - LandscapeRight, - }; - private: enum { MAX_MOUSE_COUNT = 8, @@ -64,8 +56,6 @@ private: static HashMap<String, void *> dynamic_symbol_lookup_table; friend void register_dynamic_symbol(char *name, void *address); - uint8_t supported_orientations; - VisualServer *visual_server; AudioDriverCoreAudio audio_driver; diff --git a/platform/iphone/view_controller.mm b/platform/iphone/view_controller.mm index cdaae0cb81..f75f0fd812 100644 --- a/platform/iphone/view_controller.mm +++ b/platform/iphone/view_controller.mm @@ -83,51 +83,36 @@ int add_cmdline(int p_argc, char **p_args) { printf("*********** did receive memory warning!\n"); }; -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)p_orientation { - - if (/*OSIPhone::get_singleton() == NULL*/ TRUE) { - - printf("checking on info.plist\n"); - NSArray *arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; - switch (p_orientation) { - - case UIInterfaceOrientationLandscapeLeft: - return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; - - case UIInterfaceOrientationLandscapeRight: - return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO; - - case UIInterfaceOrientationPortrait: - return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO; - - case UIInterfaceOrientationPortraitUpsideDown: - return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO; - - default: - return NO; - } - }; - - uint8_t supported = OSIPhone::get_singleton()->get_orientations(); - switch (p_orientation) { - - case UIInterfaceOrientationLandscapeLeft: - return supported & (1 << OSIPhone::LandscapeLeft) ? YES : NO; - - case UIInterfaceOrientationLandscapeRight: - return supported & (1 << OSIPhone::LandscapeRight) ? YES : NO; - - case UIInterfaceOrientationPortrait: - return supported & (1 << OSIPhone::PortraitDown) ? YES : NO; - - case UIInterfaceOrientationPortraitUpsideDown: - return supported & (1 << OSIPhone::PortraitUp) ? YES : NO; - +- (BOOL)shouldAutorotate { + switch (OS::get_singleton()->get_screen_orientation()) { + case OS::SCREEN_SENSOR: + case OS::SCREEN_SENSOR_LANDSCAPE: + case OS::SCREEN_SENSOR_PORTRAIT: + return YES; default: return NO; } }; +- (UIInterfaceOrientationMask)supportedInterfaceOrientations { + switch (OS::get_singleton()->get_screen_orientation()) { + case OS::SCREEN_PORTRAIT: + return UIInterfaceOrientationMaskPortrait; + case OS::SCREEN_REVERSE_LANDSCAPE: + return UIInterfaceOrientationMaskLandscapeRight; + case OS::SCREEN_REVERSE_PORTRAIT: + return UIInterfaceOrientationMaskPortraitUpsideDown; + case OS::SCREEN_SENSOR_LANDSCAPE: + return UIInterfaceOrientationMaskLandscape; + case OS::SCREEN_SENSOR_PORTRAIT: + return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; + case OS::SCREEN_SENSOR: + return UIInterfaceOrientationMaskAll; + case OS::SCREEN_LANDSCAPE: + return UIInterfaceOrientationMaskLandscapeLeft; + } +}; + - (BOOL)prefersStatusBarHidden { return YES; } diff --git a/platform/javascript/dom_keys.h b/platform/javascript/dom_keys.inc index 4edca63c6d..dc8d67d52b 100644 --- a/platform/javascript/dom_keys.h +++ b/platform/javascript/dom_keys.inc @@ -1,5 +1,5 @@ /*************************************************************************/ -/* dom_keys.h */ +/* dom_keys.inc */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,9 +28,6 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef DOM_KEYS_H -#define DOM_KEYS_H - #include "os/keyboard.h" // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Constants_for_keyCode_value @@ -295,8 +292,8 @@ int dom2godot_scancode(int dom_keycode) { //case DOM_VK_SELECT: return KEY_UNKNOWN; - case DOM_VK_PRINTSCREEN: // this is the usual printScreen key - case DOM_VK_PRINT: // maybe for alt+printScreen or physical printers? + case DOM_VK_PRINTSCREEN: + case DOM_VK_PRINT: return KEY_PRINT; //case DOM_VK_EXECUTE: return KEY_UNKNOWN; @@ -311,11 +308,11 @@ int dom2godot_scancode(int dom_keycode) { case DOM_VK_SLEEP: return KEY_STANDBY; - // these are numpad keys according to MDN + // Numpad keys case DOM_VK_MULTIPLY: return KEY_KP_MULTIPLY; case DOM_VK_ADD: return KEY_KP_ADD; case DOM_VK_SEPARATOR: - return KEY_KP_PERIOD; // good enough? + return KEY_KP_PERIOD; // Good enough? case DOM_VK_SUBTRACT: return KEY_KP_SUBTRACT; case DOM_VK_DECIMAL: return KEY_KP_PERIOD; case DOM_VK_DIVIDE: @@ -376,10 +373,8 @@ int dom2godot_scancode(int dom_keycode) { case DOM_VK_QUOTE: return KEY_APOSTROPHE; - // rest is OEM/unusual + // The rest is OEM/unusual. default: return KEY_UNKNOWN; }; } - -#endif diff --git a/platform/javascript/javascript_main.cpp b/platform/javascript/javascript_main.cpp index 68a2d72464..3829e8d406 100644 --- a/platform/javascript/javascript_main.cpp +++ b/platform/javascript/javascript_main.cpp @@ -28,17 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "emscripten.h" #include "io/resource_loader.h" #include "main/main.h" #include "os_javascript.h" -OS_JavaScript *os = NULL; - -static void main_loop() { - - os->main_loop_iterate(); -} +#include <emscripten/emscripten.h> extern "C" EMSCRIPTEN_KEEPALIVE void main_after_fs_sync(char *p_idbfs_err) { @@ -46,18 +40,18 @@ extern "C" EMSCRIPTEN_KEEPALIVE void main_after_fs_sync(char *p_idbfs_err) { if (!idbfs_err.empty()) { print_line("IndexedDB not available: " + idbfs_err); } - os->set_idbfs_available(idbfs_err.empty()); - // Ease up compatibility + OS_JavaScript *os = OS_JavaScript::get_singleton(); + os->set_idb_available(idbfs_err.empty()); + // Ease up compatibility. ResourceLoader::set_abort_on_missing_resources(false); Main::start(); - os->main_loop_begin(); - emscripten_set_main_loop(main_loop, 0, false); + os->run_async(); } int main(int argc, char *argv[]) { - // sync from persistent state into memory and then - // run the 'main_after_fs_sync' function + // Sync from persistent state into memory and then + // run the 'main_after_fs_sync' function. /* clang-format off */ EM_ASM( FS.mkdir('/userfs'); @@ -68,9 +62,10 @@ int main(int argc, char *argv[]) { ); /* clang-format on */ - os = new OS_JavaScript(argv[0], NULL); - Error err = Main::setup(argv[0], argc - 1, &argv[1]); + new OS_JavaScript(argc, argv); + // TODO: Check error return value. + Main::setup(argv[0], argc - 1, &argv[1]); return 0; - // continued async in main_after_fs_sync() from syncfs() callback + // Continued async in main_after_fs_sync() from the syncfs() callback. } diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp index 6c6e4d2d1c..c05ae03ec6 100644 --- a/platform/javascript/os_javascript.cpp +++ b/platform/javascript/os_javascript.cpp @@ -30,290 +30,196 @@ #include "os_javascript.h" -#include "core/engine.h" -#include "core/io/file_access_buffered_fa.h" -#include "dom_keys.h" -#include "drivers/gles2/rasterizer_gles2.h" -#include "drivers/gles3/rasterizer_gles3.h" -#include "drivers/unix/dir_access_unix.h" -#include "drivers/unix/file_access_unix.h" +#include "gles2/rasterizer_gles2.h" +#include "gles3/rasterizer_gles3.h" +#include "io/file_access_buffered_fa.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" +#include "unix/dir_access_unix.h" +#include "unix/file_access_unix.h" #include <emscripten.h> #include <stdlib.h> +#include "dom_keys.inc" + #define DOM_BUTTON_LEFT 0 #define DOM_BUTTON_MIDDLE 1 #define DOM_BUTTON_RIGHT 2 +#define DOM_BUTTON_XBUTTON1 3 +#define DOM_BUTTON_XBUTTON2 4 -template <typename T> -static void dom2godot_mod(T emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) { - - godot_event->set_shift(emscripten_event_ptr->shiftKey); - godot_event->set_alt(emscripten_event_ptr->altKey); - godot_event->set_control(emscripten_event_ptr->ctrlKey); - godot_event->set_metakey(emscripten_event_ptr->metaKey); -} - -int OS_JavaScript::get_video_driver_count() const { +// Window (canvas) - return VIDEO_DRIVER_MAX; -} - -const char *OS_JavaScript::get_video_driver_name(int p_driver) const { - - switch (p_driver) { - case VIDEO_DRIVER_GLES3: - return "GLES3"; - case VIDEO_DRIVER_GLES2: - return "GLES2"; - } - ERR_EXPLAIN("Invalid video driver index " + itos(p_driver)); - ERR_FAIL_V(NULL); -} - -int OS_JavaScript::get_audio_driver_count() const { - - return 1; -} - -const char *OS_JavaScript::get_audio_driver_name(int p_driver) const { +static void focus_canvas() { - return "JavaScript"; + /* clang-format off */ + EM_ASM( + Module.canvas.focus(); + ); + /* clang-format on */ } -void OS_JavaScript::initialize_core() { +static bool is_canvas_focused() { - OS_Unix::initialize_core(); - FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES); + /* clang-format off */ + return EM_ASM_INT_V( + return document.activeElement == Module.canvas; + ); + /* clang-format on */ } -static EM_BOOL _browser_resize_callback(int event_type, const EmscriptenUiEvent *ui_event, void *user_data) { +static bool cursor_inside_canvas = true; - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_RESIZE, false); +EM_BOOL OS_JavaScript::browser_resize_callback(int p_event_type, const EmscriptenUiEvent *p_event, void *p_user_data) { - OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data); // The order of the fullscreen change event and the window size change - // event varies, even within just one browser, so defer handling - os->request_canvas_size_adjustment(); + // event varies, even within just one browser, so defer handling. + get_singleton()->canvas_size_adjustment_requested = true; return false; } -static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFullscreenChangeEvent *event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false); +EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) { - OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data); - String id = String::utf8(event->id); - // empty id is canvas - if (id.empty() || id == "canvas") { - - OS::VideoMode vm = os->get_video_mode(); - // this event property is the only reliable information on - // browser fullscreen state - vm.fullscreen = event->isFullscreen; - os->set_video_mode(vm); - os->request_canvas_size_adjustment(); + OS_JavaScript *os = get_singleton(); + // Empty ID is canvas. + String target_id = String::utf8(p_event->id); + if (target_id.empty() || target_id == "canvas") { + // This event property is the only reliable data on + // browser fullscreen state. + os->video_mode.fullscreen = p_event->isFullscreen; + os->canvas_size_adjustment_requested = true; } return false; } -static InputDefault *_input; - -static bool is_canvas_focused() { +void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) { - /* clang-format off */ - return EM_ASM_INT_V( - return document.activeElement == Module.canvas; - ); - /* clang-format on */ + video_mode = p_video_mode; } -static void focus_canvas() { +OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const { - /* clang-format off */ - EM_ASM( - Module.canvas.focus(); - ); - /* clang-format on */ + return video_mode; } -static bool _cursor_inside_canvas = true; - -static bool is_cursor_inside_canvas() { +Size2 OS_JavaScript::get_screen_size(int p_screen) const { - return _cursor_inside_canvas; + EmscriptenFullscreenChangeEvent ev; + EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev); + ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2()); + return Size2(ev.screenWidth, ev.screenHeight); } -static EM_BOOL _mousebutton_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEDOWN && event_type != EMSCRIPTEN_EVENT_MOUSEUP, false); - - Ref<InputEventMouseButton> ev; - ev.instance(); - ev->set_pressed(event_type == EMSCRIPTEN_EVENT_MOUSEDOWN); - ev->set_position(Point2(mouse_event->canvasX, mouse_event->canvasY)); - ev->set_global_position(ev->get_position()); - dom2godot_mod(mouse_event, ev); - - switch (mouse_event->button) { - case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break; - case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break; - case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break; - default: return false; - } +void OS_JavaScript::set_window_size(const Size2 p_size) { - int mask = _input->get_mouse_button_mask(); - int button_flag = 1 << (ev->get_button_index() - 1); - if (ev->is_pressed()) { - // Since the event is consumed, focus manually. The containing iframe, - // if used, may not have focus yet, so focus even if already focused. - focus_canvas(); - mask |= button_flag; - } else if (mask & button_flag) { - mask &= ~button_flag; + windowed_size = p_size; + if (is_window_fullscreen()) { + window_maximized = false; + set_window_fullscreen(false); + } else if (is_window_maximized()) { + set_window_maximized(false); } else { - // release event, but press was outside the canvas, so ignore - return false; + video_mode.width = p_size.x; + video_mode.height = p_size.y; + emscripten_set_canvas_size(p_size.x, p_size.y); } - ev->set_button_mask(mask); - - _input->parse_input_event(ev); - // Prevent multi-click text selection and wheel-click scrolling anchor. - // Context menu is prevented through contextmenu event. - return true; } -static EM_BOOL _mousemove_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEMOVE, false); - OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data); - int input_mask = _input->get_mouse_button_mask(); - Point2 pos = Point2(mouse_event->canvasX, mouse_event->canvasY); - // outside the canvas, only read mouse movement if dragging started inside - // the canvas; imitating desktop app behaviour - if (!is_cursor_inside_canvas() && !input_mask) - return false; - - Ref<InputEventMouseMotion> ev; - ev.instance(); - dom2godot_mod(mouse_event, ev); - ev->set_button_mask(input_mask); - - ev->set_position(pos); - ev->set_global_position(ev->get_position()); - - ev->set_relative(Vector2(mouse_event->movementX, mouse_event->movementY)); - _input->set_mouse_position(ev->get_position()); - ev->set_speed(_input->get_last_mouse_speed()); +Size2 OS_JavaScript::get_window_size() const { - _input->parse_input_event(ev); - // don't suppress mouseover/leave events - return false; + int canvas[3]; + emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2); + return Size2(canvas[0], canvas[1]); } -static EM_BOOL _wheel_callback(int event_type, const EmscriptenWheelEvent *wheel_event, void *user_data) { +void OS_JavaScript::set_window_maximized(bool p_enabled) { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_WHEEL, false); - if (!is_canvas_focused()) { - if (is_cursor_inside_canvas()) { - focus_canvas(); - } else { - return false; - } + window_maximized = p_enabled; + if (is_window_fullscreen()) { + set_window_fullscreen(false); + return; } + // Calling emscripten_enter_soft_fullscreen mutltiple times hides all + // page elements except the canvas permanently, so track state. + if (p_enabled && !soft_fullscreen_enabled) { - Ref<InputEventMouseButton> ev; - ev.instance(); - ev->set_button_mask(_input->get_mouse_button_mask()); - ev->set_position(_input->get_mouse_position()); - ev->set_global_position(ev->get_position()); - - ev->set_shift(_input->is_key_pressed(KEY_SHIFT)); - ev->set_alt(_input->is_key_pressed(KEY_ALT)); - ev->set_control(_input->is_key_pressed(KEY_CONTROL)); - ev->set_metakey(_input->is_key_pressed(KEY_META)); - - if (wheel_event->deltaY < 0) - ev->set_button_index(BUTTON_WHEEL_UP); - else if (wheel_event->deltaY > 0) - ev->set_button_index(BUTTON_WHEEL_DOWN); - else if (wheel_event->deltaX > 0) - ev->set_button_index(BUTTON_WHEEL_LEFT); - else if (wheel_event->deltaX < 0) - ev->set_button_index(BUTTON_WHEEL_RIGHT); - else - return false; - - // Different browsers give wildly different delta values, and we can't - // interpret deltaMode, so use default value for wheel events' factor + EmscriptenFullscreenStrategy strategy; + strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; + strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; + strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; + strategy.canvasResizedCallback = NULL; + emscripten_enter_soft_fullscreen(NULL, &strategy); + soft_fullscreen_enabled = true; + video_mode.width = get_window_size().width; + video_mode.height = get_window_size().height; + } else if (!p_enabled) { - ev->set_pressed(true); - _input->parse_input_event(ev); + emscripten_exit_soft_fullscreen(); + soft_fullscreen_enabled = false; + video_mode.width = windowed_size.width; + video_mode.height = windowed_size.height; + emscripten_set_canvas_size(video_mode.width, video_mode.height); + } +} - ev->set_pressed(false); - _input->parse_input_event(ev); +bool OS_JavaScript::is_window_maximized() const { - return true; + return window_maximized; } -static Point2 _prev_touches[32]; - -static EM_BOOL _touchpress_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) { +void OS_JavaScript::set_window_fullscreen(bool p_enabled) { - ERR_FAIL_COND_V( - event_type != EMSCRIPTEN_EVENT_TOUCHSTART && - event_type != EMSCRIPTEN_EVENT_TOUCHEND && - event_type != EMSCRIPTEN_EVENT_TOUCHCANCEL, - false); + if (p_enabled == is_window_fullscreen()) { + return; + } - Ref<InputEventScreenTouch> ev; - ev.instance(); - int lowest_id_index = -1; - for (int i = 0; i < touch_event->numTouches; ++i) { + // Just request changes here, if successful, canvas is resized in + // _browser_resize_callback or _fullscreen_change_callback. + EMSCRIPTEN_RESULT result; + if (p_enabled) { + if (window_maximized) { + // Soft fullsreen during real fulllscreen can cause issues. + set_window_maximized(false); + window_maximized = true; + } + EmscriptenFullscreenStrategy strategy; + strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; + strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; + strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; + strategy.canvasResizedCallback = NULL; + emscripten_request_fullscreen_strategy(NULL, false, &strategy); + } else { + result = emscripten_exit_fullscreen(); + if (result != EMSCRIPTEN_RESULT_SUCCESS) { + ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result)); + } + } +} - const EmscriptenTouchPoint &touch = touch_event->touches[i]; - if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier) - lowest_id_index = i; - if (!touch.isChanged) - continue; - ev->set_index(touch.identifier); - ev->set_position(Point2(touch.canvasX, touch.canvasY)); - _prev_touches[i] = ev->get_position(); - ev->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART); +bool OS_JavaScript::is_window_fullscreen() const { - _input->parse_input_event(ev); - } - return true; + return video_mode.fullscreen; } -static EM_BOOL _touchmove_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) { +void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_TOUCHMOVE, false); + Size2 screen = get_screen_size(); + p_list->push_back(OS::VideoMode(screen.width, screen.height, true)); +} - Ref<InputEventScreenDrag> ev; - ev.instance(); - int lowest_id_index = -1; - for (int i = 0; i < touch_event->numTouches; ++i) { +// Keys - const EmscriptenTouchPoint &touch = touch_event->touches[i]; - if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier) - lowest_id_index = i; - if (!touch.isChanged) - continue; - ev->set_index(touch.identifier); - ev->set_position(Point2(touch.canvasX, touch.canvasY)); - Point2 &prev = _prev_touches[i]; - ev->set_relative(ev->get_position() - prev); - prev = ev->get_position(); +template <typename T> +static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) { - _input->parse_input_event(ev); - } - return true; + godot_event->set_shift(emscripten_event_ptr->shiftKey); + godot_event->set_alt(emscripten_event_ptr->altKey); + godot_event->set_control(emscripten_event_ptr->ctrlKey); + godot_event->set_metakey(emscripten_event_ptr->metaKey); } -static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) { +static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) { Ref<InputEventKey> ev; ev.instance(); @@ -322,9 +228,9 @@ static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscri ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode)); String unicode = String::utf8(emscripten_event->key); - // check if empty or multi-character (e.g. `CapsLock`) + // Check if empty or multi-character (e.g. `CapsLock`). if (unicode.length() != 1) { - // might be empty as well, but better than nonsense + // Might be empty as well, but better than nonsense. unicode = String::utf8(emscripten_event->charValue); } if (unicode.length() == 1) { @@ -334,175 +240,115 @@ static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscri return ev; } -static Ref<InputEventKey> deferred_key_event; - -static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) { +EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false); - - Ref<InputEventKey> ev = _setup_key_event(key_event); + OS_JavaScript *os = get_singleton(); + Ref<InputEventKey> ev = setup_key_event(p_event); ev->set_pressed(true); if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) { - // defer to keypress event for legacy unicode retrieval - deferred_key_event = ev; - return false; // do not suppress keypress event + // Defer to keypress event for legacy unicode retrieval. + os->deferred_key_event = ev; + // Do not suppress keypress event. + return false; } - _input->parse_input_event(ev); + os->input->parse_input_event(ev); return true; } -static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false); +EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - deferred_key_event->set_unicode(key_event->charCode); - _input->parse_input_event(deferred_key_event); + OS_JavaScript *os = get_singleton(); + os->deferred_key_event->set_unicode(p_event->charCode); + os->input->parse_input_event(os->deferred_key_event); return true; } -static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) { +EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false); - - Ref<InputEventKey> ev = _setup_key_event(key_event); + Ref<InputEventKey> ev = setup_key_event(p_event); ev->set_pressed(false); - _input->parse_input_event(ev); + get_singleton()->input->parse_input_event(ev); return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0; } -static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) { - OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton(); - if (os) { - return os->joy_connection_changed(p_type, p_event); - } - return false; +// Mouse + +Point2 OS_JavaScript::get_mouse_position() const { + + return input->get_mouse_position(); } -extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int notif) { +int OS_JavaScript::get_mouse_button_state() const { - if (notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || notif == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) { - _cursor_inside_canvas = notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER; - } - OS_JavaScript::get_singleton()->get_main_loop()->notification(notif); + return input->get_mouse_button_mask(); } -Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { +EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) { - print_line("Init OS"); + OS_JavaScript *os = get_singleton(); - EmscriptenWebGLContextAttributes attributes; - emscripten_webgl_init_context_attributes(&attributes); - attributes.alpha = false; - attributes.antialias = false; - ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER); - switch (p_video_driver) { - case VIDEO_DRIVER_GLES3: - attributes.majorVersion = 2; - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); - break; - case VIDEO_DRIVER_GLES2: - attributes.majorVersion = 1; - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - break; + Ref<InputEventMouseButton> ev; + ev.instance(); + ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN); + ev->set_position(Point2(p_event->canvasX, p_event->canvasY)); + ev->set_global_position(ev->get_position()); + dom2godot_mod(p_event, ev); + switch (p_event->button) { + case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break; + case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break; + case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break; + case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break; + case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break; + default: return false; } - EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes); - ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available"); - ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE); - video_mode = p_desired; - // can't fulfil fullscreen request due to browser security - video_mode.fullscreen = false; - /* clang-format off */ - if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) { - /* clang-format on */ - set_window_size(Size2(video_mode.width, video_mode.height)); + int mask = os->input->get_mouse_button_mask(); + int button_flag = 1 << (ev->get_button_index() - 1); + if (ev->is_pressed()) { + // Since the event is consumed, focus manually. The containing iframe, + // if exists, may not have focus yet, so focus even if already focused. + focus_canvas(); + mask |= button_flag; + } else if (mask & button_flag) { + mask &= ~button_flag; } else { - set_window_size(get_window_size()); + // Received release event, but press was outside the canvas, so ignore. + return false; } + ev->set_button_mask(mask); - char locale_ptr[16]; - /* clang-format off */ - EM_ASM_ARGS({ - stringToUTF8(Module.locale, $0, 16); - }, locale_ptr); - /* clang-format on */ - setenv("LANG", locale_ptr, true); - - print_line("Init Audio"); - - AudioDriverManager::initialize(p_audio_driver); - - print_line("Init VS"); - - visual_server = memnew(VisualServerRaster()); - // visual_server->cursor_set_visible(false, 0); - - print_line("Init Physicsserver"); - - input = memnew(InputDefault); - _input = input; - -#define EM_CHECK(ev) \ - if (result != EMSCRIPTEN_RESULT_SUCCESS) \ - ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result)) -#define SET_EM_CALLBACK(target, ev, cb) \ - result = emscripten_set_##ev##_callback(target, this, true, &cb); \ - EM_CHECK(ev) -#define SET_EM_CALLBACK_NODATA(ev, cb) \ - result = emscripten_set_##ev##_callback(NULL, true, &cb); \ - EM_CHECK(ev) - - EMSCRIPTEN_RESULT result; - SET_EM_CALLBACK("#window", mousemove, _mousemove_callback) - SET_EM_CALLBACK("#canvas", mousedown, _mousebutton_callback) - SET_EM_CALLBACK("#window", mouseup, _mousebutton_callback) - SET_EM_CALLBACK("#window", wheel, _wheel_callback) - SET_EM_CALLBACK("#window", touchstart, _touchpress_callback) - SET_EM_CALLBACK("#window", touchmove, _touchmove_callback) - SET_EM_CALLBACK("#window", touchend, _touchpress_callback) - SET_EM_CALLBACK("#window", touchcancel, _touchpress_callback) - SET_EM_CALLBACK("#canvas", keydown, _keydown_callback) - SET_EM_CALLBACK("#canvas", keypress, _keypress_callback) - SET_EM_CALLBACK("#canvas", keyup, _keyup_callback) - SET_EM_CALLBACK(NULL, resize, _browser_resize_callback) - SET_EM_CALLBACK(NULL, fullscreenchange, _fullscreen_change_callback) - SET_EM_CALLBACK_NODATA(gamepadconnected, joy_callback_func) - SET_EM_CALLBACK_NODATA(gamepaddisconnected, joy_callback_func) - -#undef SET_EM_CALLBACK_NODATA -#undef SET_EM_CALLBACK -#undef EM_CHECK - - visual_server->init(); - - return OK; + os->input->parse_input_event(ev); + // Prevent multi-click text selection and wheel-click scrolling anchor. + // Context menu is prevented through contextmenu event. + return true; } -void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) { +EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) { - main_loop = p_main_loop; - input->set_main_loop(p_main_loop); -} - -void OS_JavaScript::delete_main_loop() { + OS_JavaScript *os = get_singleton(); - memdelete(main_loop); -} + int input_mask = os->input->get_mouse_button_mask(); + Point2 pos = Point2(p_event->canvasX, p_event->canvasY); + // For motion outside the canvas, only read mouse movement if dragging + // started inside the canvas; imitating desktop app behaviour. + if (!cursor_inside_canvas && !input_mask) + return false; -void OS_JavaScript::finalize() { + Ref<InputEventMouseMotion> ev; + ev.instance(); + dom2godot_mod(p_event, ev); + ev->set_button_mask(input_mask); - memdelete(input); -} + ev->set_position(pos); + ev->set_global_position(ev->get_position()); -void OS_JavaScript::alert(const String &p_alert, const String &p_title) { + ev->set_relative(Vector2(p_event->movementX, p_event->movementY)); + os->input->set_mouse_position(ev->get_position()); + ev->set_speed(os->input->get_last_mouse_speed()); - /* clang-format off */ - EM_ASM_({ - window.alert(UTF8ToString($0)); - }, p_alert.utf8().get_data()); - /* clang-format on */ + os->input->parse_input_event(ev); + // Don't suppress mouseover/-leave events. + return false; } static const char *godot2dom_cursor(OS::CursorShape p_shape) { @@ -530,7 +376,7 @@ static const char *godot2dom_cursor(OS::CursorShape p_shape) { } } -void OS_JavaScript::set_css_cursor(const char *p_cursor) { +static void set_css_cursor(const char *p_cursor) { /* clang-format off */ EM_ASM_({ @@ -539,7 +385,7 @@ void OS_JavaScript::set_css_cursor(const char *p_cursor) { /* clang-format on */ } -const char *OS_JavaScript::get_css_cursor() const { +static const char *get_css_cursor() { char cursor[16]; /* clang-format off */ @@ -550,9 +396,20 @@ const char *OS_JavaScript::get_css_cursor() const { return cursor; } +void OS_JavaScript::set_cursor_shape(CursorShape p_shape) { + + ERR_FAIL_INDEX(p_shape, CURSOR_MAX); + + cursor_shape = p_shape; + if (get_mouse_mode() != MOUSE_MODE_HIDDEN) + set_css_cursor(godot2dom_cursor(cursor_shape)); +} + +void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { +} + void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) { - ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1); ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform"); ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED); if (p_mode == get_mouse_mode()) @@ -580,190 +437,303 @@ void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) { OS::MouseMode OS_JavaScript::get_mouse_mode() const { - if (!strcmp(get_css_cursor(), "none")) + if (String::utf8(get_css_cursor()) == "none") return MOUSE_MODE_HIDDEN; EmscriptenPointerlockChangeEvent ev; emscripten_get_pointerlock_status(&ev); - return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE; + return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE; } -Point2 OS_JavaScript::get_mouse_position() const { +// Wheel - return input->get_mouse_position(); -} +EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) { -int OS_JavaScript::get_mouse_button_state() const { + ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false); + if (!is_canvas_focused()) { + if (cursor_inside_canvas) { + focus_canvas(); + } else { + return false; + } + } - return input->get_mouse_button_mask(); -} + InputDefault *input = get_singleton()->input; + Ref<InputEventMouseButton> ev; + ev.instance(); + ev->set_button_mask(input->get_mouse_button_mask()); + ev->set_position(input->get_mouse_position()); + ev->set_global_position(ev->get_position()); -void OS_JavaScript::set_window_title(const String &p_title) { + ev->set_shift(input->is_key_pressed(KEY_SHIFT)); + ev->set_alt(input->is_key_pressed(KEY_ALT)); + ev->set_control(input->is_key_pressed(KEY_CONTROL)); + ev->set_metakey(input->is_key_pressed(KEY_META)); - /* clang-format off */ - EM_ASM_({ - document.title = UTF8ToString($0); - }, p_title.utf8().get_data()); - /* clang-format on */ -} + if (p_event->deltaY < 0) + ev->set_button_index(BUTTON_WHEEL_UP); + else if (p_event->deltaY > 0) + ev->set_button_index(BUTTON_WHEEL_DOWN); + else if (p_event->deltaX > 0) + ev->set_button_index(BUTTON_WHEEL_LEFT); + else if (p_event->deltaX < 0) + ev->set_button_index(BUTTON_WHEEL_RIGHT); + else + return false; -//interesting byt not yet -//void set_clipboard(const String& p_text); -//String get_clipboard() const; + // Different browsers give wildly different delta values, and we can't + // interpret deltaMode, so use default value for wheel events' factor. -void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) { + ev->set_pressed(true); + input->parse_input_event(ev); - video_mode = p_video_mode; + ev->set_pressed(false); + input->parse_input_event(ev); + + return true; } -OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const { +// Touch - return video_mode; +bool OS_JavaScript::has_touchscreen_ui_hint() const { + + /* clang-format off */ + return EM_ASM_INT_V( + return 'ontouchstart' in window; + ); + /* clang-format on */ } -Size2 OS_JavaScript::get_screen_size(int p_screen) const { +EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) { - EmscriptenFullscreenChangeEvent ev; - EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev); - ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2()); - return Size2(ev.screenWidth, ev.screenHeight); -} + OS_JavaScript *os = get_singleton(); + Ref<InputEventScreenTouch> ev; + ev.instance(); + int lowest_id_index = -1; + for (int i = 0; i < p_event->numTouches; ++i) { -void OS_JavaScript::set_window_size(const Size2 p_size) { + const EmscriptenTouchPoint &touch = p_event->touches[i]; + if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier) + lowest_id_index = i; + if (!touch.isChanged) + continue; + ev->set_index(touch.identifier); + ev->set_position(Point2(touch.canvasX, touch.canvasY)); + os->touches[i] = ev->get_position(); + ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART); - windowed_size = p_size; - if (is_window_fullscreen()) { - window_maximized = false; - set_window_fullscreen(false); - } else if (is_window_maximized()) { - set_window_maximized(false); - } else { - video_mode.width = p_size.x; - video_mode.height = p_size.y; - emscripten_set_canvas_size(p_size.x, p_size.y); + os->input->parse_input_event(ev); } + return true; } -Size2 OS_JavaScript::get_window_size() const { +EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) { - int canvas[3]; - emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2); - return Size2(canvas[0], canvas[1]); -} + OS_JavaScript *os = get_singleton(); + Ref<InputEventScreenDrag> ev; + ev.instance(); + int lowest_id_index = -1; + for (int i = 0; i < p_event->numTouches; ++i) { -void OS_JavaScript::set_window_maximized(bool p_enabled) { + const EmscriptenTouchPoint &touch = p_event->touches[i]; + if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier) + lowest_id_index = i; + if (!touch.isChanged) + continue; + ev->set_index(touch.identifier); + ev->set_position(Point2(touch.canvasX, touch.canvasY)); + Point2 &prev = os->touches[i]; + ev->set_relative(ev->get_position() - prev); + prev = ev->get_position(); - window_maximized = p_enabled; - if (is_window_fullscreen()) { - set_window_fullscreen(false); - return; + os->input->parse_input_event(ev); } - // Calling emscripten_enter_soft_fullscreen mutltiple times hides all - // page elements except the canvas permanently, so track state - if (p_enabled && !soft_fs_enabled) { + return true; +} - EmscriptenFullscreenStrategy strategy; - strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; - strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; - strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; - emscripten_enter_soft_fullscreen(NULL, &strategy); - soft_fs_enabled = true; - video_mode.width = get_window_size().width; - video_mode.height = get_window_size().height; - } else if (!p_enabled) { +// Gamepad - emscripten_exit_soft_fullscreen(); - soft_fs_enabled = false; - video_mode.width = windowed_size.width; - video_mode.height = windowed_size.height; - emscripten_set_canvas_size(video_mode.width, video_mode.height); +EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) { + + InputDefault *input = get_singleton()->input; + if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) { + + String guid = ""; + if (String::utf8(p_event->mapping) == "standard") + guid = "Default HTML5 Gamepad"; + input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid); + } else { + input->joy_connection_changed(p_event->index, false, ""); } + return true; } -void OS_JavaScript::set_window_fullscreen(bool p_enable) { +void OS_JavaScript::process_joypads() { - if (p_enable == is_window_fullscreen()) { - return; - } + int joypad_count = emscripten_get_num_gamepads(); + for (int joypad = 0; joypad < joypad_count; joypad++) { + EmscriptenGamepadEvent state; + emscripten_get_gamepad_status(joypad, &state); + if (state.connected) { - // only requesting changes here, if successful, canvas is resized in - // _browser_resize_callback or _fullscreen_change_callback - EMSCRIPTEN_RESULT result; - if (p_enable) { - if (window_maximized) { - // soft fs during real fs can cause issues - set_window_maximized(false); - window_maximized = true; - } - EmscriptenFullscreenStrategy strategy; - strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; - strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; - strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; - emscripten_request_fullscreen_strategy(NULL, false, &strategy); - } else { - result = emscripten_exit_fullscreen(); - if (result != EMSCRIPTEN_RESULT_SUCCESS) { - ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result)); + int button_count = MIN(state.numButtons, 18); + int axis_count = MIN(state.numAxes, 8); + for (int button = 0; button < button_count; button++) { + + float value = state.analogButton[button]; + if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) { + InputDefault::JoyAxis joy_axis; + joy_axis.min = 0; + joy_axis.value = value; + input->joy_axis(joypad, button, joy_axis); + } else { + input->joy_button(joypad, button, value); + } + } + for (int axis = 0; axis < axis_count; axis++) { + + InputDefault::JoyAxis joy_axis; + joy_axis.min = -1; + joy_axis.value = state.axis[axis]; + input->joy_axis(joypad, axis, joy_axis); + } } } } -bool OS_JavaScript::is_window_fullscreen() const { +bool OS_JavaScript::is_joy_known(int p_device) { - return video_mode.fullscreen; + return input->is_joy_mapped(p_device); } -void OS_JavaScript::request_canvas_size_adjustment() { +String OS_JavaScript::get_joy_guid(int p_device) const { - canvas_size_adjustment_requested = true; + return input->get_joy_guid_remapped(p_device); } -void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { +// Video - Size2 screen = get_screen_size(); - p_list->push_back(OS::VideoMode(screen.width, screen.height, true)); +int OS_JavaScript::get_video_driver_count() const { + + return VIDEO_DRIVER_MAX; } -String OS_JavaScript::get_name() { +const char *OS_JavaScript::get_video_driver_name(int p_driver) const { - return "HTML5"; + switch (p_driver) { + case VIDEO_DRIVER_GLES3: + return "GLES3"; + case VIDEO_DRIVER_GLES2: + return "GLES2"; + } + ERR_EXPLAIN("Invalid video driver index " + itos(p_driver)); + ERR_FAIL_V(NULL); } -MainLoop *OS_JavaScript::get_main_loop() const { +// Audio - return main_loop; +int OS_JavaScript::get_audio_driver_count() const { + + return 1; } -bool OS_JavaScript::can_draw() const { +const char *OS_JavaScript::get_audio_driver_name(int p_driver) const { - return true; //always? + return "JavaScript"; } -void OS_JavaScript::set_cursor_shape(CursorShape p_shape) { +// Lifecycle - ERR_FAIL_INDEX(p_shape, CURSOR_MAX); +void OS_JavaScript::initialize_core() { - cursor_shape = p_shape; - if (get_mouse_mode() != MOUSE_MODE_HIDDEN) - set_css_cursor(godot2dom_cursor(cursor_shape)); + OS_Unix::initialize_core(); + FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES); } -void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { -} +Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { + + EmscriptenWebGLContextAttributes attributes; + emscripten_webgl_init_context_attributes(&attributes); + attributes.alpha = false; + attributes.antialias = false; + ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER); + switch (p_video_driver) { + case VIDEO_DRIVER_GLES3: + attributes.majorVersion = 2; + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + case VIDEO_DRIVER_GLES2: + attributes.majorVersion = 1; + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } + EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes); + ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available"); + ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE); -void OS_JavaScript::main_loop_begin() { + video_mode = p_desired; + // Can't fulfil fullscreen request during start-up due to browser security. + video_mode.fullscreen = false; + /* clang-format off */ + if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) { + /* clang-format on */ + set_window_size(Size2(video_mode.width, video_mode.height)); + } else { + set_window_size(get_window_size()); + } - if (main_loop) - main_loop->init(); + char locale_ptr[16]; + /* clang-format off */ + EM_ASM_ARGS({ + stringToUTF8(Module.locale, $0, 16); + }, locale_ptr); + /* clang-format on */ + setenv("LANG", locale_ptr, true); + + AudioDriverManager::initialize(p_audio_driver); + VisualServer *visual_server = memnew(VisualServerRaster()); + input = memnew(InputDefault); + + EMSCRIPTEN_RESULT result; +#define EM_CHECK(ev) \ + if (result != EMSCRIPTEN_RESULT_SUCCESS) \ + ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result)) +#define SET_EM_CALLBACK(target, ev, cb) \ + result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \ + EM_CHECK(ev) +#define SET_EM_CALLBACK_NOTARGET(ev, cb) \ + result = emscripten_set_##ev##_callback(NULL, true, &cb); \ + EM_CHECK(ev) + // These callbacks from Emscripten's html5.h suffice to access most + // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM + // is used below. + SET_EM_CALLBACK("#window", mousemove, mousemove_callback) + SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback) + SET_EM_CALLBACK("#window", mouseup, mouse_button_callback) + SET_EM_CALLBACK("#window", wheel, wheel_callback) + SET_EM_CALLBACK("#window", touchstart, touch_press_callback) + SET_EM_CALLBACK("#window", touchmove, touchmove_callback) + SET_EM_CALLBACK("#window", touchend, touch_press_callback) + SET_EM_CALLBACK("#window", touchcancel, touch_press_callback) + SET_EM_CALLBACK("#canvas", keydown, keydown_callback) + SET_EM_CALLBACK("#canvas", keypress, keypress_callback) + SET_EM_CALLBACK("#canvas", keyup, keyup_callback) + SET_EM_CALLBACK(NULL, resize, browser_resize_callback) + SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback) + SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback) + SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback) +#undef SET_EM_CALLBACK_NODATA +#undef SET_EM_CALLBACK +#undef EM_CHECK /* clang-format off */ EM_ASM_ARGS({ const send_notification = cwrap('send_notification', null, ['number']); - const notifs = arguments; - (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, i) { - Module.canvas.addEventListener(event, send_notification.bind(null, notifs[i])); + const notifications = arguments; + (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) { + Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index])); }); }, MainLoop::NOTIFICATION_WM_MOUSE_ENTER, @@ -772,22 +742,44 @@ void OS_JavaScript::main_loop_begin() { MainLoop::NOTIFICATION_WM_FOCUS_OUT ); /* clang-format on */ + + visual_server->init(); + + return OK; } -bool OS_JavaScript::main_loop_iterate() { +void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) { - if (!main_loop) - return false; + main_loop = p_main_loop; + input->set_main_loop(p_main_loop); +} + +MainLoop *OS_JavaScript::get_main_loop() const { + + return main_loop; +} + +void OS_JavaScript::run_async() { + + main_loop->init(); + emscripten_set_main_loop(main_loop_callback, -1, false); +} + +void OS_JavaScript::main_loop_callback() { + + get_singleton()->main_loop_iterate(); +} + +bool OS_JavaScript::main_loop_iterate() { - if (idbfs_available && time_to_save_sync >= 0) { - int64_t newtime = get_ticks_msec(); - int64_t elapsed = newtime - last_sync_time; - last_sync_time = newtime; + if (is_userfs_persistent() && sync_wait_time >= 0) { + int64_t current_time = get_ticks_msec(); + int64_t elapsed_time = current_time - last_sync_check_time; + last_sync_check_time = current_time; - time_to_save_sync -= elapsed; + sync_wait_time -= elapsed_time; - if (time_to_save_sync < 0) { - //time to sync, for real + if (sync_wait_time < 0) { /* clang-format off */ EM_ASM( FS.syncfs(function(err) { @@ -812,121 +804,101 @@ bool OS_JavaScript::main_loop_iterate() { return Main::iteration(); } -void OS_JavaScript::main_loop_end() { +void OS_JavaScript::delete_main_loop() { - if (main_loop) - main_loop->finish(); + memdelete(main_loop); } -void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) { +void OS_JavaScript::finalize() { - input->set_accelerometer(p_accelerometer); + memdelete(input); } -bool OS_JavaScript::has_touchscreen_ui_hint() const { +// Miscellaneous - /* clang-format off */ - return EM_ASM_INT_V( - return 'ontouchstart' in window; - ); - /* clang-format on */ +extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) { + + if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) { + cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER; + } + OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification); } -void OS_JavaScript::main_loop_request_quit() { +bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) { + + if (p_feature == "HTML5" || p_feature == "web") + return true; + +#ifdef JAVASCRIPT_EVAL_ENABLED + if (p_feature == "JavaScript") + return true; +#endif + + EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context(); + // All extensions are already automatically enabled, this function allows + // checking WebGL extension support without inline JavaScript + if (p_feature == "s3tc") + return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb"); + if (p_feature == "etc") + return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1"); + if (p_feature == "etc2") + return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc"); - if (main_loop) - main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); + return false; } -Error OS_JavaScript::shell_open(String p_uri) { +void OS_JavaScript::alert(const String &p_alert, const String &p_title) { + /* clang-format off */ EM_ASM_({ - window.open(UTF8ToString($0), '_blank'); - }, p_uri.utf8().get_data()); + window.alert(UTF8ToString($0)); + }, p_alert.utf8().get_data()); /* clang-format on */ - return OK; } -String OS_JavaScript::get_resource_dir() const { +void OS_JavaScript::set_window_title(const String &p_title) { - return "/"; //javascript has it's own filesystem for resources inside the APK + /* clang-format off */ + EM_ASM_({ + document.title = UTF8ToString($0); + }, p_title.utf8().get_data()); + /* clang-format on */ } -String OS_JavaScript::get_user_data_dir() const { - - /* - if (get_user_data_dir_func) - return get_user_data_dir_func(); - */ - return "/userfs"; -}; - String OS_JavaScript::get_executable_path() const { return OS::get_executable_path(); } -void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) { +Error OS_JavaScript::shell_open(String p_uri) { - OS_JavaScript *os = static_cast<OS_JavaScript *>(get_singleton()); - if (os->idbfs_available && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) { - os->last_sync_time = OS::get_singleton()->get_ticks_msec(); - os->time_to_save_sync = 5000; //five seconds since last save - } + // Open URI in a new tab, browser will deal with it by protocol. + /* clang-format off */ + EM_ASM_({ + window.open(UTF8ToString($0), '_blank'); + }, p_uri.utf8().get_data()); + /* clang-format on */ + return OK; } -void OS_JavaScript::process_joypads() { - - int joy_count = emscripten_get_num_gamepads(); - for (int i = 0; i < joy_count; i++) { - EmscriptenGamepadEvent state; - emscripten_get_gamepad_status(i, &state); - if (state.connected) { +String OS_JavaScript::get_name() { - int num_buttons = MIN(state.numButtons, 18); - int num_axes = MIN(state.numAxes, 8); - for (int j = 0; j < num_buttons; j++) { + return "HTML5"; +} - float value = state.analogButton[j]; - if (String(state.mapping) == "standard" && (j == 6 || j == 7)) { - InputDefault::JoyAxis jx; - jx.min = 0; - jx.value = value; - input->joy_axis(i, j, jx); - } else { - input->joy_button(i, j, value); - } - } - for (int j = 0; j < num_axes; j++) { +bool OS_JavaScript::can_draw() const { - InputDefault::JoyAxis jx; - jx.min = -1; - jx.value = state.axis[j]; - input->joy_axis(i, j, jx); - } - } - } + return true; // Always? } -bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) { - if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) { +String OS_JavaScript::get_user_data_dir() const { - String guid = ""; - if (String(p_event->mapping) == "standard") - guid = "Default HTML5 Gamepad"; - input->joy_connection_changed(p_event->index, true, String(p_event->id), guid); - } else { - input->joy_connection_changed(p_event->index, false, ""); - } - return true; -} + return "/userfs"; +}; -bool OS_JavaScript::is_joy_known(int p_device) { - return input->is_joy_mapped(p_device); -} +String OS_JavaScript::get_resource_dir() const { -String OS_JavaScript::get_joy_guid(int p_device) const { - return input->get_joy_guid_remapped(p_device); + return "/"; } OS::PowerState OS_JavaScript::get_power_state() { @@ -947,59 +919,53 @@ int OS_JavaScript::get_power_percent_left() { return -1; } -bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) { +void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) { - if (p_feature == "HTML5" || p_feature == "web") - return true; - -#ifdef JAVASCRIPT_EVAL_ENABLED - if (p_feature == "JavaScript") - return true; -#endif + OS_JavaScript *os = get_singleton(); + if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) { + os->last_sync_check_time = OS::get_singleton()->get_ticks_msec(); + // Wait five seconds in case more files are about to be closed. + os->sync_wait_time = 5000; + } +} - EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context(); - // all extensions are already automatically enabled, this function allows - // checking WebGL extension support without inline JavaScript - if (p_feature == "s3tc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb")) - return true; - if (p_feature == "etc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1")) - return true; - if (p_feature == "etc2" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc")) - return true; +void OS_JavaScript::set_idb_available(bool p_idb_available) { - return false; + idb_available = p_idb_available; } -void OS_JavaScript::set_idbfs_available(bool p_idbfs_available) { +bool OS_JavaScript::is_userfs_persistent() const { - idbfs_available = p_idbfs_available; + return idb_available; } -bool OS_JavaScript::is_userfs_persistent() const { +OS_JavaScript *OS_JavaScript::get_singleton() { - return idbfs_available; + return static_cast<OS_JavaScript *>(OS::get_singleton()); } -OS_JavaScript::OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func) { +OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) { + + List<String> arguments; + for (int i = 1; i < p_argc; i++) { + arguments.push_back(String::utf8(p_argv[i])); + } + set_cmdline(p_argv[0], arguments); - set_cmdline(p_execpath, get_cmdline_args()); - main_loop = NULL; window_maximized = false; - soft_fs_enabled = false; + soft_fullscreen_enabled = false; canvas_size_adjustment_requested = false; - get_user_data_dir_func = p_get_user_data_dir_func; - FileAccessUnix::close_notification_func = _close_notification_funcs; + main_loop = NULL; - idbfs_available = false; - time_to_save_sync = -1; + idb_available = false; + sync_wait_time = -1; + + AudioDriverManager::add_driver(&audio_driver_javascript); Vector<Logger *> loggers; loggers.push_back(memnew(StdLogger)); _set_logger(memnew(CompositeLogger(loggers))); - AudioDriverManager::add_driver(&audio_driver_javascript); -} - -OS_JavaScript::~OS_JavaScript() { + FileAccessUnix::close_notification_func = file_access_close_callback; } diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h index 46eb1b3f13..503c92585b 100644 --- a/platform/javascript/os_javascript.h +++ b/platform/javascript/os_javascript.h @@ -32,52 +32,56 @@ #define OS_JAVASCRIPT_H #include "audio_driver_javascript.h" -#include "drivers/unix/os_unix.h" #include "main/input_default.h" -#include "os/input.h" -#include "os/main_loop.h" #include "servers/audio_server.h" #include "servers/visual/rasterizer.h" +#include "unix/os_unix.h" #include <emscripten/html5.h> -typedef String (*GetUserDataDirFunc)(); - class OS_JavaScript : public OS_Unix { - bool idbfs_available; - int64_t time_to_save_sync; - int64_t last_sync_time; - - VisualServer *visual_server; - AudioDriverJavaScript audio_driver_javascript; - - InputDefault *input; + VideoMode video_mode; Vector2 windowed_size; bool window_maximized; - bool soft_fs_enabled; + bool soft_fullscreen_enabled; bool canvas_size_adjustment_requested; - VideoMode video_mode; + + InputDefault *input; + Ref<InputEventKey> deferred_key_event; CursorShape cursor_shape; + Point2 touches[32]; + MainLoop *main_loop; + AudioDriverJavaScript audio_driver_javascript; - GetUserDataDirFunc get_user_data_dir_func; + bool idb_available; + int64_t sync_wait_time; + int64_t last_sync_check_time; - static void _close_notification_funcs(const String &p_file, int p_flags); + static EM_BOOL browser_resize_callback(int p_event_type, const EmscriptenUiEvent *p_event, void *p_user_data); + static EM_BOOL fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data); - void process_joypads(); + static EM_BOOL keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); + static EM_BOOL keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); + static EM_BOOL keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); - void set_css_cursor(const char *); - const char *get_css_cursor() const; + static EM_BOOL mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data); + static EM_BOOL mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data); -public: - // functions used by main to initialize/deintialize the OS - virtual int get_video_driver_count() const; - virtual const char *get_video_driver_name(int p_driver) const; + static EM_BOOL wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data); - virtual int get_audio_driver_count() const; - virtual const char *get_audio_driver_name(int p_driver) const; + static EM_BOOL touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data); + static EM_BOOL touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data); + + static EM_BOOL gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data); + void process_joypads(); + static void main_loop_callback(); + + static void file_access_close_callback(const String &p_file, int p_flags); + +protected: virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); @@ -86,77 +90,64 @@ public: virtual void finalize(); - typedef int64_t ProcessID; - - //static OS* get_singleton(); - - virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); - - virtual void set_mouse_mode(MouseMode p_mode); - virtual MouseMode get_mouse_mode() const; - virtual Point2 get_mouse_position() const; - virtual int get_mouse_button_state() const; - virtual void set_window_title(const String &p_title); + virtual bool _check_internal_feature_support(const String &p_feature); - //virtual void set_clipboard(const String& p_text); - //virtual String get_clipboard() const; +public: + // Override return type to make writing static callbacks less tedious. + static OS_JavaScript *get_singleton(); virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0); virtual VideoMode get_video_mode(int p_screen = 0) const; virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const; - virtual Size2 get_screen_size(int p_screen = -1) const; - virtual void set_window_size(const Size2); virtual Size2 get_window_size() const; virtual void set_window_maximized(bool p_enabled); - virtual bool is_window_maximized() const { return window_maximized; } - virtual void set_window_fullscreen(bool p_enable); + virtual bool is_window_maximized() const; + virtual void set_window_fullscreen(bool p_enabled); virtual bool is_window_fullscreen() const; + virtual Size2 get_screen_size(int p_screen = -1) const; - void request_canvas_size_adjustment(); + virtual Point2 get_mouse_position() const; + virtual int get_mouse_button_state() const; + virtual void set_cursor_shape(CursorShape p_shape); + virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot); + virtual void set_mouse_mode(MouseMode p_mode); + virtual MouseMode get_mouse_mode() const; - virtual String get_name(); - virtual MainLoop *get_main_loop() const; + virtual bool has_touchscreen_ui_hint() const; - virtual bool can_draw() const; + virtual bool is_joy_known(int p_device); + virtual String get_joy_guid(int p_device) const; - virtual bool is_userfs_persistent() const; + virtual int get_video_driver_count() const; + virtual const char *get_video_driver_name(int p_driver) const; - virtual void set_cursor_shape(CursorShape p_shape); - virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot); + virtual int get_audio_driver_count() const; + virtual const char *get_audio_driver_name(int p_driver) const; - void main_loop_begin(); + virtual MainLoop *get_main_loop() const; + void run_async(); bool main_loop_iterate(); - void main_loop_request_quit(); - void main_loop_end(); - void main_loop_focusout(); - void main_loop_focusin(); - virtual bool has_touchscreen_ui_hint() const; - - virtual Error shell_open(String p_uri); - virtual String get_user_data_dir() const; + virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); + virtual void set_window_title(const String &p_title); String get_executable_path() const; - virtual String get_resource_dir() const; - - void process_accelerometer(const Vector3 &p_accelerometer); - void push_input(const Ref<InputEvent> &p_ev); + virtual Error shell_open(String p_uri); + virtual String get_name(); + virtual bool can_draw() const; - virtual bool is_joy_known(int p_device); - virtual String get_joy_guid(int p_device) const; - bool joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event); + virtual String get_resource_dir() const; + virtual String get_user_data_dir() const; virtual OS::PowerState get_power_state(); virtual int get_power_seconds_left(); virtual int get_power_percent_left(); - virtual bool _check_internal_feature_support(const String &p_feature); - - void set_idbfs_available(bool p_idbfs_available); + void set_idb_available(bool p_idb_available); + virtual bool is_userfs_persistent() const; - OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func); - ~OS_JavaScript(); + OS_JavaScript(int p_argc, char *p_argv[]); }; #endif diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index 4ece1e0325..41a19ac992 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -625,10 +625,18 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { - (void)otherMouseDown:(NSEvent *)event { - if ((int)[event buttonNumber] != 2) - return; + if ((int)[event buttonNumber] == 2) { + _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true); + + } else if ((int)[event buttonNumber] == 3) { + _mouseDownEvent(event, BUTTON_XBUTTON1, BUTTON_MASK_XBUTTON1, true); + + } else if ((int)[event buttonNumber] == 4) { + _mouseDownEvent(event, BUTTON_XBUTTON2, BUTTON_MASK_XBUTTON2, true); - _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true); + } else { + return; + } } - (void)otherMouseDragged:(NSEvent *)event { @@ -637,10 +645,18 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { - (void)otherMouseUp:(NSEvent *)event { - if ((int)[event buttonNumber] != 2) - return; + if ((int)[event buttonNumber] == 2) { + _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false); + + } else if ((int)[event buttonNumber] == 3) { + _mouseDownEvent(event, BUTTON_XBUTTON1, BUTTON_MASK_XBUTTON1, false); + + } else if ((int)[event buttonNumber] == 4) { + _mouseDownEvent(event, BUTTON_XBUTTON2, BUTTON_MASK_XBUTTON2, false); - _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false); + } else { + return; + } } - (void)mouseExited:(NSEvent *)event { diff --git a/platform/uwp/app.cpp b/platform/uwp/app.cpp index c18aa36402..b769925849 100644 --- a/platform/uwp/app.cpp +++ b/platform/uwp/app.cpp @@ -143,14 +143,13 @@ void App::SetWindow(CoreWindow ^ p_window) { window->KeyUp += ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &App::OnKeyUp); + os->set_window(window); + unsigned int argc; char **argv = get_command_line(&argc); Main::setup("uwp", argc, argv, false); - // The CoreWindow has been created, so EGL can be initialized. - ContextEGL *context = memnew(ContextEGL(window)); - os->set_gl_context(context); UpdateWindowSize(Size(window->Bounds.Width, window->Bounds.Height)); Main::setup2(); @@ -513,7 +512,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (f == NULL) { - wprintf(L"Couldn't open command line file."); + wprintf(L"Couldn't open command line file.\n"); return fail_cl; } @@ -527,7 +526,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (r < 4) { fclose(f); - wprintf(L"Wrong cmdline length."); + wprintf(L"Wrong cmdline length.\n"); return (fail_cl); } @@ -539,7 +538,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (r < 4) { fclose(f); - wprintf(L"Wrong cmdline param length."); + wprintf(L"Wrong cmdline param length.\n"); return (fail_cl); } @@ -547,7 +546,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (strlen > CMD_MAX_LEN) { fclose(f); - wprintf(L"Wrong command length."); + wprintf(L"Wrong command length.\n"); return (fail_cl); } @@ -568,7 +567,7 @@ char **App::get_command_line(unsigned int *out_argc) { delete[] arg; fclose(f); - wprintf(L"Error reading command."); + wprintf(L"Error reading command.\n"); return (fail_cl); } } diff --git a/platform/uwp/gl_context_egl.cpp b/platform/uwp/gl_context_egl.cpp index 88c9c8d687..6c60b27f5a 100644 --- a/platform/uwp/gl_context_egl.cpp +++ b/platform/uwp/gl_context_egl.cpp @@ -93,12 +93,26 @@ Error ContextEGL::initialize() { EGLint numConfigs = 0; EGLint majorVersion = 1; - EGLint minorVersion = 0; + EGLint minorVersion; + if (driver == GLES_2_0) { + minorVersion = 0; + } else { + minorVersion = 5; + } EGLDisplay display = EGL_NO_DISPLAY; EGLContext context = EGL_NO_CONTEXT; EGLSurface surface = EGL_NO_SURFACE; EGLConfig config = nullptr; - EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE, EGL_NONE }; + EGLint contextAttribs[3]; + if (driver == GLES_2_0) { + contextAttribs[0] = EGL_CONTEXT_CLIENT_VERSION; + contextAttribs[1] = 2; + contextAttribs[2] = EGL_NONE; + } else { + contextAttribs[0] = EGL_CONTEXT_CLIENT_VERSION; + contextAttribs[1] = 3; + contextAttribs[2] = EGL_NONE; + } try { @@ -114,7 +128,8 @@ Error ContextEGL::initialize() { // EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER is an optimization that can have large performance benefits on mobile devices. // Its syntax is subject to change, though. Please update your Visual Studio templates if you experience compilation issues with it. - //EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE, + EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, + EGL_TRUE, // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that enables ANGLE to automatically call // the IDXGIDevice3::Trim method on behalf of the application when it gets suspended. @@ -193,13 +208,12 @@ void ContextEGL::cleanup() { } }; -ContextEGL::ContextEGL(CoreWindow ^ p_window) : +ContextEGL::ContextEGL(CoreWindow ^ p_window, Driver p_driver) : mEglDisplay(EGL_NO_DISPLAY), mEglContext(EGL_NO_CONTEXT), - mEglSurface(EGL_NO_SURFACE) { - - window = p_window; -}; + mEglSurface(EGL_NO_SURFACE), + driver(p_driver), + window(p_window) {} ContextEGL::~ContextEGL() { diff --git a/platform/uwp/gl_context_egl.h b/platform/uwp/gl_context_egl.h index 527baf1054..df0108c124 100644 --- a/platform/uwp/gl_context_egl.h +++ b/platform/uwp/gl_context_egl.h @@ -42,6 +42,13 @@ using namespace Windows::UI::Core; class ContextEGL : public ContextGL { +public: + enum Driver { + GLES_2_0, + GLES_3_0, + }; + +private: CoreWindow ^ window; EGLDisplay mEglDisplay; @@ -53,6 +60,8 @@ class ContextEGL : public ContextGL { bool vsync; + Driver driver; + public: virtual void release_current(); @@ -70,7 +79,7 @@ public: void cleanup(); - ContextEGL(CoreWindow ^ p_window); + ContextEGL(CoreWindow ^ p_window, Driver p_driver); ~ContextEGL(); }; diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index d00da3dbcd..8cdd13df90 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -30,6 +30,7 @@ #include "os_uwp.h" +#include "drivers/gles2/rasterizer_gles2.h" #include "drivers/gles3/rasterizer_gles3.h" #include "drivers/unix/ip_unix.h" #include "drivers/windows/dir_access_windows.h" @@ -66,12 +67,7 @@ using namespace Windows::ApplicationModel::DataTransfer; using namespace concurrency; int OSUWP::get_video_driver_count() const { - - return 1; -} -const char *OSUWP::get_video_driver_name(int p_driver) const { - - return "GLES3"; + return 2; } Size2 OSUWP::get_window_size() const { @@ -133,18 +129,6 @@ void OSUWP::set_keep_screen_on(bool p_enabled) { OS::set_keep_screen_on(p_enabled); } -int OSUWP::get_audio_driver_count() const { - - return AudioDriverManager::get_driver_count(); -} - -const char *OSUWP::get_audio_driver_name(int p_driver) const { - - AudioDriver *driver = AudioDriverManager::get_driver(p_driver); - ERR_FAIL_COND_V(!driver, ""); - return AudioDriverManager::get_driver(p_driver)->get_name(); -} - void OSUWP::initialize_core() { last_button_state = 0; @@ -185,10 +169,9 @@ bool OSUWP::can_draw() const { return !minimized; }; -void OSUWP::set_gl_context(ContextEGL *p_context) { - - gl_context = p_context; -}; +void OSUWP::set_window(Windows::UI::Core::CoreWindow ^ p_window) { + window = p_window; +} void OSUWP::screen_size_changed() { @@ -200,6 +183,11 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au main_loop = NULL; outside = true; + if (p_video_driver == VIDEO_DRIVER_GLES2) { + gl_context = memnew(ContextEGL(window, ContextEGL::GLES_2_0)); + } else { + gl_context = memnew(ContextEGL(window, ContextEGL::GLES_3_0)); + } gl_context->initialize(); VideoMode vm; vm.width = gl_context->get_window_width(); @@ -240,8 +228,13 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au gl_context->make_current(); - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); + if (p_video_driver == VIDEO_DRIVER_GLES2) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + } else { + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + } gl_context->set_use_vsync(vm.use_vsync); visual_server = memnew(VisualServerRaster); diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index 95afdab469..0f7f068652 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -96,6 +96,7 @@ private: int pressrc; ContextEGL *gl_context; + Windows::UI::Core::CoreWindow ^ window; VideoMode video_mode; @@ -153,10 +154,6 @@ private: // functions used by main to initialize/deintialize the OS protected: virtual int get_video_driver_count() const; - virtual const char *get_video_driver_name(int p_driver) const; - - virtual int get_audio_driver_count() const; - virtual const char *get_audio_driver_name(int p_driver) const; virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); @@ -231,7 +228,7 @@ public: virtual bool _check_internal_feature_support(const String &p_feature); - void set_gl_context(ContextEGL *p_context); + void set_window(Windows::UI::Core::CoreWindow ^ p_window); void screen_size_changed(); virtual void release_rendering_thread(); diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index 216be1064a..05d16a5964 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -434,11 +434,12 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0; bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0; bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0; + bmask |= (wParam & MK_XBUTTON1) ? (1 << 7) : 0; + bmask |= (wParam & MK_XBUTTON2) ? (1 << 8) : 0; mm->set_button_mask(bmask); last_button_state = mm->get_button_mask(); - /*mm->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0; - mm->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/ + mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); @@ -495,153 +496,168 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: - /*case WM_XBUTTONDOWN: - case WM_XBUTTONUP: */ { - - Ref<InputEventMouseButton> mb; - mb.instance(); - - switch (uMsg) { - case WM_LBUTTONDOWN: { - mb->set_pressed(true); - mb->set_button_index(1); - } break; - case WM_LBUTTONUP: { - mb->set_pressed(false); - mb->set_button_index(1); - } break; - case WM_MBUTTONDOWN: { - mb->set_pressed(true); - mb->set_button_index(3); - - } break; - case WM_MBUTTONUP: { - mb->set_pressed(false); - mb->set_button_index(3); - } break; - case WM_RBUTTONDOWN: { - mb->set_pressed(true); - mb->set_button_index(2); - } break; - case WM_RBUTTONUP: { - mb->set_pressed(false); - mb->set_button_index(2); - } break; - case WM_LBUTTONDBLCLK: { - - mb->set_pressed(true); - mb->set_button_index(1); - mb->set_doubleclick(true); - } break; - case WM_RBUTTONDBLCLK: { - - mb->set_pressed(true); - mb->set_button_index(2); - mb->set_doubleclick(true); - } break; - case WM_MBUTTONDBLCLK: { - - mb->set_pressed(true); - mb->set_button_index(3); - mb->set_doubleclick(true); - } break; - case WM_MOUSEWHEEL: { - - mb->set_pressed(true); - int motion = (short)HIWORD(wParam); - if (!motion) - return 0; - - if (motion > 0) - mb->set_button_index(BUTTON_WHEEL_UP); - else - mb->set_button_index(BUTTON_WHEEL_DOWN); - - } break; - case WM_MOUSEHWHEEL: { - - mb->set_pressed(true); - int motion = (short)HIWORD(wParam); - if (!motion) - return 0; - - if (motion < 0) { - mb->set_button_index(BUTTON_WHEEL_LEFT); - mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); - } else { - mb->set_button_index(BUTTON_WHEEL_RIGHT); - mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); - } - } break; - /* - case WM_XBUTTONDOWN: { - mb->is_pressed()=true; - mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7; + case WM_XBUTTONDBLCLK: + case WM_XBUTTONDOWN: + case WM_XBUTTONUP: { + + Ref<InputEventMouseButton> mb; + mb.instance(); + + switch (uMsg) { + case WM_LBUTTONDOWN: { + mb->set_pressed(true); + mb->set_button_index(1); } break; - case WM_XBUTTONUP: - mb->is_pressed()=true; - mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7; - } break;*/ - default: { return 0; } - } + case WM_LBUTTONUP: { + mb->set_pressed(false); + mb->set_button_index(1); + } break; + case WM_MBUTTONDOWN: { + mb->set_pressed(true); + mb->set_button_index(3); - mb->set_control((wParam & MK_CONTROL) != 0); - mb->set_shift((wParam & MK_SHIFT) != 0); - mb->set_alt(alt_mem); - //mb->get_alt()=(wParam&MK_MENU)!=0; - int bmask = 0; - bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0; - bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0; - bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0; - mb->set_button_mask(bmask); - - last_button_state = mb->get_button_mask(); - /* - mb->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0; - mb->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/ - mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); - - if (mouse_mode == MOUSE_MODE_CAPTURED) { - - mb->set_position(Vector2(old_x, old_y)); - } + } break; + case WM_MBUTTONUP: { + mb->set_pressed(false); + mb->set_button_index(3); + } break; + case WM_RBUTTONDOWN: { + mb->set_pressed(true); + mb->set_button_index(2); + } break; + case WM_RBUTTONUP: { + mb->set_pressed(false); + mb->set_button_index(2); + } break; + case WM_LBUTTONDBLCLK: { - if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) { - if (mb->is_pressed()) { + mb->set_pressed(true); + mb->set_button_index(1); + mb->set_doubleclick(true); + } break; + case WM_RBUTTONDBLCLK: { - if (++pressrc > 0) - SetCapture(hWnd); - } else { + mb->set_pressed(true); + mb->set_button_index(2); + mb->set_doubleclick(true); + } break; + case WM_MBUTTONDBLCLK: { - if (--pressrc <= 0) { - ReleaseCapture(); - pressrc = 0; - } + mb->set_pressed(true); + mb->set_button_index(3); + mb->set_doubleclick(true); + } break; + case WM_MOUSEWHEEL: { + + mb->set_pressed(true); + int motion = (short)HIWORD(wParam); + if (!motion) + return 0; + + if (motion > 0) + mb->set_button_index(BUTTON_WHEEL_UP); + else + mb->set_button_index(BUTTON_WHEEL_DOWN); + + } break; + case WM_MOUSEHWHEEL: { + + mb->set_pressed(true); + int motion = (short)HIWORD(wParam); + if (!motion) + return 0; + + if (motion < 0) { + mb->set_button_index(BUTTON_WHEEL_LEFT); + mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); + } else { + mb->set_button_index(BUTTON_WHEEL_RIGHT); + mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); } - } else if (mouse_mode != MOUSE_MODE_CAPTURED) { - // for reasons unknown to mankind, wheel comes in screen cordinates - POINT coords; - coords.x = mb->get_position().x; - coords.y = mb->get_position().y; + } break; + case WM_XBUTTONDOWN: { + + mb->set_pressed(true); + if (HIWORD(wParam) == XBUTTON1) + mb->set_button_index(BUTTON_XBUTTON1); + else + mb->set_button_index(BUTTON_XBUTTON2); + } break; + case WM_XBUTTONUP: { - ScreenToClient(hWnd, &coords); + mb->set_pressed(false); + if (HIWORD(wParam) == XBUTTON1) + mb->set_button_index(BUTTON_XBUTTON1); + else + mb->set_button_index(BUTTON_XBUTTON2); + } break; + case WM_XBUTTONDBLCLK: { - mb->set_position(Vector2(coords.x, coords.y)); - } + mb->set_pressed(true); + if (HIWORD(wParam) == XBUTTON1) + mb->set_button_index(BUTTON_XBUTTON1); + else + mb->set_button_index(BUTTON_XBUTTON2); + mb->set_doubleclick(true); + } break; + default: { return 0; } + } + + mb->set_control((wParam & MK_CONTROL) != 0); + mb->set_shift((wParam & MK_SHIFT) != 0); + mb->set_alt(alt_mem); + //mb->get_alt()=(wParam&MK_MENU)!=0; + int bmask = 0; + bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0; + bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0; + bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0; + bmask |= (wParam & MK_XBUTTON1) ? (1 << 7) : 0; + bmask |= (wParam & MK_XBUTTON2) ? (1 << 8) : 0; + mb->set_button_mask(bmask); + + last_button_state = mb->get_button_mask(); + mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); - mb->set_global_position(mb->get_position()); + if (mouse_mode == MOUSE_MODE_CAPTURED) { + + mb->set_position(Vector2(old_x, old_y)); + } + + if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) { + if (mb->is_pressed()) { - if (main_loop) { - input->parse_input_event(mb); - if (mb->is_pressed() && mb->get_button_index() > 3) { - //send release for mouse wheel - Ref<InputEventMouseButton> mbd = mb->duplicate(); - mbd->set_pressed(false); - input->parse_input_event(mbd); + if (++pressrc > 0) + SetCapture(hWnd); + } else { + + if (--pressrc <= 0) { + ReleaseCapture(); + pressrc = 0; } } + } else if (mouse_mode != MOUSE_MODE_CAPTURED) { + // for reasons unknown to mankind, wheel comes in screen cordinates + POINT coords; + coords.x = mb->get_position().x; + coords.y = mb->get_position().y; + + ScreenToClient(hWnd, &coords); + + mb->set_position(Vector2(coords.x, coords.y)); + } + + mb->set_global_position(mb->get_position()); + + if (main_loop) { + input->parse_input_event(mb); + if (mb->is_pressed() && mb->get_button_index() > 3 && mb->get_button_index() < 8) { + //send release for mouse wheel + Ref<InputEventMouseButton> mbd = mb->duplicate(); + mbd->set_pressed(false); + input->parse_input_event(mbd); + } } - break; + } break; case WM_SIZE: { int window_w = LOWORD(lParam); diff --git a/scene/2d/audio_stream_player_2d.cpp b/scene/2d/audio_stream_player_2d.cpp index b6dfc666b0..507499a324 100644 --- a/scene/2d/audio_stream_player_2d.cpp +++ b/scene/2d/audio_stream_player_2d.cpp @@ -37,7 +37,7 @@ void AudioStreamPlayer2D::_mix_audio() { if (!stream_playback.is_valid() || !active || - (stream_paused && stream_paused_fade <= 0.f)) { + (stream_paused && !stream_paused_fade_out)) { return; } @@ -50,11 +50,13 @@ void AudioStreamPlayer2D::_mix_audio() { AudioFrame *buffer = mix_buffer.ptrw(); int buffer_size = mix_buffer.size(); - // Mix if we're not paused or we're fading out - if (!stream_paused || stream_paused_fade > 0.f) { - stream_playback->mix(buffer, pitch_scale, buffer_size); + if (stream_paused_fade_out) { + // Short fadeout ramp + buffer_size = MIN(buffer_size, 128); } + stream_playback->mix(buffer, pitch_scale, buffer_size); + //write all outputs for (int i = 0; i < output_count; i++) { @@ -82,15 +84,10 @@ void AudioStreamPlayer2D::_mix_audio() { } //mix! - AudioFrame vol_inc = (current.vol - prev_outputs[i].vol) / float(buffer_size); - AudioFrame vol = current.vol; - - if (stream_paused) { - vol = vol * stream_paused_fade; - if (stream_paused_fade > 0.f) { - stream_paused_fade -= 0.1f; - } - } + AudioFrame target_volume = stream_paused_fade_out ? AudioFrame(0.f, 0.f) : current.vol; + AudioFrame vol_prev = stream_paused_fade_in ? AudioFrame(0.f, 0.f) : prev_outputs[i].vol; + AudioFrame vol_inc = (target_volume - vol_prev) / float(buffer_size); + AudioFrame vol = stream_paused_fade_in ? AudioFrame(0.f, 0.f) : current.vol; int cc = AudioServer::get_singleton()->get_channel_count(); @@ -131,6 +128,8 @@ void AudioStreamPlayer2D::_mix_audio() { } output_ready = false; + stream_paused_fade_in = false; + stream_paused_fade_out = false; } void AudioStreamPlayer2D::_notification(int p_what) { @@ -305,6 +304,11 @@ float AudioStreamPlayer2D::get_pitch_scale() const { void AudioStreamPlayer2D::play(float p_from_pos) { + if (!is_playing()) { + // Reset the prev_output_count if the stream is stopped + prev_output_count = 0; + } + if (stream_playback.is_valid()) { setplay = p_from_pos; output_ready = false; @@ -439,7 +443,8 @@ void AudioStreamPlayer2D::set_stream_paused(bool p_pause) { if (p_pause != stream_paused) { stream_paused = p_pause; - stream_paused_fade = stream_paused ? 1.f : 0.f; + stream_paused_fade_in = p_pause ? false : true; + stream_paused_fade_out = p_pause ? true : false; } } @@ -518,7 +523,8 @@ AudioStreamPlayer2D::AudioStreamPlayer2D() { output_ready = false; area_mask = 1; stream_paused = false; - stream_paused_fade = 0.f; + stream_paused_fade_in = false; + stream_paused_fade_out = false; AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed"); } diff --git a/scene/2d/audio_stream_player_2d.h b/scene/2d/audio_stream_player_2d.h index b508de3171..e68e6eeca5 100644 --- a/scene/2d/audio_stream_player_2d.h +++ b/scene/2d/audio_stream_player_2d.h @@ -71,9 +71,10 @@ private: float volume_db; float pitch_scale; - float stream_paused_fade; bool autoplay; bool stream_paused; + bool stream_paused_fade_in; + bool stream_paused_fade_out; StringName bus; void _mix_audio(); diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp index 35c52a26c9..d46231a677 100644 --- a/scene/3d/audio_stream_player_3d.cpp +++ b/scene/3d/audio_stream_player_3d.cpp @@ -36,7 +36,7 @@ void AudioStreamPlayer3D::_mix_audio() { if (!stream_playback.is_valid() || !active || - (stream_paused && stream_paused_fade <= 0.f)) { + (stream_paused && !stream_paused_fade_out)) { return; } @@ -51,9 +51,13 @@ void AudioStreamPlayer3D::_mix_audio() { AudioFrame *buffer = mix_buffer.ptrw(); int buffer_size = mix_buffer.size(); + if (stream_paused_fade_out) { + // Short fadeout ramp + buffer_size = MIN(buffer_size, 128); + } + // Mix if we're not paused or we're fading out - if ((output_count > 0 || out_of_range_mode == OUT_OF_RANGE_MIX) && - (!stream_paused || stream_paused_fade > 0.f)) { + if ((output_count > 0 || out_of_range_mode == OUT_OF_RANGE_MIX)) { float output_pitch_scale = 0.0; if (output_count) { @@ -103,15 +107,10 @@ void AudioStreamPlayer3D::_mix_audio() { int buffers = AudioServer::get_singleton()->get_channel_count(); for (int k = 0; k < buffers; k++) { - AudioFrame vol_inc = (current.vol[k] - prev_outputs[i].vol[k]) / float(buffer_size); - AudioFrame vol = current.vol[k]; - - if (stream_paused) { - vol = vol * stream_paused_fade; - if (stream_paused_fade > 0.f) { - stream_paused_fade -= 0.1f; - } - } + AudioFrame target_volume = stream_paused_fade_out ? AudioFrame(0.f, 0.f) : current.vol[k]; + AudioFrame vol_prev = stream_paused_fade_in ? AudioFrame(0.f, 0.f) : prev_outputs[i].vol[k]; + AudioFrame vol_inc = (target_volume - vol_prev) / float(buffer_size); + AudioFrame vol = stream_paused_fade_in ? AudioFrame(0.f, 0.f) : current.vol[k]; AudioFrame *target = AudioServer::get_singleton()->thread_get_channel_mix_buffer(current.bus_index, k); @@ -193,6 +192,8 @@ void AudioStreamPlayer3D::_mix_audio() { } output_ready = false; + stream_paused_fade_in = false; + stream_paused_fade_out = false; } float AudioStreamPlayer3D::_get_attenuation_db(float p_distance) const { @@ -846,7 +847,8 @@ void AudioStreamPlayer3D::set_stream_paused(bool p_pause) { if (p_pause != stream_paused) { stream_paused = p_pause; - stream_paused_fade = stream_paused ? 1.f : 0.f; + stream_paused_fade_in = stream_paused ? false : true; + stream_paused_fade_out = stream_paused ? true : false; } } @@ -984,7 +986,8 @@ AudioStreamPlayer3D::AudioStreamPlayer3D() { out_of_range_mode = OUT_OF_RANGE_MIX; doppler_tracking = DOPPLER_TRACKING_DISABLED; stream_paused = false; - stream_paused_fade = 0.f; + stream_paused_fade_in = false; + stream_paused_fade_out = false; velocity_tracker.instance(); AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed"); diff --git a/scene/3d/audio_stream_player_3d.h b/scene/3d/audio_stream_player_3d.h index cab1ff121a..14413d0702 100644 --- a/scene/3d/audio_stream_player_3d.h +++ b/scene/3d/audio_stream_player_3d.h @@ -107,9 +107,10 @@ private: float unit_size; float max_db; float pitch_scale; - float stream_paused_fade; bool autoplay; bool stream_paused; + bool stream_paused_fade_in; + bool stream_paused_fade_out; StringName bus; void _mix_audio(); diff --git a/scene/audio/audio_player.cpp b/scene/audio/audio_player.cpp index 40ec04e479..863b278b62 100644 --- a/scene/audio/audio_player.cpp +++ b/scene/audio/audio_player.cpp @@ -41,30 +41,22 @@ void AudioStreamPlayer::_mix_internal(bool p_fadeout) { int buffer_size = mix_buffer.size(); if (p_fadeout) { - buffer_size = MIN(buffer_size, 16); //short fadeout ramp + // Short fadeout ramp + buffer_size = MIN(buffer_size, 128); } - // Mix if we're not paused or we're fading out - if (!stream_paused || stream_paused_fade > 0.f) { - stream_playback->mix(buffer, pitch_scale, buffer_size); - } + stream_playback->mix(buffer, pitch_scale, buffer_size); //multiply volume interpolating to avoid clicks if this changes float target_volume = p_fadeout ? -80.0 : volume_db; float vol = Math::db2linear(mix_volume_db); float vol_inc = (Math::db2linear(target_volume) - vol) / float(buffer_size); - if (stream_paused) { - vol = vol * stream_paused_fade; - if (stream_paused_fade > 0.f) { - stream_paused_fade -= 0.1f; - } - } - for (int i = 0; i < buffer_size; i++) { buffer[i] *= vol; vol += vol_inc; } + //set volume for next mix mix_volume_db = target_volume; @@ -99,8 +91,14 @@ void AudioStreamPlayer::_mix_internal(bool p_fadeout) { void AudioStreamPlayer::_mix_audio() { - if (!stream_playback.is_valid() || !active || - (stream_paused && stream_paused_fade <= 0.f)) { + if (!stream_playback.is_valid() || !active) + return; + + if (stream_paused) { + if (stream_paused_fade) { + _mix_internal(true); + stream_paused_fade = false; + } return; } @@ -295,7 +293,7 @@ void AudioStreamPlayer::set_stream_paused(bool p_pause) { if (p_pause != stream_paused) { stream_paused = p_pause; - stream_paused_fade = stream_paused ? 1.f : 0.f; + stream_paused_fade = p_pause ? true : false; } } @@ -385,7 +383,7 @@ AudioStreamPlayer::AudioStreamPlayer() { setseek = -1; active = false; stream_paused = false; - stream_paused_fade = 0.f; + stream_paused_fade = false; mix_target = MIX_TARGET_STEREO; AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed"); diff --git a/scene/audio/audio_player.h b/scene/audio/audio_player.h index c42f191589..591c00ed18 100644 --- a/scene/audio/audio_player.h +++ b/scene/audio/audio_player.h @@ -56,9 +56,9 @@ private: float mix_volume_db; float pitch_scale; float volume_db; - float stream_paused_fade; bool autoplay; bool stream_paused; + bool stream_paused_fade; StringName bus; MixTarget mix_target; diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp index f8c188d33d..8e232c6f46 100644 --- a/scene/gui/color_picker.cpp +++ b/scene/gui/color_picker.cpp @@ -743,8 +743,9 @@ ColorPicker *ColorPickerButton::get_picker() { return picker; } -PopupPanel *ColorPickerButton::get_popup() const { +PopupPanel *ColorPickerButton::get_popup() { + _update_picker(); return popup; } diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h index c8d8e1aa8a..0166da7118 100644 --- a/scene/gui/color_picker.h +++ b/scene/gui/color_picker.h @@ -144,7 +144,7 @@ public: bool is_editing_alpha() const; ColorPicker *get_picker(); - PopupPanel *get_popup() const; + PopupPanel *get_popup(); ColorPickerButton(); }; diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp index c5e4149782..2901176a69 100644 --- a/scene/gui/option_button.cpp +++ b/scene/gui/option_button.cpp @@ -36,7 +36,7 @@ Size2 OptionButton::get_minimum_size() const { Size2 minsize = Button::get_minimum_size(); if (has_icon("arrow")) - minsize.width += Control::get_icon("arrow")->get_width(); + minsize.width += Control::get_icon("arrow")->get_width() + get_constant("hseparation"); return minsize; } diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp index 18e609c798..ebec61ee6d 100644 --- a/scene/gui/popup_menu.cpp +++ b/scene/gui/popup_menu.cpp @@ -398,6 +398,15 @@ void PopupMenu::_notification(int p_what) { switch (p_what) { + case NOTIFICATION_ENTER_TREE: { + + PopupMenu *pm = Object::cast_to<PopupMenu>(get_parent()); + if (pm) { + // Inherit submenu's popup delay time from parent menu + float pm_delay = pm->get_submenu_popup_delay(); + set_submenu_popup_delay(pm_delay); + } + } break; case NOTIFICATION_TRANSLATION_CHANGED: { for (int i = 0; i < items.size(); i++) { @@ -421,6 +430,8 @@ void PopupMenu::_notification(int p_what) { Ref<Texture> uncheck[] = { get_icon("unchecked"), get_icon("radio_unchecked") }; Ref<Texture> submenu = get_icon("submenu"); Ref<StyleBox> separator = get_stylebox("separator"); + Ref<StyleBox> labeled_separator_left = get_stylebox("labeled_separator_left"); + Ref<StyleBox> labeled_separator_right = get_stylebox("labeled_separator_right"); style->draw(ci, Rect2(Point2(), get_size())); Point2 ofs = style->get_offset(); @@ -457,10 +468,25 @@ void PopupMenu::_notification(int p_what) { hover->draw(ci, Rect2(item_ofs + Point2(-hseparation, -vseparation / 2), Size2(get_size().width - style->get_minimum_size().width + hseparation * 2, h + vseparation))); } + String text = items[i].shortcut.is_valid() ? String(tr(items[i].shortcut->get_name())) : items[i].xl_text; + if (items[i].separator) { int sep_h = separator->get_center_size().height + separator->get_minimum_size().height; - separator->draw(ci, Rect2(item_ofs + Point2(0, Math::floor((h - sep_h) / 2.0)), Size2(get_size().width - style->get_minimum_size().width, sep_h))); + if (text != String()) { + int ss = font->get_string_size(text).width; + int center = (get_size().width) / 2; + int l = center - ss / 2; + int r = center + ss / 2; + if (l > item_ofs.x) { + labeled_separator_left->draw(ci, Rect2(item_ofs + Point2(0, Math::floor((h - sep_h) / 2.0)), Size2(MAX(0, l - item_ofs.x), sep_h))); + } + if (r < get_size().width - style->get_margin(MARGIN_RIGHT)) { + labeled_separator_right->draw(ci, Rect2(Point2(r, item_ofs.y + Math::floor((h - sep_h) / 2.0)), Size2(MAX(0, get_size().width - style->get_margin(MARGIN_RIGHT) - r), sep_h))); + } + } else { + separator->draw(ci, Rect2(item_ofs + Point2(0, Math::floor((h - sep_h) / 2.0)), Size2(get_size().width - style->get_minimum_size().width, sep_h))); + } } if (items[i].checkable_type) { @@ -480,8 +506,13 @@ void PopupMenu::_notification(int p_what) { } item_ofs.y += font->get_ascent(); - String text = items[i].shortcut.is_valid() ? String(tr(items[i].shortcut->get_name())) : items[i].xl_text; - if (!items[i].separator) { + if (items[i].separator) { + + if (text != String()) { + int center = (get_size().width - font->get_string_size(text).width) / 2; + font->draw(ci, Point2(center, item_ofs.y + Math::floor((h - font_h) / 2.0)), text, font_color_disabled); + } + } else { font->draw(ci, item_ofs + Point2(0, Math::floor((h - font_h) / 2.0)), text, items[i].disabled ? font_color_disabled : (i == mouse_over ? font_color_hover : font_color)); } @@ -1064,11 +1095,15 @@ void PopupMenu::remove_item(int p_idx) { update(); } -void PopupMenu::add_separator() { +void PopupMenu::add_separator(const String &p_text) { Item sep; sep.separator = true; sep.ID = -1; + if (p_text != String()) { + sep.text = p_text; + sep.xl_text = tr(p_text); + } items.push_back(sep); update(); } @@ -1201,6 +1236,19 @@ bool PopupMenu::is_hide_on_multistate_item_selection() const { return hide_on_multistate_item_selection; } +void PopupMenu::set_submenu_popup_delay(float p_time) { + + if (p_time <= 0) + p_time = 0.01; + + submenu_timer->set_wait_time(p_time); +} + +float PopupMenu::get_submenu_popup_delay() const { + + return submenu_timer->get_wait_time(); +} + String PopupMenu::get_tooltip(const Point2 &p_pos) const { int over = _get_mouse_over(p_pos); @@ -1288,7 +1336,7 @@ void PopupMenu::_bind_methods() { ClassDB::bind_method(D_METHOD("remove_item", "idx"), &PopupMenu::remove_item); - ClassDB::bind_method(D_METHOD("add_separator"), &PopupMenu::add_separator); + ClassDB::bind_method(D_METHOD("add_separator", "label"), &PopupMenu::add_separator, DEFVAL(String())); ClassDB::bind_method(D_METHOD("clear"), &PopupMenu::clear); ClassDB::bind_method(D_METHOD("_set_items"), &PopupMenu::_set_items); @@ -1303,12 +1351,15 @@ void PopupMenu::_bind_methods() { ClassDB::bind_method(D_METHOD("set_hide_on_state_item_selection", "enable"), &PopupMenu::set_hide_on_multistate_item_selection); ClassDB::bind_method(D_METHOD("is_hide_on_state_item_selection"), &PopupMenu::is_hide_on_multistate_item_selection); + ClassDB::bind_method(D_METHOD("set_submenu_popup_delay", "seconds"), &PopupMenu::set_submenu_popup_delay); + ClassDB::bind_method(D_METHOD("get_submenu_popup_delay"), &PopupMenu::get_submenu_popup_delay); ClassDB::bind_method(D_METHOD("_submenu_timeout"), &PopupMenu::_submenu_timeout); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_items", "_get_items"); ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "hide_on_item_selection"), "set_hide_on_item_selection", "is_hide_on_item_selection"); ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "hide_on_checkable_item_selection"), "set_hide_on_checkable_item_selection", "is_hide_on_checkable_item_selection"); ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "hide_on_state_item_selection"), "set_hide_on_state_item_selection", "is_hide_on_state_item_selection"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "submenu_popup_delay"), "set_submenu_popup_delay", "get_submenu_popup_delay"); ADD_SIGNAL(MethodInfo("id_pressed", PropertyInfo(Variant::INT, "ID"))); ADD_SIGNAL(MethodInfo("id_focused", PropertyInfo(Variant::INT, "ID"))); diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h index d3ee9be1c0..8ec51c7d3a 100644 --- a/scene/gui/popup_menu.h +++ b/scene/gui/popup_menu.h @@ -180,7 +180,7 @@ public: void remove_item(int p_idx); - void add_separator(); + void add_separator(const String &p_text = String()); void clear(); @@ -202,6 +202,9 @@ public: void set_hide_on_multistate_item_selection(bool p_enabled); bool is_hide_on_multistate_item_selection() const; + void set_submenu_popup_delay(float p_time); + float get_submenu_popup_delay() const; + virtual void popup(const Rect2 &p_bounds = Rect2()); PopupMenu(); diff --git a/scene/gui/slider.cpp b/scene/gui/slider.cpp index 46215c9277..b820e2eafd 100644 --- a/scene/gui/slider.cpp +++ b/scene/gui/slider.cpp @@ -65,11 +65,12 @@ void Slider::_gui_input(Ref<InputEvent> p_event) { } else { grab.active = false; } - } else if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_UP) { - - set_value(get_value() + get_step()); - } else if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_DOWN) { - set_value(get_value() - get_step()); + } else if (scrollable) { + if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_UP) { + set_value(get_value() + get_step()); + } else if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_DOWN) { + set_value(get_value() - get_step()); + } } } @@ -247,6 +248,16 @@ bool Slider::is_editable() const { return editable; } +void Slider::set_scrollable(bool p_scrollable) { + + scrollable = p_scrollable; +} + +bool Slider::is_scrollable() const { + + return scrollable; +} + void Slider::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &Slider::_gui_input); @@ -258,8 +269,11 @@ void Slider::_bind_methods() { ClassDB::bind_method(D_METHOD("set_editable", "editable"), &Slider::set_editable); ClassDB::bind_method(D_METHOD("is_editable"), &Slider::is_editable); + ClassDB::bind_method(D_METHOD("set_scrollable", "scrollable"), &Slider::set_scrollable); + ClassDB::bind_method(D_METHOD("is_scrollable"), &Slider::is_scrollable); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scrollable"), "set_scrollable", "is_scrollable"); ADD_PROPERTY(PropertyInfo(Variant::INT, "tick_count", PROPERTY_HINT_RANGE, "0,4096,1"), "set_ticks", "get_ticks"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ticks_on_borders"), "set_ticks_on_borders", "get_ticks_on_borders"); ADD_PROPERTY(PropertyInfo(Variant::INT, "focus_mode", PROPERTY_HINT_ENUM, "None,Click,All"), "set_focus_mode", "get_focus_mode"); @@ -272,5 +286,6 @@ Slider::Slider(Orientation p_orientation) { ticks = 0; custom_step = -1; editable = true; + scrollable = true; set_focus_mode(FOCUS_ALL); } diff --git a/scene/gui/slider.h b/scene/gui/slider.h index e77a0b7423..4d02348159 100644 --- a/scene/gui/slider.h +++ b/scene/gui/slider.h @@ -48,6 +48,7 @@ class Slider : public Range { Orientation orientation; float custom_step; bool editable; + bool scrollable; protected: void _gui_input(Ref<InputEvent> p_event); @@ -70,6 +71,9 @@ public: void set_editable(bool p_editable); bool is_editable() const; + void set_scrollable(bool p_scrollable); + bool is_scrollable() const; + Slider(Orientation p_orientation = VERTICAL); }; diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index f42c1e0982..2064bf9b04 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -135,6 +135,7 @@ #include "scene/resources/concave_polygon_shape_2d.h" #include "scene/resources/convex_polygon_shape.h" #include "scene/resources/convex_polygon_shape_2d.h" +#include "scene/resources/cylinder_shape.h" #include "scene/resources/default_theme/default_theme.h" #include "scene/resources/dynamic_font.h" #include "scene/resources/dynamic_font_stb.h" @@ -158,6 +159,8 @@ #include "scene/resources/texture.h" #include "scene/resources/tile_set.h" #include "scene/resources/video_stream.h" +#include "scene/resources/visual_shader.h" +#include "scene/resources/visual_shader_nodes.h" #include "scene/resources/world.h" #include "scene/resources/world_2d.h" #include "scene/scene_string_names.h" @@ -455,6 +458,39 @@ void register_scene_types() { AcceptDialog::set_swap_ok_cancel(GLOBAL_DEF("gui/common/swap_ok_cancel", bool(OS::get_singleton()->get_swap_ok_cancel()))); ClassDB::register_class<Shader>(); + ClassDB::register_class<VisualShader>(); + ClassDB::register_virtual_class<VisualShaderNode>(); + ClassDB::register_class<VisualShaderNodeInput>(); + ClassDB::register_virtual_class<VisualShaderNodeOutput>(); + ClassDB::register_class<VisualShaderNodeScalarConstant>(); + ClassDB::register_class<VisualShaderNodeColorConstant>(); + ClassDB::register_class<VisualShaderNodeVec3Constant>(); + ClassDB::register_class<VisualShaderNodeTransformConstant>(); + ClassDB::register_class<VisualShaderNodeScalarOp>(); + ClassDB::register_class<VisualShaderNodeVectorOp>(); + ClassDB::register_class<VisualShaderNodeColorOp>(); + ClassDB::register_class<VisualShaderNodeTransformMult>(); + ClassDB::register_class<VisualShaderNodeTransformVecMult>(); + ClassDB::register_class<VisualShaderNodeScalarFunc>(); + ClassDB::register_class<VisualShaderNodeVectorFunc>(); + ClassDB::register_class<VisualShaderNodeDotProduct>(); + ClassDB::register_class<VisualShaderNodeVectorLen>(); + ClassDB::register_class<VisualShaderNodeScalarInterp>(); + ClassDB::register_class<VisualShaderNodeVectorInterp>(); + ClassDB::register_class<VisualShaderNodeVectorConstruct>(); + ClassDB::register_class<VisualShaderNodeTransformConstruct>(); + ClassDB::register_class<VisualShaderNodeVectorDestruct>(); + ClassDB::register_class<VisualShaderNodeTransformDestruct>(); + ClassDB::register_class<VisualShaderNodeTexture>(); + ClassDB::register_class<VisualShaderNodeCubeMap>(); + ClassDB::register_virtual_class<VisualShaderNodeUniform>(); + ClassDB::register_class<VisualShaderNodeScalarUniform>(); + ClassDB::register_class<VisualShaderNodeColorUniform>(); + ClassDB::register_class<VisualShaderNodeVec3Uniform>(); + ClassDB::register_class<VisualShaderNodeTransformUniform>(); + ClassDB::register_class<VisualShaderNodeTextureUniform>(); + ClassDB::register_class<VisualShaderNodeCubeMapUniform>(); + ClassDB::register_class<ShaderMaterial>(); ClassDB::register_virtual_class<CanvasItem>(); ClassDB::register_class<CanvasItemMaterial>(); @@ -541,6 +577,7 @@ void register_scene_types() { ClassDB::register_class<SphereShape>(); ClassDB::register_class<BoxShape>(); ClassDB::register_class<CapsuleShape>(); + ClassDB::register_class<CylinderShape>(); ClassDB::register_class<PlaneShape>(); ClassDB::register_class<ConvexPolygonShape>(); ClassDB::register_class<ConcavePolygonShape>(); diff --git a/scene/resources/cylinder_shape.cpp b/scene/resources/cylinder_shape.cpp new file mode 100644 index 0000000000..f760462d49 --- /dev/null +++ b/scene/resources/cylinder_shape.cpp @@ -0,0 +1,116 @@ +/*************************************************************************/ +/* cylinder_shape.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "cylinder_shape.h" +#include "servers/physics_server.h" + +Vector<Vector3> CylinderShape::_gen_debug_mesh_lines() { + + float radius = get_radius(); + float height = get_height(); + + Vector<Vector3> points; + + Vector3 d(0, height * 0.5, 0); + for (int i = 0; i < 360; i++) { + + float ra = Math::deg2rad((float)i); + float rb = Math::deg2rad((float)i + 1); + Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius; + Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius; + + points.push_back(Vector3(a.x, 0, a.y) + d); + points.push_back(Vector3(b.x, 0, b.y) + d); + + points.push_back(Vector3(a.x, 0, a.y) - d); + points.push_back(Vector3(b.x, 0, b.y) - d); + + if (i % 90 == 0) { + + points.push_back(Vector3(a.x, 0, a.y) + d); + points.push_back(Vector3(a.x, 0, a.y) - d); + } + } + + return points; +} + +void CylinderShape::_update_shape() { + + Dictionary d; + d["radius"] = radius; + d["height"] = height; + PhysicsServer::get_singleton()->shape_set_data(get_shape(), d); +} + +void CylinderShape::set_radius(float p_radius) { + + radius = p_radius; + _update_shape(); + notify_change_to_owners(); + _change_notify("radius"); +} + +float CylinderShape::get_radius() const { + + return radius; +} + +void CylinderShape::set_height(float p_height) { + + height = p_height; + _update_shape(); + notify_change_to_owners(); + _change_notify("height"); +} + +float CylinderShape::get_height() const { + + return height; +} + +void CylinderShape::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CylinderShape::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &CylinderShape::get_radius); + ClassDB::bind_method(D_METHOD("set_height", "height"), &CylinderShape::set_height); + ClassDB::bind_method(D_METHOD("get_height"), &CylinderShape::get_height); + + ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_radius", "get_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_height", "get_height"); +} + +CylinderShape::CylinderShape() : + Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CYLINDER)) { + + radius = 1.0; + height = 2.0; + _update_shape(); +} diff --git a/scene/resources/cylinder_shape.h b/scene/resources/cylinder_shape.h new file mode 100644 index 0000000000..f510758e91 --- /dev/null +++ b/scene/resources/cylinder_shape.h @@ -0,0 +1,57 @@ +/*************************************************************************/ +/* cylinder_shape.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef CYLINDER_SHAPE_H +#define CYLINDER_SHAPE_H + +#include "scene/resources/shape.h" + +class CylinderShape : public Shape { + + GDCLASS(CylinderShape, Shape); + float radius; + float height; + +protected: + static void _bind_methods(); + virtual void _update_shape(); + + virtual Vector<Vector3> _gen_debug_mesh_lines(); + +public: + void set_radius(float p_radius); + float get_radius() const; + void set_height(float p_height); + float get_height() const; + + CylinderShape(); +}; + +#endif // CYLINDER_SHAPE_H diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp index 702953fa40..d4432b969f 100644 --- a/scene/resources/default_theme/default_theme.cpp +++ b/scene/resources/default_theme/default_theme.cpp @@ -585,6 +585,8 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const theme->set_stylebox("panel_disabled", "PopupMenu", make_stylebox(popup_bg_disabled_png, 4, 4, 4, 4)); theme->set_stylebox("hover", "PopupMenu", selected); theme->set_stylebox("separator", "PopupMenu", make_stylebox(vseparator_png, 3, 3, 3, 3)); + theme->set_stylebox("labeled_separator_left", "PopupMenu", make_stylebox(vseparator_png, 0, 0, 0, 0)); + theme->set_stylebox("labeled_separator_right", "PopupMenu", make_stylebox(vseparator_png, 0, 0, 0, 0)); theme->set_icon("checked", "PopupMenu", make_icon(checked_png)); theme->set_icon("unchecked", "PopupMenu", make_icon(unchecked_png)); diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp index 654d7b884e..90e103c96b 100644 --- a/scene/resources/material.cpp +++ b/scene/resources/material.cpp @@ -145,11 +145,17 @@ void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const { void ShaderMaterial::set_shader(const Ref<Shader> &p_shader) { + if (shader.is_valid()) { + shader->disconnect("changed", this, "_shader_changed"); + } + shader = p_shader; RID rid; - if (shader.is_valid()) + if (shader.is_valid()) { rid = shader->get_rid(); + shader->connect("changed", this, "_shader_changed"); + } VS::get_singleton()->material_set_shader(_get_material(), rid); _change_notify(); //properties for shader exposed @@ -171,12 +177,17 @@ Variant ShaderMaterial::get_shader_param(const StringName &p_param) const { return VS::get_singleton()->material_get_param(_get_material(), p_param); } +void ShaderMaterial::_shader_changed() { + _change_notify(); //update all properties +} + void ShaderMaterial::_bind_methods() { ClassDB::bind_method(D_METHOD("set_shader", "shader"), &ShaderMaterial::set_shader); ClassDB::bind_method(D_METHOD("get_shader"), &ShaderMaterial::get_shader); ClassDB::bind_method(D_METHOD("set_shader_param", "param", "value"), &ShaderMaterial::set_shader_param); ClassDB::bind_method(D_METHOD("get_shader_param", "param"), &ShaderMaterial::get_shader_param); + ClassDB::bind_method(D_METHOD("_shader_changed"), &ShaderMaterial::_shader_changed); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, "Shader"), "set_shader", "get_shader"); } diff --git a/scene/resources/material.h b/scene/resources/material.h index 87594213bc..3b9d1be260 100644 --- a/scene/resources/material.h +++ b/scene/resources/material.h @@ -92,6 +92,8 @@ protected: virtual bool _can_do_next_pass() const; + void _shader_changed(); + public: void set_shader(const Ref<Shader> &p_shader); Ref<Shader> get_shader() const; diff --git a/scene/resources/scene_format_text.cpp b/scene/resources/scene_format_text.cpp index 597866eb74..9df117d09c 100644 --- a/scene/resources/scene_format_text.cpp +++ b/scene/resources/scene_format_text.cpp @@ -896,7 +896,7 @@ static void bs_save_unicode_string(FileAccess *f, const String &p_string, bool p CharString utf8 = p_string.utf8(); if (p_bit_on_len) { - f->store_32(utf8.length() + 1 | 0x80000000); + f->store_32((utf8.length() + 1) | 0x80000000); } else { f->store_32(utf8.length() + 1); } diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp index 36740a307b..f53f03c1c8 100644 --- a/scene/resources/shader.cpp +++ b/scene/resources/shader.cpp @@ -54,16 +54,20 @@ void Shader::set_code(const String &p_code) { VisualServer::get_singleton()->shader_set_code(shader, p_code); params_cache_dirty = true; - emit_signal(SceneStringNames::get_singleton()->changed); + + emit_changed(); } String Shader::get_code() const { + _update_shader(); return VisualServer::get_singleton()->shader_get_code(shader); } void Shader::get_param_list(List<PropertyInfo> *p_params) const { + _update_shader(); + List<PropertyInfo> local; VisualServer::get_singleton()->shader_get_param_list(shader, &local); params_cache.clear(); @@ -72,6 +76,9 @@ void Shader::get_param_list(List<PropertyInfo> *p_params) const { for (List<PropertyInfo>::Element *E = local.front(); E; E = E->next()) { PropertyInfo pi = E->get(); + if (default_textures.has(pi.name)) { //do not show default textures + continue; + } pi.name = "shader_param/" + pi.name; params_cache[pi.name] = E->get().name; if (p_params) { @@ -86,6 +93,8 @@ void Shader::get_param_list(List<PropertyInfo> *p_params) const { RID Shader::get_rid() const { + _update_shader(); + return shader; } @@ -98,6 +107,8 @@ void Shader::set_default_texture_param(const StringName &p_param, const Ref<Text default_textures.erase(p_param); VS::get_singleton()->shader_set_default_texture_param(shader, p_param, RID()); } + + emit_changed(); } Ref<Texture> Shader::get_default_texture_param(const StringName &p_param) const { @@ -120,6 +131,9 @@ bool Shader::has_param(const StringName &p_param) const { return params_cache.has(p_param); } +void Shader::_update_shader() const { +} + void Shader::_bind_methods() { ClassDB::bind_method(D_METHOD("get_mode"), &Shader::get_mode); @@ -227,5 +241,5 @@ void ResourceFormatSaverShader::get_recognized_extensions(const RES &p_resource, } bool ResourceFormatSaverShader::recognize(const RES &p_resource) const { - return Object::cast_to<Shader>(*p_resource) != NULL; + return p_resource->get_class_name() == "Shader"; //only shader, not inherited } diff --git a/scene/resources/shader.h b/scene/resources/shader.h index 248a6f0125..efc5da7753 100644 --- a/scene/resources/shader.h +++ b/scene/resources/shader.h @@ -61,12 +61,13 @@ private: mutable Map<StringName, StringName> params_cache; //map a shader param to a material param.. Map<StringName, Ref<Texture> > default_textures; + virtual void _update_shader() const; //used for visual shader protected: static void _bind_methods(); public: //void set_mode(Mode p_mode); - Mode get_mode() const; + virtual Mode get_mode() const; void set_code(const String &p_code); String get_code() const; diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp index ebad00b068..fb81375b0a 100644 --- a/scene/resources/style_box.cpp +++ b/scene/resources/style_box.cpp @@ -905,12 +905,20 @@ bool StyleBoxLine::is_vertical() const { return vertical; } -void StyleBoxLine::set_grow(float p_grow) { - grow = p_grow; +void StyleBoxLine::set_grow_end(float p_grow_end) { + grow_end = p_grow_end; emit_changed(); } -float StyleBoxLine::get_grow() const { - return grow; +float StyleBoxLine::get_grow_end() const { + return grow_end; +} + +void StyleBoxLine::set_grow_begin(float p_grow_begin) { + grow_begin = p_grow_begin; + emit_changed(); +} +float StyleBoxLine::get_grow_begin() const { + return grow_begin; } void StyleBoxLine::_bind_methods() { @@ -919,13 +927,16 @@ void StyleBoxLine::_bind_methods() { ClassDB::bind_method(D_METHOD("get_color"), &StyleBoxLine::get_color); ClassDB::bind_method(D_METHOD("set_thickness", "thickness"), &StyleBoxLine::set_thickness); ClassDB::bind_method(D_METHOD("get_thickness"), &StyleBoxLine::get_thickness); - ClassDB::bind_method(D_METHOD("set_grow", "grow"), &StyleBoxLine::set_grow); - ClassDB::bind_method(D_METHOD("get_grow"), &StyleBoxLine::get_grow); + ClassDB::bind_method(D_METHOD("set_grow_begin", "offset"), &StyleBoxLine::set_grow_begin); + ClassDB::bind_method(D_METHOD("get_grow_begin"), &StyleBoxLine::get_grow_begin); + ClassDB::bind_method(D_METHOD("set_grow_end", "offset"), &StyleBoxLine::set_grow_end); + ClassDB::bind_method(D_METHOD("get_grow_end"), &StyleBoxLine::get_grow_end); ClassDB::bind_method(D_METHOD("set_vertical", "vertical"), &StyleBoxLine::set_vertical); ClassDB::bind_method(D_METHOD("is_vertical"), &StyleBoxLine::is_vertical); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); - ADD_PROPERTY(PropertyInfo(Variant::REAL, "grow", PROPERTY_HINT_RANGE, "-300,300,1"), "set_grow", "get_grow"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "grow_begin", PROPERTY_HINT_RANGE, "-300,300,1"), "set_grow_begin", "get_grow_begin"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "grow_end", PROPERTY_HINT_RANGE, "-300,300,1"), "set_grow_end", "get_grow_end"); ADD_PROPERTY(PropertyInfo(Variant::INT, "thickness", PROPERTY_HINT_RANGE, "0,10"), "set_thickness", "get_thickness"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "vertical"), "set_vertical", "is_vertical"); } @@ -941,12 +952,12 @@ void StyleBoxLine::draw(RID p_canvas_item, const Rect2 &p_rect) const { Rect2i r = p_rect; if (vertical) { - r.position.y -= grow; - r.size.y += grow * 2; + r.position.y -= grow_begin; + r.size.y += (grow_begin + grow_end); r.size.x = thickness; } else { - r.position.x -= grow; - r.size.x += grow * 2; + r.position.x -= grow_begin; + r.size.x += (grow_begin + grow_end); r.size.y = thickness; } @@ -954,7 +965,8 @@ void StyleBoxLine::draw(RID p_canvas_item, const Rect2 &p_rect) const { } StyleBoxLine::StyleBoxLine() { - grow = 1.0; + grow_begin = 1.0; + grow_end = 1.0; thickness = 1; color = Color(0.0, 0.0, 0.0); vertical = false; diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h index c1d84fe19f..ed193a1ab4 100644 --- a/scene/resources/style_box.h +++ b/scene/resources/style_box.h @@ -236,7 +236,8 @@ class StyleBoxLine : public StyleBox { Color color; int thickness; bool vertical; - float grow; + float grow_begin; + float grow_end; protected: virtual float get_style_margin(Margin p_margin) const; @@ -252,8 +253,11 @@ public: void set_vertical(bool p_vertical); bool is_vertical() const; - void set_grow(float p_grow); - float get_grow() const; + void set_grow_begin(float p_grow); + float get_grow_begin() const; + + void set_grow_end(float p_grow); + float get_grow_end() const; virtual Size2 get_center_size() const; diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp new file mode 100644 index 0000000000..b7b7802d1b --- /dev/null +++ b/scene/resources/visual_shader.cpp @@ -0,0 +1,1555 @@ +#include "visual_shader.h" +#include "servers/visual/shader_types.h" +#include "vmap.h" + +void VisualShaderNode::set_output_port_for_preview(int p_index) { + + port_preview = p_index; +} + +int VisualShaderNode::get_output_port_for_preview() const { + + return port_preview; +} + +void VisualShaderNode::set_input_port_default_value(int p_port, const Variant &p_value) { + default_input_values[p_port] = p_value; + emit_changed(); +} + +Variant VisualShaderNode::get_input_port_default_value(int p_port) const { + if (default_input_values.has(p_port)) { + return default_input_values[p_port]; + } + + return Variant(); +} + +bool VisualShaderNode::is_port_separator(int p_index) const { + return false; +} + +Vector<VisualShader::DefaultTextureParam> VisualShaderNode::get_default_texture_parameters(VisualShader::Type p_type, int p_id) const { + return Vector<VisualShader::DefaultTextureParam>(); +} +String VisualShaderNode::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + return String(); +} + +Vector<StringName> VisualShaderNode::get_editable_properties() const { + return Vector<StringName>(); +} + +Array VisualShaderNode::_get_default_input_values() const { + + Array ret; + for (Map<int, Variant>::Element *E = default_input_values.front(); E; E = E->next()) { + ret.push_back(E->key()); + ret.push_back(E->get()); + } + return ret; +} +void VisualShaderNode::_set_default_input_values(const Array &p_values) { + + if (p_values.size() % 2 == 0) { + for (int i = 0; i < p_values.size(); i += 2) { + default_input_values[p_values[i + 0]] = p_values[i + 1]; + } + } + + emit_changed(); +} + +String VisualShaderNode::get_warning(Shader::Mode p_mode, VisualShader::Type p_type) const { + return String(); +} + +void VisualShaderNode::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_output_port_for_preview", "port"), &VisualShaderNode::set_output_port_for_preview); + ClassDB::bind_method(D_METHOD("get_output_port_for_preview"), &VisualShaderNode::get_output_port_for_preview); + + ClassDB::bind_method(D_METHOD("set_input_port_default_value", "port", "value"), &VisualShaderNode::set_input_port_default_value); + ClassDB::bind_method(D_METHOD("get_input_port_default_value", "port"), &VisualShaderNode::get_input_port_default_value); + + ClassDB::bind_method(D_METHOD("_set_default_input_values", "values"), &VisualShaderNode::_set_default_input_values); + ClassDB::bind_method(D_METHOD("_get_default_input_values"), &VisualShaderNode::_get_default_input_values); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "output_port_for_preview"), "set_output_port_for_preview", "get_output_port_for_preview"); + ADD_PROPERTYNZ(PropertyInfo(Variant::ARRAY, "default_input_values", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_default_input_values", "_get_default_input_values"); + ADD_SIGNAL(MethodInfo("editor_refresh_request")); +} + +VisualShaderNode::VisualShaderNode() { + port_preview = -1; +} + +///////////////////////////////////////////////////////// + +void VisualShader::add_node(Type p_type, const Ref<VisualShaderNode> &p_node, const Vector2 &p_position, int p_id) { + ERR_FAIL_COND(p_node.is_null()); + ERR_FAIL_COND(p_id < 2); + ERR_FAIL_INDEX(p_type, TYPE_MAX); + Graph *g = &graph[p_type]; + ERR_FAIL_COND(g->nodes.has(p_id)); + Node n; + n.node = p_node; + n.position = p_position; + + Ref<VisualShaderNodeUniform> uniform = n.node; + if (uniform.is_valid()) { + String valid_name = validate_uniform_name(uniform->get_uniform_name(), uniform); + uniform->set_uniform_name(valid_name); + } + + Ref<VisualShaderNodeInput> input = n.node; + if (input.is_valid()) { + input->shader_mode = shader_mode; + input->shader_type = p_type; + input->connect("input_type_changed", this, "_input_type_changed", varray(p_type, p_id)); + } + + n.node->connect("changed", this, "_queue_update"); + + g->nodes[p_id] = n; + + _queue_update(); +} + +void VisualShader::set_node_position(Type p_type, int p_id, const Vector2 &p_position) { + ERR_FAIL_INDEX(p_type, TYPE_MAX); + Graph *g = &graph[p_type]; + ERR_FAIL_COND(!g->nodes.has(p_id)); + g->nodes[p_id].position = p_position; +} + +Vector2 VisualShader::get_node_position(Type p_type, int p_id) const { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, Vector2()); + const Graph *g = &graph[p_type]; + ERR_FAIL_COND_V(!g->nodes.has(p_id), Vector2()); + return g->nodes[p_id].position; +} +Ref<VisualShaderNode> VisualShader::get_node(Type p_type, int p_id) const { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, Ref<VisualShaderNode>()); + const Graph *g = &graph[p_type]; + ERR_FAIL_COND_V(!g->nodes.has(p_id), Ref<VisualShaderNode>()); + return g->nodes[p_id].node; +} + +Vector<int> VisualShader::get_node_list(Type p_type) const { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, Vector<int>()); + const Graph *g = &graph[p_type]; + + Vector<int> ret; + for (Map<int, Node>::Element *E = g->nodes.front(); E; E = E->next()) { + ret.push_back(E->key()); + } + + return ret; +} +int VisualShader::get_valid_node_id(Type p_type) const { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, NODE_ID_INVALID); + const Graph *g = &graph[p_type]; + return g->nodes.size() ? MAX(2, g->nodes.back()->key() + 1) : 2; +} + +int VisualShader::find_node_id(Type p_type, const Ref<VisualShaderNode> &p_node) const { + for (const Map<int, Node>::Element *E = graph[p_type].nodes.front(); E; E = E->next()) { + if (E->get().node == p_node) + return E->key(); + } + + return NODE_ID_INVALID; +} + +void VisualShader::remove_node(Type p_type, int p_id) { + ERR_FAIL_INDEX(p_type, TYPE_MAX); + ERR_FAIL_COND(p_id < 2); + Graph *g = &graph[p_type]; + ERR_FAIL_COND(!g->nodes.has(p_id)); + + Ref<VisualShaderNodeInput> input = g->nodes[p_id].node; + if (input.is_valid()) { + input->disconnect("input_type_changed", this, "_input_type_changed"); + } + + g->nodes[p_id].node->disconnect("changed", this, "_queue_update"); + + g->nodes.erase(p_id); + + for (List<Connection>::Element *E = g->connections.front(); E;) { + List<Connection>::Element *N = E->next(); + if (E->get().from_node == p_id || E->get().to_node == p_id) { + g->connections.erase(E); + } + E = N; + } + + _queue_update(); +} + +bool VisualShader::is_node_connection(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, false); + const Graph *g = &graph[p_type]; + + for (const List<Connection>::Element *E = g->connections.front(); E; E = E->next()) { + + if (E->get().from_node == p_from_node && E->get().from_port == p_from_port && E->get().to_node == p_to_node && E->get().to_port == p_to_port) { + return true; + } + } + + return false; +} + +bool VisualShader::can_connect_nodes(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const { + + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, false); + const Graph *g = &graph[p_type]; + + if (!g->nodes.has(p_from_node)) + return false; + + if (p_from_port < 0 || p_from_port >= g->nodes[p_from_node].node->get_output_port_count()) + return false; + + if (!g->nodes.has(p_to_node)) + return false; + + if (p_to_port < 0 || p_to_port >= g->nodes[p_to_node].node->get_input_port_count()) + return false; + + VisualShaderNode::PortType from_port_type = g->nodes[p_from_node].node->get_output_port_type(p_from_port); + VisualShaderNode::PortType to_port_type = g->nodes[p_to_node].node->get_input_port_type(p_to_port); + + if (MAX(0, from_port_type - 1) != (MAX(0, to_port_type - 1))) { + return false; + } + + for (const List<Connection>::Element *E = g->connections.front(); E; E = E->next()) { + + if (E->get().from_node == p_from_node && E->get().from_port == p_from_port && E->get().to_node == p_to_node && E->get().to_port == p_to_port) { + return false; + } + } + + return true; +} + +Error VisualShader::connect_nodes(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, ERR_CANT_CONNECT); + Graph *g = &graph[p_type]; + + ERR_FAIL_COND_V(!g->nodes.has(p_from_node), ERR_INVALID_PARAMETER); + ERR_FAIL_INDEX_V(p_from_port, g->nodes[p_from_node].node->get_output_port_count(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!g->nodes.has(p_to_node), ERR_INVALID_PARAMETER); + ERR_FAIL_INDEX_V(p_to_port, g->nodes[p_to_node].node->get_input_port_count(), ERR_INVALID_PARAMETER); + + VisualShaderNode::PortType from_port_type = g->nodes[p_from_node].node->get_output_port_type(p_from_port); + VisualShaderNode::PortType to_port_type = g->nodes[p_to_node].node->get_input_port_type(p_to_port); + + if (MAX(0, from_port_type - 1) != (MAX(0, to_port_type - 1))) { + ERR_EXPLAIN("Incompatible port types (scalar/vec with transform"); + ERR_FAIL_V(ERR_INVALID_PARAMETER) + return ERR_INVALID_PARAMETER; + } + + for (List<Connection>::Element *E = g->connections.front(); E; E = E->next()) { + + if (E->get().from_node == p_from_node && E->get().from_port == p_from_port && E->get().to_node == p_to_node && E->get().to_port == p_to_port) { + ERR_FAIL_V(ERR_ALREADY_EXISTS); + } + } + + Connection c; + c.from_node = p_from_node; + c.from_port = p_from_port; + c.to_node = p_to_node; + c.to_port = p_to_port; + g->connections.push_back(c); + + _queue_update(); + return OK; +} +void VisualShader::disconnect_nodes(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { + ERR_FAIL_INDEX(p_type, TYPE_MAX); + Graph *g = &graph[p_type]; + + for (List<Connection>::Element *E = g->connections.front(); E; E = E->next()) { + + if (E->get().from_node == p_from_node && E->get().from_port == p_from_port && E->get().to_node == p_to_node && E->get().to_port == p_to_port) { + g->connections.erase(E); + _queue_update(); + return; + } + } +} + +Array VisualShader::_get_node_connections(Type p_type) const { + ERR_FAIL_INDEX_V(p_type, TYPE_MAX, Array()); + const Graph *g = &graph[p_type]; + + Array ret; + for (const List<Connection>::Element *E = g->connections.front(); E; E = E->next()) { + Dictionary d; + d["from_node"] = E->get().from_node; + d["from_port"] = E->get().from_port; + d["to_node"] = E->get().to_node; + d["to_port"] = E->get().to_port; + ret.push_back(d); + } + + return ret; +} +void VisualShader::get_node_connections(Type p_type, List<Connection> *r_connections) const { + ERR_FAIL_INDEX(p_type, TYPE_MAX); + const Graph *g = &graph[p_type]; + + for (const List<Connection>::Element *E = g->connections.front(); E; E = E->next()) { + r_connections->push_back(E->get()); + } +} + +void VisualShader::set_mode(Mode p_mode) { + if (shader_mode == p_mode) { + return; + } + + //erase input/output connections + modes.clear(); + flags.clear(); + shader_mode = p_mode; + for (int i = 0; i < TYPE_MAX; i++) { + + for (Map<int, Node>::Element *E = graph[i].nodes.front(); E; E = E->next()) { + + Ref<VisualShaderNodeInput> input = E->get().node; + if (input.is_valid()) { + input->shader_mode = shader_mode; + //input->input_index = 0; + } + } + + Ref<VisualShaderNodeOutput> output = graph[i].nodes[NODE_ID_OUTPUT].node; + output->shader_mode = shader_mode; + + // clear connections since they are no longer valid + for (List<Connection>::Element *E = graph[i].connections.front(); E;) { + + bool keep = true; + + List<Connection>::Element *N = E->next(); + + int from = E->get().from_node; + int to = E->get().to_node; + + if (!graph[i].nodes.has(from)) { + keep = false; + } else { + Ref<VisualShaderNode> from_node = graph[i].nodes[from].node; + if (from_node->is_class("VisualShaderNodeOutput") || from_node->is_class("VisualShaderNodeInput")) { + keep = false; + } + } + + if (!graph[i].nodes.has(to)) { + keep = false; + } else { + Ref<VisualShaderNode> to_node = graph[i].nodes[to].node; + if (to_node->is_class("VisualShaderNodeOutput") || to_node->is_class("VisualShaderNodeInput")) { + keep = false; + } + } + + if (!keep) { + graph[i].connections.erase(E); + } + E = N; + } + } + + _queue_update(); + _change_notify(); +} + +void VisualShader::set_graph_offset(const Vector2 &p_offset) { + graph_offset = p_offset; +} + +Vector2 VisualShader::get_graph_offset() const { + return graph_offset; +} + +Shader::Mode VisualShader::get_mode() const { + return shader_mode; +} + +String VisualShader::generate_preview_shader(Type p_type, int p_node, int p_port, Vector<DefaultTextureParam> &default_tex_params) const { + + Ref<VisualShaderNode> node = get_node(p_type, p_node); + ERR_FAIL_COND_V(!node.is_valid(), String()); + ERR_FAIL_COND_V(p_port < 0 || p_port >= node->get_output_port_count(), String()); + ERR_FAIL_COND_V(node->get_output_port_type(p_port) == VisualShaderNode::PORT_TYPE_TRANSFORM, String()); + + StringBuilder global_code; + StringBuilder code; + + global_code += String() + "shader_type canvas_item;\n"; + + //make it faster to go around through shader + VMap<ConnectionKey, const List<Connection>::Element *> input_connections; + VMap<ConnectionKey, const List<Connection>::Element *> output_connections; + + for (const List<Connection>::Element *E = graph[p_type].connections.front(); E; E = E->next()) { + ConnectionKey from_key; + from_key.node = E->get().from_node; + from_key.port = E->get().from_port; + + output_connections.insert(from_key, E); + + ConnectionKey to_key; + to_key.node = E->get().to_node; + to_key.port = E->get().to_port; + + input_connections.insert(to_key, E); + } + + code += "\nvoid fragment() {\n"; + + Set<int> processed; + Error err = _write_node(p_type, global_code, code, default_tex_params, input_connections, output_connections, p_node, processed, true); + ERR_FAIL_COND_V(err != OK, String()); + + if (node->get_output_port_type(p_port) == VisualShaderNode::PORT_TYPE_SCALAR) { + code += "\tCOLOR.rgb = vec3( n_out" + itos(p_node) + "p" + itos(p_port) + " );\n"; + } else { + code += "\tCOLOR.rgb = n_out" + itos(p_node) + "p" + itos(p_port) + ";\n"; + } + code += "}\n"; + + //set code secretly + global_code += "\n\n"; + String final_code = global_code; + final_code += code; + //print_line(final_code); + return final_code; +} + +#define IS_INITIAL_CHAR(m_d) (((m_d) >= 'a' && (m_d) <= 'z') || ((m_d) >= 'A' && (m_d) <= 'Z')) + +#define IS_SYMBOL_CHAR(m_d) (((m_d) >= 'a' && (m_d) <= 'z') || ((m_d) >= 'A' && (m_d) <= 'Z') || ((m_d) >= '0' && (m_d) <= '9') || (m_d) == '_') + +String VisualShader::validate_uniform_name(const String &p_name, const Ref<VisualShaderNodeUniform> &p_uniform) const { + + String name = p_name; //validate name first + while (name.length() && !IS_INITIAL_CHAR(name[0])) { + name = name.substr(1, name.length() - 1); + } + if (name != String()) { + + String valid_name; + + for (int i = 0; i < name.length(); i++) { + if (IS_SYMBOL_CHAR(name[i])) { + valid_name += String::chr(name[i]); + } else if (name[i] == ' ') { + valid_name += "_"; + } + } + + name = valid_name; + } + + if (name == String()) { + name = p_uniform->get_caption(); + } + + int attempt = 1; + + while (true) { + + bool exists = false; + for (int i = 0; i < TYPE_MAX; i++) { + for (const Map<int, Node>::Element *E = graph[i].nodes.front(); E; E = E->next()) { + Ref<VisualShaderNodeUniform> node = E->get().node; + if (node == p_uniform) { //do not test on self + continue; + } + if (node.is_valid() && node->get_uniform_name() == name) { + exists = true; + break; + } + } + if (exists) { + break; + } + } + + if (exists) { + //remove numbers, put new and try again + attempt++; + while (name.length() && name[name.length() - 1] >= '0' && name[name.length() - 1] <= '9') { + name = name.substr(0, name.length() - 1); + } + ERR_FAIL_COND_V(name == String(), String()); + name += itos(attempt); + } else { + break; + } + } + + return name; +} + +VisualShader::RenderModeEnums VisualShader::render_mode_enums[] = { + { Shader::MODE_SPATIAL, "blend" }, + { Shader::MODE_SPATIAL, "depth_draw" }, + { Shader::MODE_SPATIAL, "cull" }, + { Shader::MODE_SPATIAL, "diffuse" }, + { Shader::MODE_SPATIAL, "specular" }, + { Shader::MODE_CANVAS_ITEM, "blend" }, + { Shader::MODE_CANVAS_ITEM, NULL } +}; + +static const char *type_string[VisualShader::TYPE_MAX] = { + "vertex", + "fragment", + "light" +}; +bool VisualShader::_set(const StringName &p_name, const Variant &p_value) { + + String name = p_name; + if (name == "mode") { + set_mode(Shader::Mode(int(p_value))); + return true; + } else if (name.begins_with("flags/")) { + StringName flag = name.get_slicec('/', 1); + bool enable = p_value; + if (enable) { + flags.insert(flag); + } else { + flags.erase(flag); + } + _queue_update(); + return true; + } else if (name.begins_with("modes/")) { + String mode = name.get_slicec('/', 1); + int value = p_value; + if (value == 0) { + modes.erase(mode); //means its default anyway, so dont store it + } else { + modes[mode] = value; + } + _queue_update(); + return true; + } else if (name.begins_with("nodes/")) { + String typestr = name.get_slicec('/', 1); + Type type = TYPE_VERTEX; + for (int i = 0; i < TYPE_MAX; i++) { + if (typestr == type_string[i]) { + type = Type(i); + break; + } + } + + String index = name.get_slicec('/', 2); + if (index == "connections") { + + Vector<int> conns = p_value; + if (conns.size() % 4 == 0) { + for (int i = 0; i < conns.size(); i += 4) { + connect_nodes(type, conns[i + 0], conns[i + 1], conns[i + 2], conns[i + 3]); + } + } + return true; + } + + int id = index.to_int(); + String what = name.get_slicec('/', 3); + + if (what == "node") { + add_node(type, p_value, Vector2(), id); + return true; + } else if (what == "position") { + set_node_position(type, id, p_value); + return true; + } + } + return false; +} + +bool VisualShader::_get(const StringName &p_name, Variant &r_ret) const { + + String name = p_name; + if (name == "mode") { + r_ret = get_mode(); + return true; + } else if (name.begins_with("flags/")) { + StringName flag = name.get_slicec('/', 1); + r_ret = flags.has(flag); + return true; + } else if (name.begins_with("modes/")) { + String mode = name.get_slicec('/', 1); + if (modes.has(mode)) { + r_ret = modes[mode]; + } else { + r_ret = 0; + } + return true; + } else if (name.begins_with("nodes/")) { + String typestr = name.get_slicec('/', 1); + Type type = TYPE_VERTEX; + for (int i = 0; i < TYPE_MAX; i++) { + if (typestr == type_string[i]) { + type = Type(i); + break; + } + } + + String index = name.get_slicec('/', 2); + if (index == "connections") { + + Vector<int> conns; + for (const List<Connection>::Element *E = graph[type].connections.front(); E; E = E->next()) { + conns.push_back(E->get().from_node); + conns.push_back(E->get().from_port); + conns.push_back(E->get().to_node); + conns.push_back(E->get().to_port); + } + + r_ret = conns; + return true; + } + + int id = index.to_int(); + String what = name.get_slicec('/', 3); + + if (what == "node") { + r_ret = get_node(type, id); + return true; + } else if (what == "position") { + r_ret = get_node_position(type, id); + return true; + } + } + return false; +} +void VisualShader::_get_property_list(List<PropertyInfo> *p_list) const { + + //mode + p_list->push_back(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Spatial,CanvasItem,Particles")); + //render modes + + Map<String, String> blend_mode_enums; + Set<String> toggles; + + for (int i = 0; i < ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader_mode)).size(); i++) { + + String mode = ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader_mode))[i]; + int idx = 0; + bool in_enum = false; + while (render_mode_enums[idx].string) { + if (mode.begins_with(render_mode_enums[idx].string)) { + String begin = render_mode_enums[idx].string; + String option = mode.replace_first(begin + "_", ""); + if (!blend_mode_enums.has(begin)) { + blend_mode_enums[begin] = option; + } else { + blend_mode_enums[begin] += "," + option; + } + in_enum = true; + break; + } + idx++; + } + + if (!in_enum) { + toggles.insert(mode); + } + } + + for (Map<String, String>::Element *E = blend_mode_enums.front(); E; E = E->next()) { + + p_list->push_back(PropertyInfo(Variant::INT, "modes/" + E->key(), PROPERTY_HINT_ENUM, E->get())); + } + + for (Set<String>::Element *E = toggles.front(); E; E = E->next()) { + p_list->push_back(PropertyInfo(Variant::BOOL, "flags/" + E->get())); + } + + for (int i = 0; i < TYPE_MAX; i++) { + for (Map<int, Node>::Element *E = graph[i].nodes.front(); E; E = E->next()) { + + String prop_name = "nodes/"; + prop_name += type_string[i]; + prop_name += "/" + itos(E->key()); + + if (E->key() != NODE_ID_OUTPUT) { + + p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + "/node", PROPERTY_HINT_RESOURCE_TYPE, "VisualShaderNode", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); + } + p_list->push_back(PropertyInfo(Variant::VECTOR2, prop_name + "/position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + } + p_list->push_back(PropertyInfo(Variant::POOL_INT_ARRAY, "nodes/" + String(type_string[i]) + "/connections", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + } +} + +Error VisualShader::_write_node(Type type, StringBuilder &global_code, StringBuilder &code, Vector<VisualShader::DefaultTextureParam> &def_tex_params, const VMap<ConnectionKey, const List<Connection>::Element *> &input_connections, const VMap<ConnectionKey, const List<Connection>::Element *> &output_connections, int node, Set<int> &processed, bool for_preview) const { + + const Ref<VisualShaderNode> vsnode = graph[type].nodes[node].node; + + //check inputs recursively first + int input_count = vsnode->get_input_port_count(); + for (int i = 0; i < input_count; i++) { + ConnectionKey ck; + ck.node = node; + ck.port = i; + + if (input_connections.has(ck)) { + int from_node = input_connections[ck]->get().from_node; + if (processed.has(from_node)) { + continue; + } + + Error err = _write_node(type, global_code, code, def_tex_params, input_connections, output_connections, from_node, processed, for_preview); + if (err) + return err; + } + } + + // then this node + + code += "// " + vsnode->get_caption() + ":" + itos(node) + "\n"; + Vector<String> input_vars; + + input_vars.resize(vsnode->get_input_port_count()); + String *inputs = input_vars.ptrw(); + + for (int i = 0; i < input_count; i++) { + ConnectionKey ck; + ck.node = node; + ck.port = i; + + if (input_connections.has(ck)) { + //connected to something, use that output + int from_node = input_connections[ck]->get().from_node; + int from_port = input_connections[ck]->get().from_port; + + VisualShaderNode::PortType in_type = vsnode->get_input_port_type(i); + VisualShaderNode::PortType out_type = graph[type].nodes[from_node].node->get_output_port_type(from_port); + + String src_var = "n_out" + itos(from_node) + "p" + itos(from_port); + + if (in_type == out_type) { + inputs[i] = src_var; + } else if (in_type == VisualShaderNode::PORT_TYPE_SCALAR && out_type == VisualShaderNode::PORT_TYPE_VECTOR) { + inputs[i] = "dot(" + src_var + ",vec3(0.333333,0.333333,0.333333))"; + } else if (in_type == VisualShaderNode::PORT_TYPE_VECTOR && out_type == VisualShaderNode::PORT_TYPE_SCALAR) { + inputs[i] = "vec3(" + src_var + ")"; + } + } else { + + Variant defval = vsnode->get_input_port_default_value(i); + if (defval.get_type() == Variant::REAL || defval.get_type() == Variant::INT) { + float val = defval; + inputs[i] = "n_in" + itos(node) + "p" + itos(i); + code += "\tfloat " + inputs[i] + " = " + vformat("%.5f", val) + ";\n"; + } else if (defval.get_type() == Variant::VECTOR3) { + Vector3 val = defval; + inputs[i] = "n_in" + itos(node) + "p" + itos(i); + code += "\tvec3 " + inputs[i] + " = " + vformat("vec3(%.5f,%.5f,%.5f);\n", val.x, val.y, val.z); + } else if (defval.get_type() == Variant::TRANSFORM) { + Transform val = defval; + val.basis.transpose(); + inputs[i] = "n_in" + itos(node) + "p" + itos(i); + Array values; + for (int i = 0; i < 3; i++) { + values.push_back(val.basis[i].x); + values.push_back(val.basis[i].y); + values.push_back(val.basis[i].z); + } + values.push_back(val.origin.x); + values.push_back(val.origin.y); + values.push_back(val.origin.z); + bool err = false; + code += "\tmat4 " + inputs[i] + " = " + String("mat4( vec4(%.5f,%.5f,%.5f,0.0),vec4(%.5f,%.5f,%.5f,0.0),vec4(%.5f,%.5f,%.5f,0.0),vec4(%.5f,%.5f,%.5f,1.0) );\n").sprintf(values, &err); + } else { + //will go empty, node is expected to know what it is doing at this point and handle it + } + } + } + + int output_count = vsnode->get_output_port_count(); + Vector<String> output_vars; + output_vars.resize(vsnode->get_output_port_count()); + String *outputs = output_vars.ptrw(); + + for (int i = 0; i < output_count; i++) { + + outputs[i] = "n_out" + itos(node) + "p" + itos(i); + switch (vsnode->get_output_port_type(i)) { + case VisualShaderNode::PORT_TYPE_SCALAR: code += String() + "\tfloat " + outputs[i] + ";\n"; break; + case VisualShaderNode::PORT_TYPE_VECTOR: code += String() + "\tvec3 " + outputs[i] + ";\n"; break; + case VisualShaderNode::PORT_TYPE_TRANSFORM: code += String() + "\tmat4 " + outputs[i] + ";\n"; break; + default: {} + } + } + + Vector<VisualShader::DefaultTextureParam> params = vsnode->get_default_texture_parameters(type, node); + for (int i = 0; i < params.size(); i++) { + def_tex_params.push_back(params[i]); + } + + Ref<VisualShaderNodeInput> input = vsnode; + + if (input.is_valid() && for_preview) { + //handle for preview + code += input->generate_code_for_preview(type, node, inputs, outputs); + } else { + //handle normally + global_code += vsnode->generate_global(get_mode(), type, node); + code += vsnode->generate_code(get_mode(), type, node, inputs, outputs); + } + code += "\n"; // + processed.insert(node); + + return OK; +} + +void VisualShader::_update_shader() const { + if (!dirty) + return; + + dirty = false; + + StringBuilder global_code; + StringBuilder code; + Vector<VisualShader::DefaultTextureParam> default_tex_params; + static const char *shader_mode_str[Shader::MODE_MAX] = { "spatial", "canvas_item", "particles" }; + + global_code += String() + "shader_type " + shader_mode_str[shader_mode] + ";\n"; + + String render_mode; + + { + //fill render mode enums + int idx = 0; + while (render_mode_enums[idx].string) { + + if (shader_mode == render_mode_enums[idx].mode) { + + if (modes.has(render_mode_enums[idx].string)) { + + int which = modes[render_mode_enums[idx].string]; + int count = 0; + for (int i = 0; i < ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader_mode)).size(); i++) { + String mode = ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader_mode))[i]; + if (mode.begins_with(render_mode_enums[idx].string)) { + if (count == which) { + if (render_mode != String()) { + render_mode += ", "; + } + render_mode += mode; + break; + } + count++; + } + } + } + } + idx++; + } + + //fill render mode flags + for (int i = 0; i < ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader_mode)).size(); i++) { + + String mode = ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader_mode))[i]; + if (flags.has(mode)) { + if (render_mode != String()) { + render_mode += ", "; + } + render_mode += mode; + } + } + } + + if (render_mode != String()) { + + global_code += "render_mode " + render_mode + ";\n\n"; + } + + static const char *func_name[TYPE_MAX] = { "vertex", "fragment", "light" }; + + for (int i = 0; i < TYPE_MAX; i++) { + + //make it faster to go around through shader + VMap<ConnectionKey, const List<Connection>::Element *> input_connections; + VMap<ConnectionKey, const List<Connection>::Element *> output_connections; + + for (const List<Connection>::Element *E = graph[i].connections.front(); E; E = E->next()) { + ConnectionKey from_key; + from_key.node = E->get().from_node; + from_key.port = E->get().from_port; + + output_connections.insert(from_key, E); + + ConnectionKey to_key; + to_key.node = E->get().to_node; + to_key.port = E->get().to_port; + + input_connections.insert(to_key, E); + } + + code += "\nvoid " + String(func_name[i]) + "() {\n"; + + Set<int> processed; + Error err = _write_node(Type(i), global_code, code, default_tex_params, input_connections, output_connections, NODE_ID_OUTPUT, processed, false); + ERR_FAIL_COND(err != OK); + + code += "}\n"; + } + + //set code secretly + global_code += "\n\n"; + String final_code = global_code; + final_code += code; + const_cast<VisualShader *>(this)->set_code(final_code); + //print_line(final_code); + for (int i = 0; i < default_tex_params.size(); i++) { + const_cast<VisualShader *>(this)->set_default_texture_param(default_tex_params[i].name, default_tex_params[i].param); + } +} + +void VisualShader::_queue_update() { + if (dirty) { + return; + } + + dirty = true; + call_deferred("_update_shader"); +} + +void VisualShader::_input_type_changed(Type p_type, int p_id) { + //erase connections using this input, as type changed + Graph *g = &graph[p_type]; + + for (List<Connection>::Element *E = g->connections.front(); E;) { + List<Connection>::Element *N = E->next(); + if (E->get().from_node == p_id) { + g->connections.erase(E); + } + E = N; + } +} + +void VisualShader::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_mode", "mode"), &VisualShader::set_mode); + + ClassDB::bind_method(D_METHOD("add_node", "type", "node", "position", "id"), &VisualShader::add_node); + ClassDB::bind_method(D_METHOD("set_node_position", "type", "id", "position"), &VisualShader::set_node_position); + + ClassDB::bind_method(D_METHOD("get_node_position", "type", "id"), &VisualShader::get_node_position); + ClassDB::bind_method(D_METHOD("get_node", "type"), &VisualShader::get_node); + + ClassDB::bind_method(D_METHOD("get_node_list", "type"), &VisualShader::get_node_list); + ClassDB::bind_method(D_METHOD("get_valid_node_id", "type"), &VisualShader::get_valid_node_id); + + ClassDB::bind_method(D_METHOD("remove_node", "type", "id"), &VisualShader::remove_node); + + ClassDB::bind_method(D_METHOD("is_node_connection", "type", "from_node", "from_port", "to_node", "to_port"), &VisualShader::is_node_connection); + ClassDB::bind_method(D_METHOD("can_connect_nodes", "type", "from_node", "from_port", "to_node", "to_port"), &VisualShader::is_node_connection); + + ClassDB::bind_method(D_METHOD("connect_nodes", "type", "from_node", "from_port", "to_node", "to_port"), &VisualShader::connect_nodes); + ClassDB::bind_method(D_METHOD("disconnect_nodes", "type", "from_node", "from_port", "to_node", "to_port"), &VisualShader::disconnect_nodes); + + ClassDB::bind_method(D_METHOD("get_node_connections", "type"), &VisualShader::_get_node_connections); + + ClassDB::bind_method(D_METHOD("set_graph_offset", "offset"), &VisualShader::set_graph_offset); + ClassDB::bind_method(D_METHOD("get_graph_offset"), &VisualShader::get_graph_offset); + + ClassDB::bind_method(D_METHOD("_queue_update"), &VisualShader::_queue_update); + ClassDB::bind_method(D_METHOD("_update_shader"), &VisualShader::_update_shader); + + ClassDB::bind_method(D_METHOD("_input_type_changed"), &VisualShader::_input_type_changed); + + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "graph_offset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_graph_offset", "get_graph_offset"); + + BIND_ENUM_CONSTANT(TYPE_VERTEX); + BIND_ENUM_CONSTANT(TYPE_FRAGMENT); + BIND_ENUM_CONSTANT(TYPE_LIGHT); + BIND_ENUM_CONSTANT(TYPE_MAX); + + BIND_CONSTANT(NODE_ID_INVALID); + BIND_CONSTANT(NODE_ID_OUTPUT); +} + +VisualShader::VisualShader() { + shader_mode = Shader::MODE_SPATIAL; + + for (int i = 0; i < TYPE_MAX; i++) { + Ref<VisualShaderNodeOutput> output; + output.instance(); + output->shader_type = Type(i); + output->shader_mode = shader_mode; + graph[i].nodes[NODE_ID_OUTPUT].node = output; + graph[i].nodes[NODE_ID_OUTPUT].position = Vector2(400, 150); + } + + dirty = true; +} + +/////////////////////////////////////////////////////////// + +const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { + // Spatial, Vertex + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "vertex", "VERTEX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "tangent", "TANGENT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "binormal", "BINORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv2", "vec3(UV2,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "point_size", "POINT_SIZE" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "world", "WORLD_MATRIX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "inv_camera", "INV_CAMERA_MATRIX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "projection", "PROJECTION" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "vp_size", "vec3(VIEWPORT_SIZE, 0)" }, + + // Spatial, Fragment + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "vertex", "VERTEX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "tangent", "TANGENT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "binormal", "BINORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "uv2", "vec3(UV2,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "point_coord", "vec2(POINT_COORD,0.0)" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "screen_uv", "vec3(SCREEN_UV,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "side", "float(FRONT_FACING ? 1.0 : 0.0)" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_TRANSFORM, "world", "WORLD_MATRIX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_TRANSFORM, "inv_camera", "INV_CAMERA_MATRIX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_TRANSFORM, "projection", "PROJECTION" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "vp_size", "vec3(VIEWPORT_SIZE, 0.0)" }, + + // Spatial, Light + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "view", "VIEW" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light", "LIGHT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light_color", "LIGHT_COLOR" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "attenuation", "ATTENUATION" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "albedo", "ALBEDO" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "transmission", "TRANSMISSION" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "roughness", "ROUGHNESS" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_TRANSFORM, "world", "WORLD_MATRIX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_TRANSFORM, "inv_camera", "INV_CAMERA_MATRIX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_TRANSFORM, "projection", "PROJECTION" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "vp_size", "vec3(VIEWPORT_SIZE, 0.0)" }, + // Canvas Item, Vertex + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "vertex", "vec3(VERTEX,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "point_size", "POINT_SIZE" }, + + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "world", "WORLD_MATRIX" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "projection", "PROJECTION_MATRIX" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "extra", "EXTRA_MATRIX" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "light_pass", "float(AT_LIGHT_PASS ? 1.0 : 0.0)" }, + // Canvas Item, Fragment + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "screen_uv", "vec3(SCREEN_UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "point_coord", "vec2(POINT_COORD,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "light_pass", "float(AT_LIGHT_PASS ? 1.0 : 0.0)" }, + // Canvas Item, Light + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light_vec", "vec3(LIGHT_VEC,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "light_height", "LIGHT_HEIGHT" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light_color", "LIGHT_COLOR.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light_alpha", "LIGHT_COLOR.a" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light_uv", "vec3(LIGHT_UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "shadow_color", "SHADOW_COLOR.rgb" }, + + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "screen_uv", "vec3(SCREEN_UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "point_coord", "vec2(POINT_COORD,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + // Particles, Vertex + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "velocity", "VELOCITY" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "restart", "float(RESTART ? 1.0 : 0.0)" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "active", "float(ACTIVE ? 1.0 : 0.0)" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "custom", "CUSTOM.rgb" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "custom_alpha", "CUSTOM.a" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, + + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "index", "float(INDEX)" }, + + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_MAX, VisualShader::TYPE_MAX, VisualShaderNode::PORT_TYPE_TRANSFORM, NULL, NULL }, +}; + +const VisualShaderNodeInput::Port VisualShaderNodeInput::preview_ports[] = { + + // Spatial, Fragment + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "vec3(0.0,0.0,1.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "tangent", "vec3(0.0,1.0,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "binormal", "vec3(1.0,0.0,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "uv2", "vec3(UV,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "vec3(1.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "1.0" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "screen_uv", "vec3(UV,0.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "side", "1.0" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "vp_size", "vec3(1.0,1.0, 0.0)" }, + + // Spatial, Light + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "vec3(0.0,0.0,1.0)" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "vp_size", "vec3(1.0, 1.0, 0.0)" }, + // Canvas Item, Vertex + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "vertex", "vec3(VERTEX,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "vec3(1.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "1.0" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + // Canvas Item, Fragment + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "vec3(1.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "1.0" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "screen_uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + // Canvas Item, Light + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "vec3(0.0,0.0,1.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "vec3(1.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "1.0" }, + + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "screen_uv", "vec3(UV,0.0)" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + // Particles, Vertex + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "vec3(1.0)" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "1.0" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "velocity", "vec3(0.0,0.0,1.0)" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, + { Shader::MODE_MAX, VisualShader::TYPE_MAX, VisualShaderNode::PORT_TYPE_TRANSFORM, NULL, NULL }, +}; + +int VisualShaderNodeInput::get_input_port_count() const { + + return 0; +} +VisualShaderNodeInput::PortType VisualShaderNodeInput::get_input_port_type(int p_port) const { + + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeInput::get_input_port_name(int p_port) const { + + return ""; +} + +int VisualShaderNodeInput::get_output_port_count() const { + + return 1; +} +VisualShaderNodeInput::PortType VisualShaderNodeInput::get_output_port_type(int p_port) const { + + return get_input_type_by_name(input_name); +} +String VisualShaderNodeInput::get_output_port_name(int p_port) const { + return ""; +} + +String VisualShaderNodeInput::get_caption() const { + return TTR("Input"); +} + +String VisualShaderNodeInput::generate_code_for_preview(VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + int idx = 0; + + String code; + + while (preview_ports[idx].mode != Shader::MODE_MAX) { + if (preview_ports[idx].mode == shader_mode && preview_ports[idx].shader_type == shader_type && preview_ports[idx].name == input_name) { + code = "\t" + p_output_vars[0] + " = " + preview_ports[idx].string + ";\n"; + break; + } + idx++; + } + + if (code == String()) { + switch (get_output_port_type(0)) { + case PORT_TYPE_SCALAR: { + code = "\t" + p_output_vars[0] + " = 0.0;\n"; + } break; //default (none found) is scalar + case PORT_TYPE_VECTOR: { + code = "\t" + p_output_vars[0] + " = vec3(0.0);\n"; + } break; //default (none found) is scalar + case PORT_TYPE_TRANSFORM: { + code = "\t" + p_output_vars[0] + " = mat4( vec4(1.0,0.0,0.0,0.0), vec4(0.0,1.0,0.0,0.0), vec4(0.0,0.0,1.0,0.0), vec4(0.0,0.0,0.0,1.0) );\n"; + } break; //default (none found) is scalar + } + } + + return code; +} + +String VisualShaderNodeInput::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + int idx = 0; + + String code; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type && ports[idx].name == input_name) { + code = "\t" + p_output_vars[0] + " = " + ports[idx].string + ";\n"; + break; + } + idx++; + } + + if (code == String()) { + code = "\t" + p_output_vars[0] + " = 0.0;\n"; //default (none found) is scalar + } + + return code; +} + +void VisualShaderNodeInput::set_input_name(String p_name) { + PortType prev_type = get_input_type_by_name(input_name); + input_name = p_name; + emit_changed(); + if (get_input_type_by_name(input_name) != prev_type) { + emit_signal("input_type_changed"); + } +} + +String VisualShaderNodeInput::get_input_name() const { + return input_name; +} + +VisualShaderNodeInput::PortType VisualShaderNodeInput::get_input_type_by_name(String p_name) const { + + int idx = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type && ports[idx].name == p_name) { + return ports[idx].type; + } + idx++; + } + + return PORT_TYPE_SCALAR; +} + +int VisualShaderNodeInput::get_input_index_count() const { + int idx = 0; + int count = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + count++; + } + idx++; + } + + return count; +} + +VisualShaderNodeInput::PortType VisualShaderNodeInput::get_input_index_type(int p_index) const { + int idx = 0; + int count = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + if (count == p_index) { + return ports[idx].type; + } + count++; + } + idx++; + } + + return PORT_TYPE_SCALAR; +} + +String VisualShaderNodeInput::get_input_index_name(int p_index) const { + int idx = 0; + int count = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + if (count == p_index) { + return ports[idx].name; + } + count++; + } + idx++; + } + + return ""; +} + +void VisualShaderNodeInput::_validate_property(PropertyInfo &property) const { + + if (property.name == "input_name") { + String port_list; + + int idx = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + if (port_list != String()) { + port_list += ","; + } + port_list += ports[idx].name; + } + idx++; + } + + if (port_list == "") { + port_list = TTR("None"); + } + property.hint_string = port_list; + } +} + +Vector<StringName> VisualShaderNodeInput::get_editable_properties() const { + Vector<StringName> props; + props.push_back("input_name"); + return props; +} + +void VisualShaderNodeInput::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_input_name", "name"), &VisualShaderNodeInput::set_input_name); + ClassDB::bind_method(D_METHOD("get_input_name"), &VisualShaderNodeInput::get_input_name); + + ADD_PROPERTY(PropertyInfo(Variant::STRING, "input_name", PROPERTY_HINT_ENUM, ""), "set_input_name", "get_input_name"); + ADD_SIGNAL(MethodInfo("input_type_changed")); +} +VisualShaderNodeInput::VisualShaderNodeInput() { + input_name = "[None]"; + // changed when set + shader_type = VisualShader::TYPE_MAX; + shader_mode = Shader::MODE_MAX; +} + +//////////////////////////////////////////// + +const VisualShaderNodeOutput::Port VisualShaderNodeOutput::ports[] = { + // Spatial, Vertex + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "vertex", "VERTEX" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "tangent", "TANGENT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "binormal", "BINORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "UV:xy" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv2", "UV2:xy" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "roughness", "ROUGHNESS" }, + // Spatial, Fragment + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "albedo", "ALBEDO" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "ALPHA" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "metallic", "METALLIC" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "roughness", "ROUGHNESS" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "specular", "SPECULAR" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "emission", "EMISSION" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "ao", "AO" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normalmap", "NORMALMAP" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "normalmap_depth", "NORMALMAP_DEPTH" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "rim", "RIM" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "rim_tint", "RIM_TINT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "clearcoat", "CLEARCOAT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "clearcoat_gloss", "CLEARCOAT_GLOSS" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "anisotropy", "ANISOTROPY" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "anisotropy_flow", "ANISOTROPY_FLOW:xy" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "subsurf_scatter", "SSS_STRENGTH" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "transmission", "TRANSMISSION" }, + + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha_scissor", "ALPHA_SCISSOR" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "ao_light_affect", "AO_LIGHT_AFFECT" }, + + // Spatial, Light + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "diffuse", "DIFFUSE_LIGHT" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "specular", "SPECULAR_LIGHT" }, + // Canvas Item, Vertex + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "vertex", "VERTEX:xy" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "uv", "UV:xy" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + // Canvas Item, Fragment + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normal", "NORMAL" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR, "normalmap", "NORMALMAP" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR, "normalmap_depth", "NORMALMAP_DEPTH" }, + // Canvas Item, Light + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_VECTOR, "light", "LIGHT.rgb" }, + { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_LIGHT, VisualShaderNode::PORT_TYPE_SCALAR, "light_alpha", "LIGHT.rgb" }, + // Particles, Vertex + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "color", "COLOR.rgb" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "alpha", "COLOR.a" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "velocity", "VELOCITY" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR, "custom", "CUSTOM.rgb" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR, "custom_alpha", "CUSTOM.a" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, + { Shader::MODE_MAX, VisualShader::TYPE_MAX, VisualShaderNode::PORT_TYPE_TRANSFORM, NULL, NULL }, +}; + +int VisualShaderNodeOutput::get_input_port_count() const { + + int idx = 0; + int count = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + count++; + } + idx++; + } + + return count; +} + +VisualShaderNodeOutput::PortType VisualShaderNodeOutput::get_input_port_type(int p_port) const { + + int idx = 0; + int count = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + if (count == p_port) { + return ports[idx].type; + } + count++; + } + idx++; + } + + return PORT_TYPE_SCALAR; +} + +String VisualShaderNodeOutput::get_input_port_name(int p_port) const { + + int idx = 0; + int count = 0; + + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + if (count == p_port) { + return String(ports[idx].name).capitalize(); + } + count++; + } + idx++; + } + + return String(); +} + +Variant VisualShaderNodeOutput::get_input_port_default_value(int p_port) const { + return Variant(); +} + +int VisualShaderNodeOutput::get_output_port_count() const { + + return 0; +} +VisualShaderNodeOutput::PortType VisualShaderNodeOutput::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeOutput::get_output_port_name(int p_port) const { + return String(); +} + +bool VisualShaderNodeOutput::is_port_separator(int p_index) const { + + if (shader_mode == Shader::MODE_SPATIAL && shader_type == VisualShader::TYPE_FRAGMENT) { + String name = get_input_port_name(p_index); + return (name == "Normal" || name == "Rim" || name == "Alpha Scissor"); + } + return false; +} + +String VisualShaderNodeOutput::get_caption() const { + return TTR("Output"); +} + +String VisualShaderNodeOutput::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + int idx = 0; + int count = 0; + + String code; + while (ports[idx].mode != Shader::MODE_MAX) { + if (ports[idx].mode == shader_mode && ports[idx].shader_type == shader_type) { + + if (p_input_vars[count] != String()) { + String s = ports[idx].string; + if (s.find(":") != -1) { + code += "\t" + s.get_slicec(':', 0) + " = " + p_input_vars[count] + "." + s.get_slicec(':', 1) + ";\n"; + } else { + code += "\t" + s + " = " + p_input_vars[count] + ";\n"; + } + } + count++; + } + idx++; + } + + return code; +} + +VisualShaderNodeOutput::VisualShaderNodeOutput() { +} + +/////////////////////////// + +void VisualShaderNodeUniform::set_uniform_name(const String &p_name) { + uniform_name = p_name; + emit_signal("name_changed"); + emit_changed(); +} + +String VisualShaderNodeUniform::get_uniform_name() const { + return uniform_name; +} + +void VisualShaderNodeUniform::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_uniform_name", "name"), &VisualShaderNodeUniform::set_uniform_name); + ClassDB::bind_method(D_METHOD("get_uniform_name"), &VisualShaderNodeUniform::get_uniform_name); + + ADD_PROPERTY(PropertyInfo(Variant::STRING, "uniform_name"), "set_uniform_name", "get_uniform_name"); +} + +VisualShaderNodeUniform::VisualShaderNodeUniform() { +} diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h new file mode 100644 index 0000000000..6ff1c9a9fe --- /dev/null +++ b/scene/resources/visual_shader.h @@ -0,0 +1,284 @@ +#ifndef VISUAL_SHADER_H +#define VISUAL_SHADER_H + +#include "scene/resources/shader.h" +#include "string_builder.h" + +class VisualShaderNodeUniform; +class VisualShaderNode; + +class VisualShader : public Shader { + GDCLASS(VisualShader, Shader) +public: + enum Type { + TYPE_VERTEX, + TYPE_FRAGMENT, + TYPE_LIGHT, + TYPE_MAX + }; + + struct Connection { + int from_node; + int from_port; + int to_node; + int to_port; + }; + + struct DefaultTextureParam { + StringName name; + Ref<Texture> param; + }; + +private: + struct Node { + Ref<VisualShaderNode> node; + Vector2 position; + }; + + struct Graph { + Map<int, Node> nodes; + List<Connection> connections; + } graph[TYPE_MAX]; + + Shader::Mode shader_mode; + + Array _get_node_connections(Type p_type) const; + + Vector2 graph_offset; + + struct RenderModeEnums { + Shader::Mode mode; + const char *string; + }; + + HashMap<String, int> modes; + Set<StringName> flags; + + static RenderModeEnums render_mode_enums[]; + + volatile mutable bool dirty; + void _queue_update(); + + union ConnectionKey { + + struct { + uint64_t node : 32; + uint64_t port : 32; + }; + uint64_t key; + bool operator<(const ConnectionKey &p_key) const { + return key < p_key.key; + } + }; + + Error _write_node(Type p_type, StringBuilder &global_code, StringBuilder &code, Vector<DefaultTextureParam> &def_tex_params, const VMap<ConnectionKey, const List<Connection>::Element *> &input_connections, const VMap<ConnectionKey, const List<Connection>::Element *> &output_connections, int node, Set<int> &processed, bool for_preview) const; + + void _input_type_changed(Type p_type, int p_id); + +protected: + virtual void _update_shader() const; + static void _bind_methods(); + + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; + +public: + enum { + NODE_ID_INVALID = -1, + NODE_ID_OUTPUT = 0, + }; + + void add_node(Type p_type, const Ref<VisualShaderNode> &p_node, const Vector2 &p_position, int p_id); + void set_node_position(Type p_type, int p_id, const Vector2 &p_position); + + Vector2 get_node_position(Type p_type, int p_id) const; + Ref<VisualShaderNode> get_node(Type p_type, int p_id) const; + + Vector<int> get_node_list(Type p_type) const; + int get_valid_node_id(Type p_type) const; + + int find_node_id(Type p_type, const Ref<VisualShaderNode> &p_node) const; + void remove_node(Type p_type, int p_id); + + bool is_node_connection(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const; + bool can_connect_nodes(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const; + Error connect_nodes(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port); + void disconnect_nodes(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port); + + void get_node_connections(Type p_type, List<Connection> *r_connections) const; + + void set_mode(Mode p_mode); + virtual Mode get_mode() const; + + void set_graph_offset(const Vector2 &p_offset); + Vector2 get_graph_offset() const; + + String generate_preview_shader(Type p_type, int p_node, int p_port, Vector<DefaultTextureParam> &r_default_tex_params) const; + + String validate_uniform_name(const String &p_name, const Ref<VisualShaderNodeUniform> &p_uniform) const; + + VisualShader(); +}; + +VARIANT_ENUM_CAST(VisualShader::Type) +/// +/// +/// + +class VisualShaderNode : public Resource { + GDCLASS(VisualShaderNode, Resource) + + int port_preview; + + Map<int, Variant> default_input_values; + + Array _get_default_input_values() const; + void _set_default_input_values(const Array &p_values); + +protected: + static void _bind_methods(); + +public: + enum PortType { + PORT_TYPE_SCALAR, + PORT_TYPE_VECTOR, + PORT_TYPE_TRANSFORM, + }; + + virtual String get_caption() const = 0; + + virtual int get_input_port_count() const = 0; + virtual PortType get_input_port_type(int p_port) const = 0; + virtual String get_input_port_name(int p_port) const = 0; + + void set_input_port_default_value(int p_port, const Variant &p_value); + Variant get_input_port_default_value(int p_port) const; // if NIL (default if node does not set anything) is returned, it means no default value is wanted if disconnected, thus no input var must be supplied (empty string will be supplied) + + virtual int get_output_port_count() const = 0; + virtual PortType get_output_port_type(int p_port) const = 0; + virtual String get_output_port_name(int p_port) const = 0; + + void set_output_port_for_preview(int p_index); + int get_output_port_for_preview() const; + + virtual bool is_port_separator(int p_index) const; + + virtual Vector<StringName> get_editable_properties() const; + + virtual Vector<VisualShader::DefaultTextureParam> get_default_texture_parameters(VisualShader::Type p_type, int p_id) const; + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const = 0; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + virtual String get_warning(Shader::Mode p_mode, VisualShader::Type p_type) const; + + VisualShaderNode(); +}; +///// + +class VisualShaderNodeInput : public VisualShaderNode { + GDCLASS(VisualShaderNodeInput, VisualShaderNode) + + friend class VisualShader; + VisualShader::Type shader_type; + Shader::Mode shader_mode; + + struct Port { + Shader::Mode mode; + VisualShader::Type shader_type; + PortType type; + const char *name; + const char *string; + }; + + static const Port ports[]; + static const Port preview_ports[]; + + String input_name; + +protected: + static void _bind_methods(); + void _validate_property(PropertyInfo &property) const; + +public: + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String get_caption() const; + + virtual String generate_code_for_preview(VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; + + void set_input_name(String p_name); + String get_input_name() const; + + int get_input_index_count() const; + PortType get_input_index_type(int p_index) const; + String get_input_index_name(int p_index) const; + + PortType get_input_type_by_name(String p_name) const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeInput(); +}; + +/// + +class VisualShaderNodeOutput : public VisualShaderNode { + GDCLASS(VisualShaderNodeOutput, VisualShaderNode) +public: + friend class VisualShader; + VisualShader::Type shader_type; + Shader::Mode shader_mode; + + struct Port { + Shader::Mode mode; + VisualShader::Type shader_type; + PortType type; + const char *name; + const char *string; + }; + + static const Port ports[]; + +public: + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + Variant get_input_port_default_value(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual bool is_port_separator(int p_index) const; + + virtual String get_caption() const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; + + VisualShaderNodeOutput(); +}; + +class VisualShaderNodeUniform : public VisualShaderNode { + GDCLASS(VisualShaderNodeUniform, VisualShaderNode) + + String uniform_name; + +protected: + static void _bind_methods(); + +public: + void set_uniform_name(const String &p_name); + String get_uniform_name() const; + + VisualShaderNodeUniform(); +}; + +#endif // VISUAL_SHADER_H diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp new file mode 100644 index 0000000000..90af312870 --- /dev/null +++ b/scene/resources/visual_shader_nodes.cpp @@ -0,0 +1,1879 @@ +#include "visual_shader_nodes.h" +////////////// Scalar + +String VisualShaderNodeScalarConstant::get_caption() const { + return "Scalar"; +} + +int VisualShaderNodeScalarConstant::get_input_port_count() const { + return 0; +} +VisualShaderNodeScalarConstant::PortType VisualShaderNodeScalarConstant::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarConstant::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeScalarConstant::get_output_port_count() const { + return 1; +} +VisualShaderNodeScalarConstant::PortType VisualShaderNodeScalarConstant::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarConstant::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeScalarConstant::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = " + vformat("%.6f", constant) + ";\n"; +} + +void VisualShaderNodeScalarConstant::set_constant(float p_value) { + + constant = p_value; + emit_changed(); +} + +float VisualShaderNodeScalarConstant::get_constant() const { + + return constant; +} + +Vector<StringName> VisualShaderNodeScalarConstant::get_editable_properties() const { + Vector<StringName> props; + props.push_back("constant"); + return props; +} + +void VisualShaderNodeScalarConstant::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_constant", "value"), &VisualShaderNodeScalarConstant::set_constant); + ClassDB::bind_method(D_METHOD("get_constant"), &VisualShaderNodeScalarConstant::get_constant); + + ADD_PROPERTY(PropertyInfo(Variant::REAL, "constant"), "set_constant", "get_constant"); +} + +VisualShaderNodeScalarConstant::VisualShaderNodeScalarConstant() { + constant = 0; +} + +////////////// Color + +String VisualShaderNodeColorConstant::get_caption() const { + return "Color"; +} + +int VisualShaderNodeColorConstant::get_input_port_count() const { + return 0; +} +VisualShaderNodeColorConstant::PortType VisualShaderNodeColorConstant::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeColorConstant::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeColorConstant::get_output_port_count() const { + return 2; +} +VisualShaderNodeColorConstant::PortType VisualShaderNodeColorConstant::get_output_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeColorConstant::get_output_port_name(int p_port) const { + return p_port == 0 ? "" : "alpha"; //no output port means the editor will be used as port +} + +String VisualShaderNodeColorConstant::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + String code; + code += "\t" + p_output_vars[0] + " = " + vformat("vec3(%.6f,%.6f,%.6f)", constant.r, constant.g, constant.b) + ";\n"; + code += "\t" + p_output_vars[1] + " = " + vformat("%.6f", constant.a) + ";\n"; + + return code; +} + +void VisualShaderNodeColorConstant::set_constant(Color p_value) { + + constant = p_value; + emit_changed(); +} + +Color VisualShaderNodeColorConstant::get_constant() const { + + return constant; +} + +Vector<StringName> VisualShaderNodeColorConstant::get_editable_properties() const { + Vector<StringName> props; + props.push_back("constant"); + return props; +} + +void VisualShaderNodeColorConstant::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_constant", "value"), &VisualShaderNodeColorConstant::set_constant); + ClassDB::bind_method(D_METHOD("get_constant"), &VisualShaderNodeColorConstant::get_constant); + + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "constant"), "set_constant", "get_constant"); +} + +VisualShaderNodeColorConstant::VisualShaderNodeColorConstant() { + constant = Color(1, 1, 1, 1); +} + +////////////// Vector + +String VisualShaderNodeVec3Constant::get_caption() const { + return "Vector"; +} + +int VisualShaderNodeVec3Constant::get_input_port_count() const { + return 0; +} +VisualShaderNodeVec3Constant::PortType VisualShaderNodeVec3Constant::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVec3Constant::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeVec3Constant::get_output_port_count() const { + return 1; +} +VisualShaderNodeVec3Constant::PortType VisualShaderNodeVec3Constant::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVec3Constant::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeVec3Constant::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = " + vformat("vec3(%.6f,%.6f,%.6f)", constant.x, constant.y, constant.z) + ";\n"; +} + +void VisualShaderNodeVec3Constant::set_constant(Vector3 p_value) { + + constant = p_value; + emit_changed(); +} + +Vector3 VisualShaderNodeVec3Constant::get_constant() const { + + return constant; +} + +Vector<StringName> VisualShaderNodeVec3Constant::get_editable_properties() const { + Vector<StringName> props; + props.push_back("constant"); + return props; +} + +void VisualShaderNodeVec3Constant::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_constant", "value"), &VisualShaderNodeVec3Constant::set_constant); + ClassDB::bind_method(D_METHOD("get_constant"), &VisualShaderNodeVec3Constant::get_constant); + + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant"), "set_constant", "get_constant"); +} + +VisualShaderNodeVec3Constant::VisualShaderNodeVec3Constant() { +} + +////////////// Transform + +String VisualShaderNodeTransformConstant::get_caption() const { + return "Transform4x3"; +} + +int VisualShaderNodeTransformConstant::get_input_port_count() const { + return 0; +} +VisualShaderNodeTransformConstant::PortType VisualShaderNodeTransformConstant::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeTransformConstant::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeTransformConstant::get_output_port_count() const { + return 1; +} +VisualShaderNodeTransformConstant::PortType VisualShaderNodeTransformConstant::get_output_port_type(int p_port) const { + return PORT_TYPE_TRANSFORM; +} +String VisualShaderNodeTransformConstant::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeTransformConstant::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + Transform t = constant; + t.basis.transpose(); + + String code = "\t" + p_output_vars[0] + " = mat4("; + code += vformat("vec4(%.6f,%.6f,%.6f,0.0),", t.basis[0].x, t.basis[0].y, t.basis[0].z); + code += vformat("vec4(%.6f,%.6f,%.6f,0.0),", t.basis[1].x, t.basis[1].y, t.basis[1].z); + code += vformat("vec4(%.6f,%.6f,%.6f,0.0),", t.basis[2].x, t.basis[2].y, t.basis[2].z); + code += vformat("vec4(%.6f,%.6f,%.6f,1.0) );\n", t.origin.x, t.origin.y, t.origin.z); + return code; +} + +void VisualShaderNodeTransformConstant::set_constant(Transform p_value) { + + constant = p_value; + emit_changed(); +} + +Transform VisualShaderNodeTransformConstant::get_constant() const { + + return constant; +} + +Vector<StringName> VisualShaderNodeTransformConstant::get_editable_properties() const { + Vector<StringName> props; + props.push_back("constant"); + return props; +} + +void VisualShaderNodeTransformConstant::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_constant", "value"), &VisualShaderNodeTransformConstant::set_constant); + ClassDB::bind_method(D_METHOD("get_constant"), &VisualShaderNodeTransformConstant::get_constant); + + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "constant"), "set_constant", "get_constant"); +} + +VisualShaderNodeTransformConstant::VisualShaderNodeTransformConstant() { +} + +////////////// Texture + +String VisualShaderNodeTexture::get_caption() const { + return "Texture"; +} + +int VisualShaderNodeTexture::get_input_port_count() const { + return 2; +} +VisualShaderNodeTexture::PortType VisualShaderNodeTexture::get_input_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeTexture::get_input_port_name(int p_port) const { + return p_port == 0 ? "uv" : "lod"; +} + +int VisualShaderNodeTexture::get_output_port_count() const { + return 2; +} +VisualShaderNodeTexture::PortType VisualShaderNodeTexture::get_output_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeTexture::get_output_port_name(int p_port) const { + return p_port == 0 ? "rgb" : "alpha"; +} + +static String make_unique_id(VisualShader::Type p_type, int p_id, const String &p_name) { + + static const char *typepf[VisualShader::TYPE_MAX] = { "vtx", "frg", "lgt" }; + return p_name + "_" + String(typepf[p_type]) + "_" + itos(p_id); +} + +Vector<VisualShader::DefaultTextureParam> VisualShaderNodeTexture::get_default_texture_parameters(VisualShader::Type p_type, int p_id) const { + VisualShader::DefaultTextureParam dtp; + dtp.name = make_unique_id(p_type, p_id, "tex"); + dtp.param = texture; + Vector<VisualShader::DefaultTextureParam> ret; + ret.push_back(dtp); + return ret; +} + +String VisualShaderNodeTexture::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + + if (source == SOURCE_TEXTURE) { + + String u = "uniform sampler2D " + make_unique_id(p_type, p_id, "tex"); + switch (texture_type) { + case TYPE_DATA: break; + case TYPE_COLOR: u += " : hint_color"; break; + case TYPE_NORMALMAP: u += " : hint_normal"; break; + } + return u + ";"; + } + + return String(); +} + +String VisualShaderNodeTexture::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + if (source == SOURCE_TEXTURE) { + String id = make_unique_id(p_type, p_id, "tex"); + String code; + if (p_input_vars[0] == String()) { //none bound, do nothing + + code += "\tvec4 " + id + "_read = vec4(0.0);\n"; + + } else if (p_input_vars[1] == String()) { + //no lod + code += "\tvec4 " + id + "_read = texture( " + id + " , " + p_input_vars[0] + ".xy );\n"; + } else { + code += "\tvec4 " + id + "_read = textureLod( " + id + " , " + p_input_vars[0] + ".xy , " + p_input_vars[1] + " );\n"; + } + + code += "\t" + p_output_vars[0] + " = " + id + "_read.rgb;\n"; + code += "\t" + p_output_vars[1] + " = " + id + "_read.a;\n"; + return code; + } + + if (source == SOURCE_SCREEN && (p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { + + String code = "\t{\n"; + if (p_input_vars[0] == String()) { //none bound, do nothing + + code += "\t\tvec4 _tex_read = vec4(0.0);\n"; + + } else if (p_input_vars[1] == String()) { + //no lod + code += "\t\tvec4 _tex_read = textureLod( SCREEN_TEXTURE , " + p_input_vars[0] + ".xy, 0.0 );\n"; + } else { + code += "\t\tvec4 _tex_read = textureLod( SCREEN_TEXTURE , " + p_input_vars[0] + ".xy , " + p_input_vars[1] + " );\n"; + } + + code += "\t\t" + p_output_vars[0] + " = _tex_read.rgb;\n"; + code += "\t\t" + p_output_vars[1] + " = _tex_read.a;\n"; + code += "\t}\n"; + return code; + } + + if (source == SOURCE_2D_TEXTURE && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { + + String code = "\t{\n"; + if (p_input_vars[0] == String()) { //none bound, do nothing + + code += "\t\tvec4 _tex_read = vec4(0.0);\n"; + + } else if (p_input_vars[1] == String()) { + //no lod + code += "\t\tvec4 _tex_read = texture( TEXTURE , " + p_input_vars[0] + ".xy );\n"; + } else { + code += "\t\tvec4 _tex_read = textureLod( TEXTURE , " + p_input_vars[0] + ".xy , " + p_input_vars[1] + " );\n"; + } + + code += "\t\t" + p_output_vars[0] + " = _tex_read.rgb;\n"; + code += "\t\t" + p_output_vars[1] + " = _tex_read.a;\n"; + code += "\t}\n"; + return code; + } + + if (source == SOURCE_2D_NORMAL && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { + + String code = "\t{\n"; + if (p_input_vars[0] == String()) { //none bound, do nothing + + code += "\t\tvec4 _tex_read = vec4(0.0);\n"; + + } else if (p_input_vars[1] == String()) { + //no lod + code += "\t\tvec4 _tex_read = texture( NORMAL_TEXTURE , " + p_input_vars[0] + ".xy );\n"; + } else { + code += "\t\tvec4 _tex_read = textureLod( NORMAL_TEXTURE , " + p_input_vars[0] + ".xy , " + p_input_vars[1] + " );\n"; + } + + code += "\t\t" + p_output_vars[0] + " = _tex_read.rgb;\n"; + code += "\t\t" + p_output_vars[1] + " = _tex_read.a;\n"; + code += "\t}\n"; + return code; + } + + //none + String code; + code += "\t" + p_output_vars[0] + " = vec3(0.0);\n"; + code += "\t" + p_output_vars[1] + " = 1.0;\n"; + return code; +} + +void VisualShaderNodeTexture::set_source(Source p_source) { + source = p_source; + emit_changed(); + emit_signal("editor_refresh_request"); +} + +VisualShaderNodeTexture::Source VisualShaderNodeTexture::get_source() const { + return source; +} + +void VisualShaderNodeTexture::set_texture(Ref<Texture> p_value) { + + texture = p_value; + emit_changed(); +} + +Ref<Texture> VisualShaderNodeTexture::get_texture() const { + + return texture; +} + +void VisualShaderNodeTexture::set_texture_type(TextureType p_type) { + texture_type = p_type; + emit_changed(); +} + +VisualShaderNodeTexture::TextureType VisualShaderNodeTexture::get_texture_type() const { + return texture_type; +} + +Vector<StringName> VisualShaderNodeTexture::get_editable_properties() const { + Vector<StringName> props; + props.push_back("source"); + if (source == SOURCE_TEXTURE) { + props.push_back("texture"); + props.push_back("texture_type"); + } + return props; +} + +String VisualShaderNodeTexture::get_warning(Shader::Mode p_mode, VisualShader::Type p_type) const { + + if (source == SOURCE_TEXTURE) { + return String(); // all good + } + + if (source == SOURCE_SCREEN && (p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { + + return String(); // all good + } + + if (source == SOURCE_2D_TEXTURE && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { + + return String(); // all good + } + + if (source == SOURCE_2D_NORMAL && p_mode == Shader::MODE_CANVAS_ITEM) { + + return String(); // all good + } + + return TTR("Invalid source for shader."); +} + +void VisualShaderNodeTexture::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_source", "value"), &VisualShaderNodeTexture::set_source); + ClassDB::bind_method(D_METHOD("get_source"), &VisualShaderNodeTexture::get_source); + + ClassDB::bind_method(D_METHOD("set_texture", "value"), &VisualShaderNodeTexture::set_texture); + ClassDB::bind_method(D_METHOD("get_texture"), &VisualShaderNodeTexture::get_texture); + + ClassDB::bind_method(D_METHOD("set_texture_type", "value"), &VisualShaderNodeTexture::set_texture_type); + ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeTexture::get_texture_type); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "source", PROPERTY_HINT_ENUM, "Texture,Screen,Texture2D,NormalMap2D"), "set_source", "get_source"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normalmap"), "set_texture_type", "get_texture_type"); + + BIND_ENUM_CONSTANT(SOURCE_TEXTURE); + BIND_ENUM_CONSTANT(SOURCE_SCREEN); + BIND_ENUM_CONSTANT(SOURCE_2D_TEXTURE); + BIND_ENUM_CONSTANT(SOURCE_2D_NORMAL); + BIND_ENUM_CONSTANT(TYPE_DATA); + BIND_ENUM_CONSTANT(TYPE_COLOR); + BIND_ENUM_CONSTANT(TYPE_NORMALMAP); +} + +VisualShaderNodeTexture::VisualShaderNodeTexture() { + texture_type = TYPE_DATA; + source = SOURCE_TEXTURE; +} + +////////////// CubeMap + +String VisualShaderNodeCubeMap::get_caption() const { + return "CubeMap"; +} + +int VisualShaderNodeCubeMap::get_input_port_count() const { + return 2; +} +VisualShaderNodeCubeMap::PortType VisualShaderNodeCubeMap::get_input_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeCubeMap::get_input_port_name(int p_port) const { + return p_port == 0 ? "uv" : "lod"; +} + +int VisualShaderNodeCubeMap::get_output_port_count() const { + return 2; +} +VisualShaderNodeCubeMap::PortType VisualShaderNodeCubeMap::get_output_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeCubeMap::get_output_port_name(int p_port) const { + return p_port == 0 ? "rgb" : "alpha"; +} + +Vector<VisualShader::DefaultTextureParam> VisualShaderNodeCubeMap::get_default_texture_parameters(VisualShader::Type p_type, int p_id) const { + VisualShader::DefaultTextureParam dtp; + dtp.name = make_unique_id(p_type, p_id, "cube"); + dtp.param = cube_map; + Vector<VisualShader::DefaultTextureParam> ret; + ret.push_back(dtp); + return ret; +} + +String VisualShaderNodeCubeMap::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + + String u = "uniform sampler2DCube " + make_unique_id(p_type, p_id, "cube"); + switch (texture_type) { + case TYPE_DATA: break; + case TYPE_COLOR: u += " : hint_color"; break; + case TYPE_NORMALMAP: u += " : hint_normal"; break; + } + return u + ";"; +} + +String VisualShaderNodeCubeMap::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + String id = make_unique_id(p_type, p_id, "cube"); + String code; + if (p_input_vars[0] == String()) { //none bound, do nothing + + code += "\tvec4 " + id + "_read = vec4(0.0);\n"; + + } else if (p_input_vars[1] == String()) { + //no lod + code += "\tvec4 " + id + "_read = texture( " + id + " , " + p_input_vars[0] + " );\n"; + } else { + code += "\tvec4 " + id + "_read = textureLod( " + id + " , " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; + } + + code += "\t" + p_output_vars[0] + " = " + id + "_read.rgb;\n"; + code += "\t" + p_output_vars[1] + " = " + id + "_read.a;\n"; + return code; +} + +void VisualShaderNodeCubeMap::set_cube_map(Ref<CubeMap> p_value) { + + cube_map = p_value; + emit_changed(); +} + +Ref<CubeMap> VisualShaderNodeCubeMap::get_cube_map() const { + + return cube_map; +} + +void VisualShaderNodeCubeMap::set_texture_type(TextureType p_type) { + texture_type = p_type; + emit_changed(); +} + +VisualShaderNodeCubeMap::TextureType VisualShaderNodeCubeMap::get_texture_type() const { + return texture_type; +} + +Vector<StringName> VisualShaderNodeCubeMap::get_editable_properties() const { + Vector<StringName> props; + props.push_back("cube_map"); + props.push_back("texture_type"); + return props; +} + +void VisualShaderNodeCubeMap::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_cube_map", "value"), &VisualShaderNodeCubeMap::set_cube_map); + ClassDB::bind_method(D_METHOD("get_cube_map"), &VisualShaderNodeCubeMap::get_cube_map); + + ClassDB::bind_method(D_METHOD("set_texture_type", "value"), &VisualShaderNodeCubeMap::set_texture_type); + ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeCubeMap::get_texture_type); + + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "cube_map", PROPERTY_HINT_RESOURCE_TYPE, "CubeMap"), "set_cube_map", "get_cube_map"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normalmap"), "set_texture_type", "get_texture_type"); +} + +VisualShaderNodeCubeMap::VisualShaderNodeCubeMap() { + texture_type = TYPE_DATA; +} +////////////// Scalar Op + +String VisualShaderNodeScalarOp::get_caption() const { + return "ScalarOp"; +} + +int VisualShaderNodeScalarOp::get_input_port_count() const { + return 2; +} +VisualShaderNodeScalarOp::PortType VisualShaderNodeScalarOp::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarOp::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeScalarOp::get_output_port_count() const { + return 1; +} +VisualShaderNodeScalarOp::PortType VisualShaderNodeScalarOp::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarOp::get_output_port_name(int p_port) const { + return "op"; //no output port means the editor will be used as port +} + +String VisualShaderNodeScalarOp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + String code = "\t" + p_output_vars[0] + " = "; + switch (op) { + + case OP_ADD: code += p_input_vars[0] + " + " + p_input_vars[1] + ";\n"; break; + case OP_SUB: code += p_input_vars[0] + " - " + p_input_vars[1] + ";\n"; break; + case OP_MUL: code += p_input_vars[0] + " * " + p_input_vars[1] + ";\n"; break; + case OP_DIV: code += p_input_vars[0] + " / " + p_input_vars[1] + ";\n"; break; + case OP_MOD: code += "mod( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_POW: code += "pow( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_MAX: code += "max( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_MIN: code += "min( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_ATAN2: code += "atan( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + } + + return code; +} + +void VisualShaderNodeScalarOp::set_operator(Operator p_op) { + + op = p_op; + emit_changed(); +} + +VisualShaderNodeScalarOp::Operator VisualShaderNodeScalarOp::get_operator() const { + + return op; +} + +Vector<StringName> VisualShaderNodeScalarOp::get_editable_properties() const { + Vector<StringName> props; + props.push_back("operator"); + return props; +} + +void VisualShaderNodeScalarOp::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeScalarOp::set_operator); + ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeScalarOp::get_operator); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "Add,Sub,Multiply,Divide,Remainder,Power,Max,Min,Atan2"), "set_operator", "get_operator"); + + BIND_ENUM_CONSTANT(OP_ADD); + BIND_ENUM_CONSTANT(OP_SUB); + BIND_ENUM_CONSTANT(OP_MUL); + BIND_ENUM_CONSTANT(OP_DIV); + BIND_ENUM_CONSTANT(OP_MOD); + BIND_ENUM_CONSTANT(OP_POW); + BIND_ENUM_CONSTANT(OP_MAX); + BIND_ENUM_CONSTANT(OP_MIN); + BIND_ENUM_CONSTANT(OP_ATAN2); +} + +VisualShaderNodeScalarOp::VisualShaderNodeScalarOp() { + op = OP_ADD; + set_input_port_default_value(0, 0.0); + set_input_port_default_value(1, 0.0); +} + +////////////// Vector Op + +String VisualShaderNodeVectorOp::get_caption() const { + return "VecOp"; +} + +int VisualShaderNodeVectorOp::get_input_port_count() const { + return 2; +} +VisualShaderNodeVectorOp::PortType VisualShaderNodeVectorOp::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorOp::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeVectorOp::get_output_port_count() const { + return 1; +} +VisualShaderNodeVectorOp::PortType VisualShaderNodeVectorOp::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorOp::get_output_port_name(int p_port) const { + return "op"; //no output port means the editor will be used as port +} + +String VisualShaderNodeVectorOp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + String code = "\t" + p_output_vars[0] + " = "; + switch (op) { + + case OP_ADD: code += p_input_vars[0] + " + " + p_input_vars[1] + ";\n"; break; + case OP_SUB: code += p_input_vars[0] + " - " + p_input_vars[1] + ";\n"; break; + case OP_MUL: code += p_input_vars[0] + " * " + p_input_vars[1] + ";\n"; break; + case OP_DIV: code += p_input_vars[0] + " / " + p_input_vars[1] + ";\n"; break; + case OP_MOD: code += "mod( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_POW: code += "pow( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_MAX: code += "max( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_MIN: code += "min( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + case OP_CROSS: code += "cross( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; break; + } + + return code; +} + +void VisualShaderNodeVectorOp::set_operator(Operator p_op) { + + op = p_op; + emit_changed(); +} + +VisualShaderNodeVectorOp::Operator VisualShaderNodeVectorOp::get_operator() const { + + return op; +} + +Vector<StringName> VisualShaderNodeVectorOp::get_editable_properties() const { + Vector<StringName> props; + props.push_back("operator"); + return props; +} + +void VisualShaderNodeVectorOp::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeVectorOp::set_operator); + ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeVectorOp::get_operator); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "Add,Sub,Multiply,Divide,Remainder,Power,Max,Min,Cross"), "set_operator", "get_operator"); + + BIND_ENUM_CONSTANT(OP_ADD); + BIND_ENUM_CONSTANT(OP_SUB); + BIND_ENUM_CONSTANT(OP_MUL); + BIND_ENUM_CONSTANT(OP_DIV); + BIND_ENUM_CONSTANT(OP_MOD); + BIND_ENUM_CONSTANT(OP_POW); + BIND_ENUM_CONSTANT(OP_MAX); + BIND_ENUM_CONSTANT(OP_MIN); + BIND_ENUM_CONSTANT(OP_CROSS); +} + +VisualShaderNodeVectorOp::VisualShaderNodeVectorOp() { + op = OP_ADD; + set_input_port_default_value(0, Vector3()); + set_input_port_default_value(1, Vector3()); +} + +////////////// Color Op + +String VisualShaderNodeColorOp::get_caption() const { + return "ColorOp"; +} + +int VisualShaderNodeColorOp::get_input_port_count() const { + return 2; +} +VisualShaderNodeColorOp::PortType VisualShaderNodeColorOp::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeColorOp::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeColorOp::get_output_port_count() const { + return 1; +} +VisualShaderNodeColorOp::PortType VisualShaderNodeColorOp::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeColorOp::get_output_port_name(int p_port) const { + return "op"; //no output port means the editor will be used as port +} + +String VisualShaderNodeColorOp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + String code; + static const char *axisn[3] = { "x", "y", "z" }; + switch (op) { + case OP_SCREEN: { + + code += "\t" + p_output_vars[0] + "=vec3(1.0)-(vec3(1.0)-" + p_input_vars[0] + ")*(vec3(1.0)-" + p_input_vars[1] + ");\n"; + } break; + case OP_DIFFERENCE: { + + code += "\t" + p_output_vars[0] + "=abs(" + p_input_vars[0] + "-" + p_input_vars[1] + ");\n"; + } break; + case OP_DARKEN: { + + code += "\t" + p_output_vars[0] + "=min(" + p_input_vars[0] + "," + p_input_vars[1] + ");\n"; + } break; + case OP_LIGHTEN: { + + code += "\t" + p_output_vars[0] + "=max(" + p_input_vars[0] + "," + p_input_vars[1] + ");\n"; + + } break; + case OP_OVERLAY: { + + for (int i = 0; i < 3; i++) { + code += "\t{\n"; + code += "\t\tfloat base=" + p_input_vars[0] + "." + axisn[i] + ";\n"; + code += "\t\tfloat blend=" + p_input_vars[1] + "." + axisn[i] + ";\n"; + code += "\t\tif (base < 0.5) {\n"; + code += "\t\t\t" + p_output_vars[0] + "." + axisn[i] + " = 2.0 * base * blend;\n"; + code += "\t\t} else {\n"; + code += "\t\t\t" + p_output_vars[0] + "." + axisn[i] + " = 1.0 - 2.0 * (1.0 - blend) * (1.0 - base);\n"; + code += "\t\t}\n"; + code += "\t}\n"; + } + + } break; + case OP_DODGE: { + + code += "\t" + p_output_vars[0] + "=(" + p_input_vars[0] + ")/(vec3(1.0)-" + p_input_vars[1] + ");\n"; + + } break; + case OP_BURN: { + + code += "\t" + p_output_vars[0] + "=vec3(1.0)-(vec3(1.0)-" + p_input_vars[0] + ")/(" + p_input_vars[1] + ");\n"; + } break; + case OP_SOFT_LIGHT: { + + for (int i = 0; i < 3; i++) { + code += "\t{\n"; + code += "\t\tfloat base=" + p_input_vars[0] + "." + axisn[i] + ";\n"; + code += "\t\tfloat blend=" + p_input_vars[1] + "." + axisn[i] + ";\n"; + code += "\t\tif (base < 0.5) {\n"; + code += "\t\t\t" + p_output_vars[0] + "." + axisn[i] + " = (base * (blend+0.5));\n"; + code += "\t\t} else {\n"; + code += "\t\t\t" + p_output_vars[0] + "." + axisn[i] + " = (1.0 - (1.0-base) * (1.0-(blend-0.5)));\n"; + code += "\t\t}\n"; + code += "\t}\n"; + } + + } break; + case OP_HARD_LIGHT: { + + for (int i = 0; i < 3; i++) { + code += "\t{\n"; + code += "\t\tfloat base=" + p_input_vars[0] + "." + axisn[i] + ";\n"; + code += "\t\tfloat blend=" + p_input_vars[1] + "." + axisn[i] + ";\n"; + code += "\t\tif (base < 0.5) {\n"; + code += "\t\t\t" + p_output_vars[0] + "." + axisn[i] + " = (base * (2.0*blend));\n"; + code += "\t\t} else {\n"; + code += "\t\t\t" + p_output_vars[0] + "." + axisn[i] + " = (1.0 - (1.0-base) * (1.0-2.0*(blend-0.5)));\n"; + code += "\t\t}\n"; + code += "\t}\n"; + } + + } break; + } + + return code; +} + +void VisualShaderNodeColorOp::set_operator(Operator p_op) { + + op = p_op; + emit_changed(); +} + +VisualShaderNodeColorOp::Operator VisualShaderNodeColorOp::get_operator() const { + + return op; +} + +Vector<StringName> VisualShaderNodeColorOp::get_editable_properties() const { + Vector<StringName> props; + props.push_back("operator"); + return props; +} + +void VisualShaderNodeColorOp::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeColorOp::set_operator); + ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeColorOp::get_operator); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "Screen,Difference,Darken,Lighten,Overlay,Dodge,Burn,SoftLight,HardLight"), "set_operator", "get_operator"); +} + +VisualShaderNodeColorOp::VisualShaderNodeColorOp() { + op = OP_SCREEN; + set_input_port_default_value(0, Vector3()); + set_input_port_default_value(1, Vector3()); +} + +////////////// Transform Mult + +String VisualShaderNodeTransformMult::get_caption() const { + return "TransMult"; +} + +int VisualShaderNodeTransformMult::get_input_port_count() const { + return 2; +} +VisualShaderNodeTransformMult::PortType VisualShaderNodeTransformMult::get_input_port_type(int p_port) const { + return PORT_TYPE_TRANSFORM; +} +String VisualShaderNodeTransformMult::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeTransformMult::get_output_port_count() const { + return 1; +} +VisualShaderNodeTransformMult::PortType VisualShaderNodeTransformMult::get_output_port_type(int p_port) const { + return PORT_TYPE_TRANSFORM; +} +String VisualShaderNodeTransformMult::get_output_port_name(int p_port) const { + return "mult"; //no output port means the editor will be used as port +} + +String VisualShaderNodeTransformMult::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + if (op == OP_AxB) { + return "\t" + p_output_vars[0] + " = " + p_input_vars[0] + " * " + p_input_vars[1] + ";\n"; + } else { + return "\t" + p_output_vars[0] + " = " + p_input_vars[1] + " * " + p_input_vars[0] + ";\n"; + } +} + +void VisualShaderNodeTransformMult::set_operator(Operator p_op) { + + op = p_op; + emit_changed(); +} + +VisualShaderNodeTransformMult::Operator VisualShaderNodeTransformMult::get_operator() const { + + return op; +} + +Vector<StringName> VisualShaderNodeTransformMult::get_editable_properties() const { + Vector<StringName> props; + props.push_back("operator"); + return props; +} + +void VisualShaderNodeTransformMult::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeTransformMult::set_operator); + ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeTransformMult::get_operator); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "A x B,B x A"), "set_operator", "get_operator"); +} + +VisualShaderNodeTransformMult::VisualShaderNodeTransformMult() { + op = OP_AxB; + set_input_port_default_value(0, Transform()); + set_input_port_default_value(1, Transform()); +} + +////////////// TransformVec Mult + +String VisualShaderNodeTransformVecMult::get_caption() const { + return "TransVecMult"; +} + +int VisualShaderNodeTransformVecMult::get_input_port_count() const { + return 2; +} +VisualShaderNodeTransformVecMult::PortType VisualShaderNodeTransformVecMult::get_input_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_TRANSFORM : PORT_TYPE_VECTOR; +} +String VisualShaderNodeTransformVecMult::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeTransformVecMult::get_output_port_count() const { + return 1; +} +VisualShaderNodeTransformVecMult::PortType VisualShaderNodeTransformVecMult::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeTransformVecMult::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeTransformVecMult::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + if (op == OP_AxB) { + return "\t" + p_output_vars[0] + " = ( " + p_input_vars[0] + " * vec4(" + p_input_vars[1] + ", 1.0) ).xyz;\n"; + } else if (op == OP_BxA) { + return "\t" + p_output_vars[0] + " = ( vec4(" + p_input_vars[1] + ", 1.0) * " + p_input_vars[0] + " ).xyz;\n"; + } else if (op == OP_3x3_AxB) { + return "\t" + p_output_vars[0] + " = ( " + p_input_vars[0] + " * vec4(" + p_input_vars[1] + ", 0.0) ).xyz;\n"; + } else { + return "\t" + p_output_vars[0] + " = ( vec4(" + p_input_vars[1] + ", 0.0) * " + p_input_vars[0] + " ).xyz;\n"; + } +} + +void VisualShaderNodeTransformVecMult::set_operator(Operator p_op) { + + op = p_op; + emit_changed(); +} + +VisualShaderNodeTransformVecMult::Operator VisualShaderNodeTransformVecMult::get_operator() const { + + return op; +} + +Vector<StringName> VisualShaderNodeTransformVecMult::get_editable_properties() const { + Vector<StringName> props; + props.push_back("operator"); + return props; +} + +void VisualShaderNodeTransformVecMult::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeTransformVecMult::set_operator); + ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeTransformVecMult::get_operator); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "A x B,B x A,A x B (3x3),B x A (3x3)"), "set_operator", "get_operator"); + + BIND_ENUM_CONSTANT(OP_AxB); + BIND_ENUM_CONSTANT(OP_BxA); + BIND_ENUM_CONSTANT(OP_3x3_AxB); + BIND_ENUM_CONSTANT(OP_3x3_BxA); +} + +VisualShaderNodeTransformVecMult::VisualShaderNodeTransformVecMult() { + op = OP_AxB; + set_input_port_default_value(0, Transform()); + set_input_port_default_value(1, Vector3()); +} + +////////////// Scalar Func + +String VisualShaderNodeScalarFunc::get_caption() const { + return "ScalarFunc"; +} + +int VisualShaderNodeScalarFunc::get_input_port_count() const { + return 1; +} +VisualShaderNodeScalarFunc::PortType VisualShaderNodeScalarFunc::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarFunc::get_input_port_name(int p_port) const { + return ""; +} + +int VisualShaderNodeScalarFunc::get_output_port_count() const { + return 1; +} +VisualShaderNodeScalarFunc::PortType VisualShaderNodeScalarFunc::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarFunc::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeScalarFunc::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + static const char *scalar_func_id[FUNC_NEGATE + 1] = { + "sin($)", + "cos($)", + "tan($)", + "asin($)", + "acos($)", + "atan($)", + "sinh($)", + "cosh($)", + "tanh($)", + "log($)", + "exp($)", + "sqrt($)", + "abs($)", + "sign($)", + "floor($)", + "round($)", + "ceil($)", + "fract($)", + "min(max($,0),1)", + "-($)", + }; + + return "\t" + p_output_vars[0] + " = " + String(scalar_func_id[func]).replace("$", p_input_vars[0]) + ";\n"; +} + +void VisualShaderNodeScalarFunc::set_function(Function p_func) { + + func = p_func; + emit_changed(); +} + +VisualShaderNodeScalarFunc::Function VisualShaderNodeScalarFunc::get_function() const { + + return func; +} + +Vector<StringName> VisualShaderNodeScalarFunc::get_editable_properties() const { + Vector<StringName> props; + props.push_back("function"); + return props; +} + +void VisualShaderNodeScalarFunc::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_function", "func"), &VisualShaderNodeScalarFunc::set_function); + ClassDB::bind_method(D_METHOD("get_function"), &VisualShaderNodeScalarFunc::get_function); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "Sin,Cos,Tan,ASin,ACos,ATan,SinH,CosH,TanH,Log,Exp,Sqrt,Abs,Sign,Floor,Round,Ceil,Frac,Saturate,Negate"), "set_function", "get_function"); + + BIND_ENUM_CONSTANT(FUNC_SIN); + BIND_ENUM_CONSTANT(FUNC_COS); + BIND_ENUM_CONSTANT(FUNC_TAN); + BIND_ENUM_CONSTANT(FUNC_ASIN); + BIND_ENUM_CONSTANT(FUNC_ACOS); + BIND_ENUM_CONSTANT(FUNC_ATAN); + BIND_ENUM_CONSTANT(FUNC_SINH); + BIND_ENUM_CONSTANT(FUNC_COSH); + BIND_ENUM_CONSTANT(FUNC_TANH); + BIND_ENUM_CONSTANT(FUNC_LOG); + BIND_ENUM_CONSTANT(FUNC_EXP); + BIND_ENUM_CONSTANT(FUNC_SQRT); + BIND_ENUM_CONSTANT(FUNC_ABS); + BIND_ENUM_CONSTANT(FUNC_SIGN); + BIND_ENUM_CONSTANT(FUNC_FLOOR); + BIND_ENUM_CONSTANT(FUNC_ROUND); + BIND_ENUM_CONSTANT(FUNC_CEIL); + BIND_ENUM_CONSTANT(FUNC_FRAC); + BIND_ENUM_CONSTANT(FUNC_SATURATE); + BIND_ENUM_CONSTANT(FUNC_NEGATE); +} + +VisualShaderNodeScalarFunc::VisualShaderNodeScalarFunc() { + func = FUNC_SIGN; + set_input_port_default_value(0, 0.0); +} + +////////////// Vector Func + +String VisualShaderNodeVectorFunc::get_caption() const { + return "VecFunc"; +} + +int VisualShaderNodeVectorFunc::get_input_port_count() const { + return 1; +} +VisualShaderNodeVectorFunc::PortType VisualShaderNodeVectorFunc::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorFunc::get_input_port_name(int p_port) const { + return ""; +} + +int VisualShaderNodeVectorFunc::get_output_port_count() const { + return 1; +} +VisualShaderNodeVectorFunc::PortType VisualShaderNodeVectorFunc::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorFunc::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeVectorFunc::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + static const char *vec_func_id[FUNC_HSV2RGB + 1] = { + "normalize($)", + "max(min($,vec3(1.0)),vec3(0.0))", + "-($)", + "1.0/($)", + "", + "", + }; + + String code; + + if (func == FUNC_RGB2HSV) { + code += "\t{\n"; + code += "\t\tvec3 c = " + p_input_vars[0] + ";\n"; + code += "\t\tvec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n"; + code += "\t\tvec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n"; + code += "\t\tvec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n"; + code += "\t\tfloat d = q.x - min(q.w, q.y);\n"; + code += "\t\tfloat e = 1.0e-10;\n"; + code += "\t\t" + p_output_vars[0] + "=vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);\n"; + code += "\t}\n"; + } else if (func == FUNC_HSV2RGB) { + code += "\t{\n"; + code += "\t\tvec3 c = " + p_input_vars[0] + ";\n"; + code += "\t\tvec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n"; + code += "\t\tvec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n"; + code += "\t\t" + p_output_vars[0] + "=c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n"; + code += "\t}\n"; + + } else { + code += "\t" + p_output_vars[0] + "=" + String(vec_func_id[func]).replace("$", p_input_vars[0]) + ";\n"; + } + + return code; +} + +void VisualShaderNodeVectorFunc::set_function(Function p_func) { + + func = p_func; + emit_changed(); +} + +VisualShaderNodeVectorFunc::Function VisualShaderNodeVectorFunc::get_function() const { + + return func; +} + +Vector<StringName> VisualShaderNodeVectorFunc::get_editable_properties() const { + Vector<StringName> props; + props.push_back("function"); + return props; +} + +void VisualShaderNodeVectorFunc::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_function", "func"), &VisualShaderNodeVectorFunc::set_function); + ClassDB::bind_method(D_METHOD("get_function"), &VisualShaderNodeVectorFunc::get_function); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "Normalize,Saturate,Negate,Reciprocal,RGB2HSV,HSV2RGB"), "set_function", "get_function"); + + BIND_ENUM_CONSTANT(FUNC_NORMALIZE); + BIND_ENUM_CONSTANT(FUNC_SATURATE); + BIND_ENUM_CONSTANT(FUNC_NEGATE); + BIND_ENUM_CONSTANT(FUNC_RECIPROCAL); + BIND_ENUM_CONSTANT(FUNC_RGB2HSV); + BIND_ENUM_CONSTANT(FUNC_HSV2RGB); +} + +VisualShaderNodeVectorFunc::VisualShaderNodeVectorFunc() { + func = FUNC_NORMALIZE; + set_input_port_default_value(0, Vector3()); +} + +////////////// Dot Product + +String VisualShaderNodeDotProduct::get_caption() const { + return "DotProd"; +} + +int VisualShaderNodeDotProduct::get_input_port_count() const { + return 2; +} +VisualShaderNodeDotProduct::PortType VisualShaderNodeDotProduct::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeDotProduct::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeDotProduct::get_output_port_count() const { + return 1; +} +VisualShaderNodeDotProduct::PortType VisualShaderNodeDotProduct::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeDotProduct::get_output_port_name(int p_port) const { + return "dot"; +} + +String VisualShaderNodeDotProduct::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = dot( " + p_input_vars[0] + " , " + p_input_vars[1] + " );\n"; +} + +VisualShaderNodeDotProduct::VisualShaderNodeDotProduct() { + set_input_port_default_value(0, Vector3()); + set_input_port_default_value(1, Vector3()); +} + +////////////// Vector Len + +String VisualShaderNodeVectorLen::get_caption() const { + return "VecLen"; +} + +int VisualShaderNodeVectorLen::get_input_port_count() const { + return 1; +} +VisualShaderNodeVectorLen::PortType VisualShaderNodeVectorLen::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorLen::get_input_port_name(int p_port) const { + return ""; +} + +int VisualShaderNodeVectorLen::get_output_port_count() const { + return 1; +} +VisualShaderNodeVectorLen::PortType VisualShaderNodeVectorLen::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeVectorLen::get_output_port_name(int p_port) const { + return "length"; +} + +String VisualShaderNodeVectorLen::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = length( " + p_input_vars[0] + " );\n"; +} + +VisualShaderNodeVectorLen::VisualShaderNodeVectorLen() { + set_input_port_default_value(0, Vector3()); +} + +////////////// Scalar Interp + +String VisualShaderNodeScalarInterp::get_caption() const { + return "ScalarInterp"; +} + +int VisualShaderNodeScalarInterp::get_input_port_count() const { + return 3; +} +VisualShaderNodeScalarInterp::PortType VisualShaderNodeScalarInterp::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarInterp::get_input_port_name(int p_port) const { + if (p_port == 0) { + return "a"; + } else if (p_port == 1) { + return "b"; + } else { + return "c"; + } +} + +int VisualShaderNodeScalarInterp::get_output_port_count() const { + return 1; +} +VisualShaderNodeScalarInterp::PortType VisualShaderNodeScalarInterp::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarInterp::get_output_port_name(int p_port) const { + return "mix"; +} + +String VisualShaderNodeScalarInterp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = mix( " + p_input_vars[0] + " , " + p_input_vars[1] + " , " + p_input_vars[2] + " );\n"; +} + +VisualShaderNodeScalarInterp::VisualShaderNodeScalarInterp() { + set_input_port_default_value(0, 0.0); + set_input_port_default_value(1, 0.0); + set_input_port_default_value(2, 0.0); +} + +////////////// Vector Interp + +String VisualShaderNodeVectorInterp::get_caption() const { + return "VecInterp"; +} + +int VisualShaderNodeVectorInterp::get_input_port_count() const { + return 3; +} +VisualShaderNodeVectorInterp::PortType VisualShaderNodeVectorInterp::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorInterp::get_input_port_name(int p_port) const { + if (p_port == 0) { + return "a"; + } else if (p_port == 1) { + return "b"; + } else { + return "c"; + } +} + +int VisualShaderNodeVectorInterp::get_output_port_count() const { + return 1; +} +VisualShaderNodeVectorInterp::PortType VisualShaderNodeVectorInterp::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorInterp::get_output_port_name(int p_port) const { + return "mix"; +} + +String VisualShaderNodeVectorInterp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = mix( " + p_input_vars[0] + " , " + p_input_vars[1] + " , " + p_input_vars[2] + " );\n"; +} + +VisualShaderNodeVectorInterp::VisualShaderNodeVectorInterp() { + set_input_port_default_value(0, Vector3()); + set_input_port_default_value(1, Vector3()); + set_input_port_default_value(2, Vector3()); +} + +////////////// Vector Construct +String VisualShaderNodeVectorConstruct::get_caption() const { + return "VecConstr"; +} + +int VisualShaderNodeVectorConstruct::get_input_port_count() const { + return 3; +} +VisualShaderNodeVectorConstruct::PortType VisualShaderNodeVectorConstruct::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeVectorConstruct::get_input_port_name(int p_port) const { + if (p_port == 0) { + return "x"; + } else if (p_port == 1) { + return "y"; + } else { + return "z"; + } +} + +int VisualShaderNodeVectorConstruct::get_output_port_count() const { + return 1; +} +VisualShaderNodeVectorConstruct::PortType VisualShaderNodeVectorConstruct::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorConstruct::get_output_port_name(int p_port) const { + return "vec"; +} + +String VisualShaderNodeVectorConstruct::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = vec3( " + p_input_vars[0] + " , " + p_input_vars[1] + " , " + p_input_vars[2] + " );\n"; +} + +VisualShaderNodeVectorConstruct::VisualShaderNodeVectorConstruct() { + + set_input_port_default_value(0, 0.0); + set_input_port_default_value(1, 0.0); + set_input_port_default_value(2, 0.0); +} + +////////////// Transform Construct + +String VisualShaderNodeTransformConstruct::get_caption() const { + return "TransConstr"; +} + +int VisualShaderNodeTransformConstruct::get_input_port_count() const { + return 4; +} +VisualShaderNodeTransformConstruct::PortType VisualShaderNodeTransformConstruct::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeTransformConstruct::get_input_port_name(int p_port) const { + if (p_port == 0) { + return "x"; + } else if (p_port == 1) { + return "y"; + } else if (p_port == 2) { + return "z"; + } else { + return "origin"; + } +} + +int VisualShaderNodeTransformConstruct::get_output_port_count() const { + return 1; +} +VisualShaderNodeTransformConstruct::PortType VisualShaderNodeTransformConstruct::get_output_port_type(int p_port) const { + return PORT_TYPE_TRANSFORM; +} +String VisualShaderNodeTransformConstruct::get_output_port_name(int p_port) const { + return "xform"; +} + +String VisualShaderNodeTransformConstruct::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = mat4( vec4(" + p_input_vars[0] + ", 0.0) , vec4(" + p_input_vars[1] + ", 0.0) , vec4(" + p_input_vars[2] + ",0.0), vec4(" + p_input_vars[3] + ",1.0) );\n"; +} + +VisualShaderNodeTransformConstruct::VisualShaderNodeTransformConstruct() { + + set_input_port_default_value(0, Vector3()); + set_input_port_default_value(1, Vector3()); + set_input_port_default_value(2, Vector3()); + set_input_port_default_value(3, Vector3()); +} + +////////////// Vector Destruct +String VisualShaderNodeVectorDestruct::get_caption() const { + return "VecDestr"; +} + +int VisualShaderNodeVectorDestruct::get_input_port_count() const { + return 1; +} +VisualShaderNodeVectorDestruct::PortType VisualShaderNodeVectorDestruct::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVectorDestruct::get_input_port_name(int p_port) const { + return "vec"; +} + +int VisualShaderNodeVectorDestruct::get_output_port_count() const { + return 3; +} +VisualShaderNodeVectorDestruct::PortType VisualShaderNodeVectorDestruct::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeVectorDestruct::get_output_port_name(int p_port) const { + if (p_port == 0) { + return "x"; + } else if (p_port == 1) { + return "y"; + } else { + return "z"; + } +} + +String VisualShaderNodeVectorDestruct::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + String code; + code += "\t" + p_output_vars[0] + " = " + p_input_vars[0] + ".x;\n"; + code += "\t" + p_output_vars[1] + " = " + p_input_vars[0] + ".y;\n"; + code += "\t" + p_output_vars[2] + " = " + p_input_vars[0] + ".z;\n"; + return code; +} + +VisualShaderNodeVectorDestruct::VisualShaderNodeVectorDestruct() { + set_input_port_default_value(0, Vector3()); +} + +////////////// Transform Destruct + +String VisualShaderNodeTransformDestruct::get_caption() const { + return "TransDestr"; +} + +int VisualShaderNodeTransformDestruct::get_input_port_count() const { + return 1; +} +VisualShaderNodeTransformDestruct::PortType VisualShaderNodeTransformDestruct::get_input_port_type(int p_port) const { + return PORT_TYPE_TRANSFORM; +} +String VisualShaderNodeTransformDestruct::get_input_port_name(int p_port) const { + return "xform"; +} + +int VisualShaderNodeTransformDestruct::get_output_port_count() const { + return 4; +} +VisualShaderNodeTransformDestruct::PortType VisualShaderNodeTransformDestruct::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeTransformDestruct::get_output_port_name(int p_port) const { + if (p_port == 0) { + return "x"; + } else if (p_port == 1) { + return "y"; + } else if (p_port == 2) { + return "z"; + } else { + return "origin"; + } +} + +String VisualShaderNodeTransformDestruct::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + String code; + code += "\t" + p_output_vars[0] + " = " + p_input_vars[0] + "[0].xyz;\n"; + code += "\t" + p_output_vars[1] + " = " + p_input_vars[0] + "[1].xyz;\n"; + code += "\t" + p_output_vars[2] + " = " + p_input_vars[0] + "[2].xyz;\n"; + code += "\t" + p_output_vars[3] + " = " + p_input_vars[0] + "[3].xyz;\n"; + return code; +} + +VisualShaderNodeTransformDestruct::VisualShaderNodeTransformDestruct() { + set_input_port_default_value(0, Transform()); +} + +////////////// Scalar Uniform + +String VisualShaderNodeScalarUniform::get_caption() const { + return "ScalarUniform"; +} + +int VisualShaderNodeScalarUniform::get_input_port_count() const { + return 0; +} +VisualShaderNodeScalarUniform::PortType VisualShaderNodeScalarUniform::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarUniform::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeScalarUniform::get_output_port_count() const { + return 1; +} +VisualShaderNodeScalarUniform::PortType VisualShaderNodeScalarUniform::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR; +} +String VisualShaderNodeScalarUniform::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} + +String VisualShaderNodeScalarUniform::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + return "uniform float " + get_uniform_name() + ";\n"; +} +String VisualShaderNodeScalarUniform::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = " + get_uniform_name() + ";\n"; +} + +VisualShaderNodeScalarUniform::VisualShaderNodeScalarUniform() { +} + +////////////// Color Uniform + +String VisualShaderNodeColorUniform::get_caption() const { + return "ColorUniform"; +} + +int VisualShaderNodeColorUniform::get_input_port_count() const { + return 0; +} +VisualShaderNodeColorUniform::PortType VisualShaderNodeColorUniform::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeColorUniform::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeColorUniform::get_output_port_count() const { + return 2; +} +VisualShaderNodeColorUniform::PortType VisualShaderNodeColorUniform::get_output_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeColorUniform::get_output_port_name(int p_port) const { + return p_port == 0 ? "color" : "alpha"; //no output port means the editor will be used as port +} + +String VisualShaderNodeColorUniform::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + + return "uniform vec4 " + get_uniform_name() + " : hint_color;\n"; +} + +String VisualShaderNodeColorUniform::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + String code = "\t" + p_output_vars[0] + " = " + get_uniform_name() + ".rgb;\n"; + code += "\t" + p_output_vars[1] + " = " + get_uniform_name() + ".a;\n"; + return code; +} + +VisualShaderNodeColorUniform::VisualShaderNodeColorUniform() { +} + +////////////// Vector Uniform + +String VisualShaderNodeVec3Uniform::get_caption() const { + return "VecUniform"; +} + +int VisualShaderNodeVec3Uniform::get_input_port_count() const { + return 0; +} +VisualShaderNodeVec3Uniform::PortType VisualShaderNodeVec3Uniform::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVec3Uniform::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeVec3Uniform::get_output_port_count() const { + return 1; +} +VisualShaderNodeVec3Uniform::PortType VisualShaderNodeVec3Uniform::get_output_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeVec3Uniform::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} +String VisualShaderNodeVec3Uniform::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + return "uniform vec3 " + get_uniform_name() + ";\n"; +} + +String VisualShaderNodeVec3Uniform::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = " + get_uniform_name() + ";\n"; +} + +VisualShaderNodeVec3Uniform::VisualShaderNodeVec3Uniform() { +} + +////////////// Transform Uniform + +String VisualShaderNodeTransformUniform::get_caption() const { + return "TransUniform"; +} + +int VisualShaderNodeTransformUniform::get_input_port_count() const { + return 0; +} +VisualShaderNodeTransformUniform::PortType VisualShaderNodeTransformUniform::get_input_port_type(int p_port) const { + return PORT_TYPE_VECTOR; +} +String VisualShaderNodeTransformUniform::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeTransformUniform::get_output_port_count() const { + return 1; +} +VisualShaderNodeTransformUniform::PortType VisualShaderNodeTransformUniform::get_output_port_type(int p_port) const { + return PORT_TYPE_TRANSFORM; +} +String VisualShaderNodeTransformUniform::get_output_port_name(int p_port) const { + return ""; //no output port means the editor will be used as port +} +String VisualShaderNodeTransformUniform::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + return "uniform mat4 " + get_uniform_name() + ";\n"; +} + +String VisualShaderNodeTransformUniform::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return "\t" + p_output_vars[0] + " = " + get_uniform_name() + ";\n"; +} + +VisualShaderNodeTransformUniform::VisualShaderNodeTransformUniform() { +} + +////////////// Texture Uniform + +String VisualShaderNodeTextureUniform::get_caption() const { + return "TexUniform"; +} + +int VisualShaderNodeTextureUniform::get_input_port_count() const { + return 2; +} +VisualShaderNodeTextureUniform::PortType VisualShaderNodeTextureUniform::get_input_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeTextureUniform::get_input_port_name(int p_port) const { + return p_port == 0 ? "uv" : "lod"; +} + +int VisualShaderNodeTextureUniform::get_output_port_count() const { + return 2; +} +VisualShaderNodeTextureUniform::PortType VisualShaderNodeTextureUniform::get_output_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeTextureUniform::get_output_port_name(int p_port) const { + return p_port == 0 ? "rgb" : "alpha"; +} + +String VisualShaderNodeTextureUniform::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + String code = "uniform sampler2D " + get_uniform_name(); + + switch (texture_type) { + case TYPE_DATA: + if (color_default == COLOR_DEFAULT_BLACK) + code += " : hint_black;\n"; + else + code += ";\n"; + break; + case TYPE_COLOR: + if (color_default == COLOR_DEFAULT_BLACK) + code += " : hint_black_albedo;\n"; + else + code += " : hint_albedo;\n"; + break; + case TYPE_NORMALMAP: code += " : hint_normal;\n"; break; + case TYPE_ANISO: code += " : hint_aniso;\n"; break; + } + + return code; +} + +String VisualShaderNodeTextureUniform::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + + String id = get_uniform_name(); + String code = "\t{\n"; + if (p_input_vars[0] == String()) { //none bound, do nothing + + code += "\t\tvec4 n_tex_read = vec4(0.0);\n"; + } else if (p_input_vars[1] == String()) { + //no lod + code += "\t\tvec4 n_tex_read = texture( " + id + " , " + p_input_vars[0] + ".xy );\n"; + } else { + code += "\t\tvec4 n_tex_read = textureLod( " + id + " , " + p_input_vars[0] + ".xy , " + p_input_vars[1] + " );\n"; + } + + code += "\t\t" + p_output_vars[0] + " = n_tex_read.rgb;\n"; + code += "\t\t" + p_output_vars[1] + " = n_tex_read.a;\n"; + code += "\t}\n"; + return code; +} + +void VisualShaderNodeTextureUniform::set_texture_type(TextureType p_type) { + + texture_type = p_type; + emit_changed(); +} + +VisualShaderNodeTextureUniform::TextureType VisualShaderNodeTextureUniform::get_texture_type() const { + return texture_type; +} + +void VisualShaderNodeTextureUniform::set_color_default(ColorDefault p_default) { + color_default = p_default; + emit_changed(); +} +VisualShaderNodeTextureUniform::ColorDefault VisualShaderNodeTextureUniform::get_color_default() const { + return color_default; +} + +Vector<StringName> VisualShaderNodeTextureUniform::get_editable_properties() const { + Vector<StringName> props; + props.push_back("texture_type"); + props.push_back("color_default"); + return props; +} + +void VisualShaderNodeTextureUniform::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_texture_type", "type"), &VisualShaderNodeTextureUniform::set_texture_type); + ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeTextureUniform::get_texture_type); + + ClassDB::bind_method(D_METHOD("set_color_default", "type"), &VisualShaderNodeTextureUniform::set_color_default); + ClassDB::bind_method(D_METHOD("get_color_default"), &VisualShaderNodeTextureUniform::get_color_default); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normalmap,Aniso"), "set_texture_type", "get_texture_type"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "color_default", PROPERTY_HINT_ENUM, "White Default,Black Default"), "set_color_default", "get_color_default"); + + BIND_ENUM_CONSTANT(TYPE_DATA); + BIND_ENUM_CONSTANT(TYPE_COLOR); + BIND_ENUM_CONSTANT(TYPE_NORMALMAP); + BIND_ENUM_CONSTANT(TYPE_ANISO); + + BIND_ENUM_CONSTANT(COLOR_DEFAULT_WHITE); + BIND_ENUM_CONSTANT(COLOR_DEFAULT_BLACK); +} + +VisualShaderNodeTextureUniform::VisualShaderNodeTextureUniform() { + texture_type = TYPE_DATA; + color_default = COLOR_DEFAULT_WHITE; +} + +////////////// CubeMap Uniform + +String VisualShaderNodeCubeMapUniform::get_caption() const { + return "CubeMap"; +} + +int VisualShaderNodeCubeMapUniform::get_input_port_count() const { + return 2; +} +VisualShaderNodeCubeMapUniform::PortType VisualShaderNodeCubeMapUniform::get_input_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeCubeMapUniform::get_input_port_name(int p_port) const { + return p_port == 0 ? "normal" : "lod"; +} + +int VisualShaderNodeCubeMapUniform::get_output_port_count() const { + return 2; +} +VisualShaderNodeCubeMapUniform::PortType VisualShaderNodeCubeMapUniform::get_output_port_type(int p_port) const { + return p_port == 0 ? PORT_TYPE_VECTOR : PORT_TYPE_SCALAR; +} +String VisualShaderNodeCubeMapUniform::get_output_port_name(int p_port) const { + return p_port == 0 ? "rgb" : "alpha"; +} + +String VisualShaderNodeCubeMapUniform::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const { + return String(); +} + +VisualShaderNodeCubeMapUniform::VisualShaderNodeCubeMapUniform() { +} diff --git a/scene/resources/visual_shader_nodes.h b/scene/resources/visual_shader_nodes.h new file mode 100644 index 0000000000..cf46ee3189 --- /dev/null +++ b/scene/resources/visual_shader_nodes.h @@ -0,0 +1,861 @@ +#ifndef VISUAL_SHADER_NODES_H +#define VISUAL_SHADER_NODES_H + +#include "scene/resources/visual_shader.h" + +/// CONSTANTS /// + +class VisualShaderNodeScalarConstant : public VisualShaderNode { + GDCLASS(VisualShaderNodeScalarConstant, VisualShaderNode) + float constant; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_constant(float p_value); + float get_constant() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeScalarConstant(); +}; + +class VisualShaderNodeColorConstant : public VisualShaderNode { + GDCLASS(VisualShaderNodeColorConstant, VisualShaderNode) + Color constant; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_constant(Color p_value); + Color get_constant() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeColorConstant(); +}; + +class VisualShaderNodeVec3Constant : public VisualShaderNode { + GDCLASS(VisualShaderNodeVec3Constant, VisualShaderNode) + Vector3 constant; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_constant(Vector3 p_value); + Vector3 get_constant() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeVec3Constant(); +}; + +class VisualShaderNodeTransformConstant : public VisualShaderNode { + GDCLASS(VisualShaderNodeTransformConstant, VisualShaderNode) + Transform constant; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_constant(Transform p_value); + Transform get_constant() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeTransformConstant(); +}; + +////////////////////////////////// + +class VisualShaderNodeTexture : public VisualShaderNode { + GDCLASS(VisualShaderNodeTexture, VisualShaderNode) + Ref<Texture> texture; + +public: + enum Source { + SOURCE_TEXTURE, + SOURCE_SCREEN, + SOURCE_2D_TEXTURE, + SOURCE_2D_NORMAL + }; + + enum TextureType { + TYPE_DATA, + TYPE_COLOR, + TYPE_NORMALMAP + }; + +private: + Source source; + TextureType texture_type; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual Vector<VisualShader::DefaultTextureParam> get_default_texture_parameters(VisualShader::Type p_type, int p_id) const; + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_source(Source p_source); + Source get_source() const; + + void set_texture(Ref<Texture> p_value); + Ref<Texture> get_texture() const; + + void set_texture_type(TextureType p_type); + TextureType get_texture_type() const; + + virtual Vector<StringName> get_editable_properties() const; + + virtual String get_warning(Shader::Mode p_mode, VisualShader::Type p_type) const; + + VisualShaderNodeTexture(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeTexture::TextureType) +VARIANT_ENUM_CAST(VisualShaderNodeTexture::Source) + +////////////////////////////////// + +class VisualShaderNodeCubeMap : public VisualShaderNode { + GDCLASS(VisualShaderNodeCubeMap, VisualShaderNode) + Ref<CubeMap> cube_map; + +public: + enum TextureType { + TYPE_DATA, + TYPE_COLOR, + TYPE_NORMALMAP + }; + +private: + TextureType texture_type; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual Vector<VisualShader::DefaultTextureParam> get_default_texture_parameters(VisualShader::Type p_type, int p_id) const; + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_cube_map(Ref<CubeMap> p_value); + Ref<CubeMap> get_cube_map() const; + + void set_texture_type(TextureType p_type); + TextureType get_texture_type() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeCubeMap(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeCubeMap::TextureType) +/////////////////////////////////////// + +class VisualShaderNodeScalarOp : public VisualShaderNode { + GDCLASS(VisualShaderNodeScalarOp, VisualShaderNode) + +public: + enum Operator { + OP_ADD, + OP_SUB, + OP_MUL, + OP_DIV, + OP_MOD, + OP_POW, + OP_MAX, + OP_MIN, + OP_ATAN2 + }; + +protected: + Operator op; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_operator(Operator p_op); + Operator get_operator() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeScalarOp(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeScalarOp::Operator) + +class VisualShaderNodeVectorOp : public VisualShaderNode { + GDCLASS(VisualShaderNodeVectorOp, VisualShaderNode) + +public: + enum Operator { + OP_ADD, + OP_SUB, + OP_MUL, + OP_DIV, + OP_MOD, + OP_POW, + OP_MAX, + OP_MIN, + OP_CROSS + + }; + +protected: + Operator op; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_operator(Operator p_op); + Operator get_operator() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeVectorOp(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeVectorOp::Operator) + +class VisualShaderNodeColorOp : public VisualShaderNode { + GDCLASS(VisualShaderNodeColorOp, VisualShaderNode) + +public: + enum Operator { + OP_SCREEN, + OP_DIFFERENCE, + OP_DARKEN, + OP_LIGHTEN, + OP_OVERLAY, + OP_DODGE, + OP_BURN, + OP_SOFT_LIGHT, + OP_HARD_LIGHT, + }; + +protected: + Operator op; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_operator(Operator p_op); + Operator get_operator() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeColorOp(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeColorOp::Operator) + +class VisualShaderNodeTransformMult : public VisualShaderNode { + GDCLASS(VisualShaderNodeTransformMult, VisualShaderNode) + +public: + enum Operator { + OP_AxB, + OP_BxA, + }; + +protected: + Operator op; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_operator(Operator p_op); + Operator get_operator() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeTransformMult(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeTransformMult::Operator) + +class VisualShaderNodeTransformVecMult : public VisualShaderNode { + GDCLASS(VisualShaderNodeTransformVecMult, VisualShaderNode) + +public: + enum Operator { + OP_AxB, + OP_BxA, + OP_3x3_AxB, + OP_3x3_BxA, + }; + +protected: + Operator op; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_operator(Operator p_op); + Operator get_operator() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeTransformVecMult(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeTransformVecMult::Operator) + +/////////////////////////////////////// + +class VisualShaderNodeScalarFunc : public VisualShaderNode { + GDCLASS(VisualShaderNodeScalarFunc, VisualShaderNode) + +public: + enum Function { + FUNC_SIN, + FUNC_COS, + FUNC_TAN, + FUNC_ASIN, + FUNC_ACOS, + FUNC_ATAN, + FUNC_SINH, + FUNC_COSH, + FUNC_TANH, + FUNC_LOG, + FUNC_EXP, + FUNC_SQRT, + FUNC_ABS, + FUNC_SIGN, + FUNC_FLOOR, + FUNC_ROUND, + FUNC_CEIL, + FUNC_FRAC, + FUNC_SATURATE, + FUNC_NEGATE, + }; + +protected: + Function func; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_function(Function p_func); + Function get_function() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeScalarFunc(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeScalarFunc::Function) + +/////////////////////////////////////// + +class VisualShaderNodeVectorFunc : public VisualShaderNode { + GDCLASS(VisualShaderNodeVectorFunc, VisualShaderNode) + +public: + enum Function { + FUNC_NORMALIZE, + FUNC_SATURATE, + FUNC_NEGATE, + FUNC_RECIPROCAL, + FUNC_RGB2HSV, + FUNC_HSV2RGB, + }; + +protected: + Function func; + + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + void set_function(Function p_func); + Function get_function() const; + + virtual Vector<StringName> get_editable_properties() const; + + VisualShaderNodeVectorFunc(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeVectorFunc::Function) + +/////////////////////////////////////// + +class VisualShaderNodeDotProduct : public VisualShaderNode { + GDCLASS(VisualShaderNodeDotProduct, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeDotProduct(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeVectorLen : public VisualShaderNode { + GDCLASS(VisualShaderNodeVectorLen, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeVectorLen(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeScalarInterp : public VisualShaderNode { + GDCLASS(VisualShaderNodeScalarInterp, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeScalarInterp(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeVectorInterp : public VisualShaderNode { + GDCLASS(VisualShaderNodeVectorInterp, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeVectorInterp(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeVectorConstruct : public VisualShaderNode { + GDCLASS(VisualShaderNodeVectorConstruct, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeVectorConstruct(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeTransformConstruct : public VisualShaderNode { + GDCLASS(VisualShaderNodeTransformConstruct, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeTransformConstruct(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeVectorDestruct : public VisualShaderNode { + GDCLASS(VisualShaderNodeVectorDestruct, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeVectorDestruct(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeTransformDestruct : public VisualShaderNode { + GDCLASS(VisualShaderNodeTransformDestruct, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeTransformDestruct(); +}; + +/////////////////////////////////////// + +class VisualShaderNodeScalarUniform : public VisualShaderNodeUniform { + GDCLASS(VisualShaderNodeScalarUniform, VisualShaderNodeUniform) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeScalarUniform(); +}; + +class VisualShaderNodeColorUniform : public VisualShaderNodeUniform { + GDCLASS(VisualShaderNodeColorUniform, VisualShaderNodeUniform) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeColorUniform(); +}; + +class VisualShaderNodeVec3Uniform : public VisualShaderNodeUniform { + GDCLASS(VisualShaderNodeVec3Uniform, VisualShaderNodeUniform) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeVec3Uniform(); +}; + +class VisualShaderNodeTransformUniform : public VisualShaderNodeUniform { + GDCLASS(VisualShaderNodeTransformUniform, VisualShaderNodeUniform) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeTransformUniform(); +}; + +////////////////////////////////// + +class VisualShaderNodeTextureUniform : public VisualShaderNodeUniform { + GDCLASS(VisualShaderNodeTextureUniform, VisualShaderNodeUniform) +public: + enum TextureType { + TYPE_DATA, + TYPE_COLOR, + TYPE_NORMALMAP, + TYPE_ANISO, + }; + + enum ColorDefault { + COLOR_DEFAULT_WHITE, + COLOR_DEFAULT_BLACK + }; + +private: + TextureType texture_type; + ColorDefault color_default; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + Vector<StringName> get_editable_properties() const; + + void set_texture_type(TextureType p_type); + TextureType get_texture_type() const; + + void set_color_default(ColorDefault p_default); + ColorDefault get_color_default() const; + + VisualShaderNodeTextureUniform(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeTextureUniform::TextureType) +VARIANT_ENUM_CAST(VisualShaderNodeTextureUniform::ColorDefault) + +////////////////////////////////// + +class VisualShaderNodeCubeMapUniform : public VisualShaderNode { + GDCLASS(VisualShaderNodeCubeMapUniform, VisualShaderNode) + +public: + virtual String get_caption() const; + + virtual int get_input_port_count() const; + virtual PortType get_input_port_type(int p_port) const; + virtual String get_input_port_name(int p_port) const; + + virtual int get_output_port_count() const; + virtual PortType get_output_port_type(int p_port) const; + virtual String get_output_port_name(int p_port) const; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars) const; //if no output is connected, the output var passed will be empty. if no input is connected and input is NIL, the input var passed will be empty + + VisualShaderNodeCubeMapUniform(); +}; + +#endif // VISUAL_SHADER_NODES_H diff --git a/servers/physics/physics_server_sw.cpp b/servers/physics/physics_server_sw.cpp index f2dbb635f8..6c25ad43f9 100644 --- a/servers/physics/physics_server_sw.cpp +++ b/servers/physics/physics_server_sw.cpp @@ -65,6 +65,11 @@ RID PhysicsServerSW::shape_create(ShapeType p_shape) { shape = memnew(CapsuleShapeSW); } break; + case SHAPE_CYLINDER: { + + ERR_EXPLAIN("CylinderShape is not supported in GodotPhysics. Please switch to Bullet in the Project Settings."); + ERR_FAIL_V(RID()); + } break; case SHAPE_CONVEX_POLYGON: { shape = memnew(ConvexPolygonShapeSW); diff --git a/servers/physics_server.cpp b/servers/physics_server.cpp index 82c4eb2e13..de173491b2 100644 --- a/servers/physics_server.cpp +++ b/servers/physics_server.cpp @@ -664,6 +664,7 @@ void PhysicsServer::_bind_methods() { BIND_ENUM_CONSTANT(SHAPE_SPHERE); BIND_ENUM_CONSTANT(SHAPE_BOX); BIND_ENUM_CONSTANT(SHAPE_CAPSULE); + BIND_ENUM_CONSTANT(SHAPE_CYLINDER); BIND_ENUM_CONSTANT(SHAPE_CONVEX_POLYGON); BIND_ENUM_CONSTANT(SHAPE_CONCAVE_POLYGON); BIND_ENUM_CONSTANT(SHAPE_HEIGHTMAP); diff --git a/servers/physics_server.h b/servers/physics_server.h index 6712bee8dc..8ecf17c0e6 100644 --- a/servers/physics_server.h +++ b/servers/physics_server.h @@ -228,6 +228,7 @@ public: SHAPE_SPHERE, ///< float:"radius" SHAPE_BOX, ///< vec3:"extents" SHAPE_CAPSULE, ///< dict( float:"radius", float:"height"):capsule + SHAPE_CYLINDER, ///< dict( float:"radius", float:"height"):cylinder SHAPE_CONVEX_POLYGON, ///< array of planes:"planes" SHAPE_CONCAVE_POLYGON, ///< vector3 array:"triangles" , or Dictionary with "indices" (int array) and "triangles" (Vector3 array) SHAPE_HEIGHTMAP, ///< dict( int:"width", int:"depth",float:"cell_size", float_array:"heights" diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp index 2069e64c43..346b04f070 100644 --- a/servers/visual/shader_language.cpp +++ b/servers/visual/shader_language.cpp @@ -3583,7 +3583,7 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, Bui return OK; } -Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_functions, const Set<String> &p_render_modes, const Set<String> &p_shader_types) { +Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_functions, const Vector<StringName> &p_render_modes, const Set<String> &p_shader_types) { Token tk = _get_token(); @@ -3642,7 +3642,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct return ERR_PARSE_ERROR; } - if (!p_render_modes.has(mode)) { + if (p_render_modes.find(mode) == -1) { _set_error("Invalid render mode: '" + String(mode) + "'"); return ERR_PARSE_ERROR; } @@ -4097,7 +4097,7 @@ String ShaderLanguage::get_shader_type(const String &p_code) { return String(); } -Error ShaderLanguage::compile(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Set<String> &p_render_modes, const Set<String> &p_shader_types) { +Error ShaderLanguage::compile(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Vector<StringName> &p_render_modes, const Set<String> &p_shader_types) { clear(); @@ -4114,7 +4114,7 @@ Error ShaderLanguage::compile(const String &p_code, const Map<StringName, Functi return OK; } -Error ShaderLanguage::complete(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Set<String> &p_render_modes, const Set<String> &p_shader_types, List<String> *r_options, String &r_call_hint) { +Error ShaderLanguage::complete(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Vector<StringName> &p_render_modes, const Set<String> &p_shader_types, List<String> *r_options, String &r_call_hint) { clear(); @@ -4134,9 +4134,9 @@ Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Funct return ERR_PARSE_ERROR; } break; case COMPLETION_RENDER_MODE: { - for (const Set<String>::Element *E = p_render_modes.front(); E; E = E->next()) { + for (int i = 0; i < p_render_modes.size(); i++) { - r_options->push_back(E->get()); + r_options->push_back(p_render_modes[i]); } return OK; diff --git a/servers/visual/shader_language.h b/servers/visual/shader_language.h index 720511e18d..9b84c5f195 100644 --- a/servers/visual/shader_language.h +++ b/servers/visual/shader_language.h @@ -650,7 +650,7 @@ private: Error _parse_block(BlockNode *p_block, const Map<StringName, BuiltInInfo> &p_builtin_types, bool p_just_one = false, bool p_can_break = false, bool p_can_continue = false); - Error _parse_shader(const Map<StringName, FunctionInfo> &p_functions, const Set<String> &p_render_modes, const Set<String> &p_shader_types); + Error _parse_shader(const Map<StringName, FunctionInfo> &p_functions, const Vector<StringName> &p_render_modes, const Set<String> &p_shader_types); public: //static void get_keyword_list(ShaderType p_type,List<String> *p_keywords); @@ -658,8 +658,8 @@ public: void clear(); static String get_shader_type(const String &p_code); - Error compile(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Set<String> &p_render_modes, const Set<String> &p_shader_types); - Error complete(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Set<String> &p_render_modes, const Set<String> &p_shader_types, List<String> *r_options, String &r_call_hint); + Error compile(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Vector<StringName> &p_render_modes, const Set<String> &p_shader_types); + Error complete(const String &p_code, const Map<StringName, FunctionInfo> &p_functions, const Vector<StringName> &p_render_modes, const Set<String> &p_shader_types, List<String> *r_options, String &r_call_hint); String get_error_text(); int get_error_line(); diff --git a/servers/visual/shader_types.cpp b/servers/visual/shader_types.cpp index a92e1b06d2..92786ea740 100644 --- a/servers/visual/shader_types.cpp +++ b/servers/visual/shader_types.cpp @@ -35,7 +35,7 @@ const Map<StringName, ShaderLanguage::FunctionInfo> &ShaderTypes::get_functions( return shader_modes[p_mode].functions; } -const Set<String> &ShaderTypes::get_modes(VS::ShaderMode p_mode) { +const Vector<StringName> &ShaderTypes::get_modes(VS::ShaderMode p_mode) { return shader_modes[p_mode].modes; } @@ -140,43 +140,44 @@ ShaderTypes::ShaderTypes() { shader_modes[VS::SHADER_SPATIAL].functions["light"].can_discard = true; - shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_mix"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_add"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_sub"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_mul"); + //order used puts first enum mode (default) first + shader_modes[VS::SHADER_SPATIAL].modes.push_back("blend_mix"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("blend_add"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("blend_sub"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("blend_mul"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_opaque"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_always"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_never"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_alpha_prepass"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("depth_draw_opaque"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("depth_draw_always"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("depth_draw_never"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("depth_draw_alpha_prepass"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_test_disable"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("depth_test_disable"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("cull_front"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("cull_back"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("cull_disabled"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("cull_back"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("cull_front"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("cull_disabled"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("unshaded"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("unshaded"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("diffuse_lambert"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("diffuse_lambert_wrap"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("diffuse_oren_nayar"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("diffuse_burley"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("diffuse_toon"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("diffuse_lambert"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("diffuse_lambert_wrap"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("diffuse_oren_nayar"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("diffuse_burley"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("diffuse_toon"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("specular_schlick_ggx"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("specular_blinn"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("specular_phong"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("specular_toon"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("specular_disabled"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("specular_schlick_ggx"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("specular_blinn"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("specular_phong"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("specular_toon"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("specular_disabled"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("skip_vertex_transform"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("world_vertex_coords"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("ensure_correct_normals"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("skip_vertex_transform"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("world_vertex_coords"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("ensure_correct_normals"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("shadows_disabled"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("shadows_disabled"); - shader_modes[VS::SHADER_SPATIAL].modes.insert("vertex_lighting"); + shader_modes[VS::SHADER_SPATIAL].modes.push_back("vertex_lighting"); /************ CANVAS ITEM **************************/ @@ -227,17 +228,17 @@ ShaderTypes::ShaderTypes() { shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"].built_ins["TIME"] = constt(ShaderLanguage::TYPE_FLOAT); shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"].can_discard = true; - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("skip_vertex_transform"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("skip_vertex_transform"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_mix"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_add"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_sub"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_mul"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_premul_alpha"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_disabled"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("blend_mix"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("blend_add"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("blend_sub"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("blend_mul"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("blend_premul_alpha"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("blend_disabled"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("unshaded"); - shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("light_only"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("unshaded"); + shader_modes[VS::SHADER_CANVAS_ITEM].modes.push_back("light_only"); /************ PARTICLES **************************/ @@ -257,9 +258,9 @@ ShaderTypes::ShaderTypes() { shader_modes[VS::SHADER_PARTICLES].functions["vertex"].built_ins["RANDOM_SEED"] = constt(ShaderLanguage::TYPE_UINT); shader_modes[VS::SHADER_PARTICLES].functions["vertex"].can_discard = false; - shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_force"); - shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_velocity"); - shader_modes[VS::SHADER_PARTICLES].modes.insert("keep_data"); + shader_modes[VS::SHADER_PARTICLES].modes.push_back("disable_force"); + shader_modes[VS::SHADER_PARTICLES].modes.push_back("disable_velocity"); + shader_modes[VS::SHADER_PARTICLES].modes.push_back("keep_data"); shader_types.insert("spatial"); shader_types.insert("canvas_item"); diff --git a/servers/visual/shader_types.h b/servers/visual/shader_types.h index 1f43ff9c92..0680ec8242 100644 --- a/servers/visual/shader_types.h +++ b/servers/visual/shader_types.h @@ -31,14 +31,16 @@ #ifndef SHADERTYPES_H #define SHADERTYPES_H +#include "ordered_hash_map.h" #include "servers/visual_server.h" #include "shader_language.h" + class ShaderTypes { struct Type { Map<StringName, ShaderLanguage::FunctionInfo> functions; - Set<String> modes; + Vector<StringName> modes; }; Map<VS::ShaderMode, Type> shader_modes; @@ -51,7 +53,7 @@ public: static ShaderTypes *get_singleton() { return singleton; } const Map<StringName, ShaderLanguage::FunctionInfo> &get_functions(VS::ShaderMode p_mode); - const Set<String> &get_modes(VS::ShaderMode p_mode); + const Vector<StringName> &get_modes(VS::ShaderMode p_mode); const Set<String> &get_types(); ShaderTypes(); diff --git a/servers/visual/visual_server_viewport.cpp b/servers/visual/visual_server_viewport.cpp index dcc270ca5e..dd6bc3cf26 100644 --- a/servers/visual/visual_server_viewport.cpp +++ b/servers/visual/visual_server_viewport.cpp @@ -268,7 +268,7 @@ void VisualServerViewport::draw_viewports() { ERR_CONTINUE(!vp->render_target.is_valid()); bool visible = vp->viewport_to_screen_rect != Rect2() || vp->update_mode == VS::VIEWPORT_UPDATE_ALWAYS || vp->update_mode == VS::VIEWPORT_UPDATE_ONCE || (vp->update_mode == VS::VIEWPORT_UPDATE_WHEN_VISIBLE && VSG::storage->render_target_was_used(vp->render_target)); - visible = visible && vp->size.x > 0 && vp->size.y > 0; + visible = visible && vp->size.x > 1 && vp->size.y > 1; if (!visible) continue; diff --git a/thirdparty/mbedtls/1453.diff b/thirdparty/mbedtls/1453.diff index acc3654cd4..fef60fc0e6 100644 --- a/thirdparty/mbedtls/1453.diff +++ b/thirdparty/mbedtls/1453.diff @@ -1,7 +1,7 @@ -diff --git a/thirdparty/mbedtls/library/entropy_poll.c b/thirdparty/mbedtls/library/entropy_poll.c -index 67900c46c8..cefe882d2a 100644 ---- a/thirdparty/mbedtls/library/entropy_poll.c -+++ b/thirdparty/mbedtls/library/entropy_poll.c +diff --git a/library/entropy_poll.c b/library/entropy_poll.c +index 67900c46..cefe882d 100644 +--- a/library/entropy_poll.c ++++ b/library/entropy_poll.c @@ -54,28 +54,43 @@ #define _WIN32_WINNT 0x0400 #endif @@ -53,11 +53,11 @@ index 67900c46c8..cefe882d2a 100644 *olen = len; return( 0 ); -diff --git a/thirdparty/mbedtls/library/x509_crt.c b/thirdparty/mbedtls/library/x509_crt.c -index afff4e18bf..7960fa1a1a 100644 ---- a/thirdparty/mbedtls/library/x509_crt.c -+++ b/thirdparty/mbedtls/library/x509_crt.c -@@ -64,6 +64,19 @@ +diff --git a/library/x509_crt.c b/library/x509_crt.c +index 290c1eb3..038eae02 100644 +--- a/library/x509_crt.c ++++ b/library/x509_crt.c +@@ -65,6 +65,19 @@ #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) #include <windows.h> @@ -77,7 +77,7 @@ index afff4e18bf..7960fa1a1a 100644 #else #include <time.h> #endif -@@ -1130,6 +1143,7 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) +@@ -1126,6 +1139,7 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) char filename[MAX_PATH]; char *p; size_t len = strlen( path ); @@ -85,7 +85,7 @@ index afff4e18bf..7960fa1a1a 100644 WIN32_FIND_DATAW file_data; HANDLE hFind; -@@ -1144,7 +1158,18 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) +@@ -1140,7 +1154,18 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) p = filename + len; filename[len++] = '*'; @@ -105,7 +105,7 @@ index afff4e18bf..7960fa1a1a 100644 MAX_PATH - 3 ); if( w_ret == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); -@@ -1161,8 +1186,11 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) +@@ -1157,8 +1182,11 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue; diff --git a/thirdparty/mbedtls/include/mbedtls/aes.h b/thirdparty/mbedtls/include/mbedtls/aes.h index 46016dcb7f..dd5c1183a5 100644 --- a/thirdparty/mbedtls/include/mbedtls/aes.h +++ b/thirdparty/mbedtls/include/mbedtls/aes.h @@ -1,7 +1,9 @@ /** * \file aes.h * - * \brief The Advanced Encryption Standard (AES) specifies a FIPS-approved + * \brief This file contains AES definitions and functions. + * + * The Advanced Encryption Standard (AES) specifies a FIPS-approved * cryptographic algorithm that can be used to protect electronic * data. * @@ -12,6 +14,7 @@ * techniques -- Encryption algorithms -- Part 2: Asymmetric * ciphers</em>. */ + /* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * @@ -50,7 +53,8 @@ #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ -/* Error codes in range 0x0023-0x0025 */ +/* Error codes in range 0x0021-0x0025 */ +#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */ #define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */ #define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */ @@ -59,14 +63,14 @@ #define inline __inline #endif -#if !defined(MBEDTLS_AES_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_AES_ALT) +// Regular implementation +// + /** * \brief The AES context-type definition. */ @@ -85,6 +89,10 @@ typedef struct } mbedtls_aes_context; +#else /* MBEDTLS_AES_ALT */ +#include "aes_alt.h" +#endif /* MBEDTLS_AES_ALT */ + /** * \brief This function initializes the specified AES context. * @@ -112,8 +120,8 @@ void mbedtls_aes_free( mbedtls_aes_context *ctx ); * <li>192 bits</li> * <li>256 bits</li></ul> * - * \return \c 0 on success or #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH - * on failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); @@ -128,7 +136,8 @@ int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, * <li>192 bits</li> * <li>256 bits</li></ul> * - * \return \c 0 on success, or #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); @@ -192,7 +201,8 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, * \param input The buffer holding the input data. * \param output The buffer holding the output data. * - * \return \c 0 on success, or #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH * on failure. */ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, @@ -300,7 +310,49 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, * must use the context initialized with mbedtls_aes_setkey_enc() * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. * - * \warning You must keep the maximum use of your counter in mind. + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an AES block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. * * \param ctx The AES context to use for encryption or decryption. * \param length The length of the input data. @@ -313,7 +365,7 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, * \param input The buffer holding the input data. * \param output The buffer holding the output data. * - * \return \c 0 on success. + * \return \c 0 on success. */ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, size_t length, @@ -391,22 +443,11 @@ MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_AES_ALT */ -#include "aes_alt.h" -#endif /* MBEDTLS_AES_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_aes_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/arc4.h b/thirdparty/mbedtls/include/mbedtls/arc4.h index f9d93f822f..f11fc5be0a 100644 --- a/thirdparty/mbedtls/include/mbedtls/arc4.h +++ b/thirdparty/mbedtls/include/mbedtls/arc4.h @@ -38,14 +38,14 @@ #define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED -0x0019 /**< ARC4 hardware accelerator failed. */ -#if !defined(MBEDTLS_ARC4_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_ARC4_ALT) +// Regular implementation +// + /** * \brief ARC4 context structure * @@ -61,6 +61,10 @@ typedef struct } mbedtls_arc4_context; +#else /* MBEDTLS_ARC4_ALT */ +#include "arc4_alt.h" +#endif /* MBEDTLS_ARC4_ALT */ + /** * \brief Initialize ARC4 context * @@ -118,18 +122,6 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key, int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input, unsigned char *output ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_ARC4_ALT */ -#include "arc4_alt.h" -#endif /* MBEDTLS_ARC4_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * diff --git a/thirdparty/mbedtls/include/mbedtls/aria.h b/thirdparty/mbedtls/include/mbedtls/aria.h new file mode 100644 index 0000000000..bae0621b23 --- /dev/null +++ b/thirdparty/mbedtls/include/mbedtls/aria.h @@ -0,0 +1,331 @@ +/** + * \file aria.h + * + * \brief ARIA block cipher + * + * The ARIA algorithm is a symmetric block cipher that can encrypt and + * decrypt information. It is defined by the Korean Agency for + * Technology and Standards (KATS) in <em>KS X 1213:2004</em> (in + * Korean, but see http://210.104.33.10/ARIA/index-e.html in English) + * and also described by the IETF in <em>RFC 5794</em>. + */ +/* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * 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. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ARIA_H +#define MBEDTLS_ARIA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include <stddef.h> +#include <stdint.h> + +#define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */ +#define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */ + +#define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */ +#define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maxiumum number of rounds in ARIA. */ +#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */ + +#define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH -0x005C /**< Invalid key length. */ +#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */ +#define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */ +#define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */ + +#if !defined(MBEDTLS_ARIA_ALT) +// Regular implementation +// + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief The ARIA context-type definition. + */ +typedef struct +{ + unsigned char nr; /*!< The number of rounds (12, 14 or 16) */ + /*! The ARIA round keys. */ + uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4]; +} +mbedtls_aria_context; + +#else /* MBEDTLS_ARIA_ALT */ +#include "aria_alt.h" +#endif /* MBEDTLS_ARIA_ALT */ + +/** + * \brief This function initializes the specified ARIA context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The ARIA context to initialize. + */ +void mbedtls_aria_init( mbedtls_aria_context *ctx ); + +/** + * \brief This function releases and clears the specified ARIA context. + * + * \param ctx The ARIA context to clear. + */ +void mbedtls_aria_free( mbedtls_aria_context *ctx ); + +/** + * \brief This function sets the encryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * \param key The encryption key. + * \param keybits The size of data passed in bits. Valid options are: + * <ul><li>128 bits</li> + * <li>192 bits</li> + * <li>256 bits</li></ul> + * + * \return \c 0 on success or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH + * on failure. + */ +int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function sets the decryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * \param key The decryption key. + * \param keybits The size of data passed. Valid options are: + * <ul><li>128 bits</li> + * <li>192 bits</li> + * <li>256 bits</li></ul> + * + * \return \c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function performs an ARIA single-block encryption or + * decryption operation. + * + * It performs encryption or decryption (depending on whether + * the key was set for encryption on decryption) on the input + * data buffer defined in the \p input parameter. + * + * mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or + * mbedtls_aria_setkey_dec() must be called before the first + * call to this API with the same context. + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param input The 16-Byte buffer holding the input data. + * \param output The 16-Byte buffer holding the output data. + + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx, + const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief This function performs an ARIA-CBC encryption or decryption operation + * on full blocks. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined in + * the \p input parameter. + * + * It can be called as many times as needed, until all the input + * data is processed. mbedtls_aria_init(), and either + * mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called + * before the first call to this API with the same context. + * + * \note This function operates on aligned blocks, that is, the input size + * must be a multiple of the ARIA block size of 16 Bytes. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the IV, you should + * either save it manually or use the cipher module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param mode The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or + * #MBEDTLS_ARIA_DECRYPT. + * \param length The length of the input data in Bytes. This must be a + * multiple of the block size (16 Bytes). + * \param iv Initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH + * on failure. + */ +int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx, + int mode, + size_t length, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief This function performs an ARIA-CFB128 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt or decrypt), on the input data buffer + * defined in the \p input parameter. + * + * For CFB, you must set up the context with mbedtls_aria_setkey_enc(), + * regardless of whether you are performing an encryption or decryption + * operation, that is, regardless of the \p mode parameter. This is + * because CFB mode uses the same key schedule for encryption and + * decryption. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you must either save it manually or use the cipher + * module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param mode The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or + * #MBEDTLS_ARIA_DECRYPT. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief This function performs an ARIA-CTR encryption or decryption + * operation. + * + * This function performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer + * defined in the \p input parameter. + * + * Due to the nature of CTR, you must use the same key schedule + * for both encryption and decryption operations. Therefore, you + * must use the context initialized with mbedtls_aria_setkey_enc() + * for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an ARIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param length The length of the input data. + * \param nc_off The offset in the current \p stream_block, for + * resuming within the current cipher stream. The + * offset pointer should be 0 at the start of a stream. + * \param nonce_counter The 128-bit nonce and counter. + * \param stream_block The saved stream block for resuming. This is + * overwritten by the function. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine. + * + * \return \c 0 on success, or \c 1 on failure. + */ +int mbedtls_aria_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* aria.h */ diff --git a/thirdparty/mbedtls/include/mbedtls/bignum.h b/thirdparty/mbedtls/include/mbedtls/bignum.h index 3bf02a7ee1..31383b1eb5 100644 --- a/thirdparty/mbedtls/include/mbedtls/bignum.h +++ b/thirdparty/mbedtls/include/mbedtls/bignum.h @@ -204,6 +204,8 @@ void mbedtls_mpi_free( mbedtls_mpi *X ); /** * \brief Enlarge to the specified number of limbs * + * This function does nothing if the MPI is already large enough. + * * \param X MPI to grow * \param nblimbs The target number of limbs * @@ -215,19 +217,23 @@ int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs ); /** * \brief Resize down, keeping at least the specified number of limbs * + * If \c X is smaller than \c nblimbs, it is resized up + * instead. + * * \param X MPI to shrink * \param nblimbs The minimum number of limbs to keep * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * (this can only happen when resizing up). */ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs ); /** * \brief Copy the contents of Y into X * - * \param X Destination MPI - * \param Y Source MPI + * \param X Destination MPI. It is enlarged if necessary. + * \param Y Source MPI. * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed diff --git a/thirdparty/mbedtls/include/mbedtls/blowfish.h b/thirdparty/mbedtls/include/mbedtls/blowfish.h index c0ef5a04cc..985faa43f0 100644 --- a/thirdparty/mbedtls/include/mbedtls/blowfish.h +++ b/thirdparty/mbedtls/include/mbedtls/blowfish.h @@ -44,14 +44,14 @@ #define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED -0x0017 /**< Blowfish hardware accelerator failed. */ #define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH -0x0018 /**< Invalid data input length. */ -#if !defined(MBEDTLS_BLOWFISH_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_BLOWFISH_ALT) +// Regular implementation +// + /** * \brief Blowfish context structure */ @@ -62,6 +62,10 @@ typedef struct } mbedtls_blowfish_context; +#else /* MBEDTLS_BLOWFISH_ALT */ +#include "blowfish_alt.h" +#endif /* MBEDTLS_BLOWFISH_ALT */ + /** * \brief Initialize Blowfish context * @@ -170,7 +174,46 @@ int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx, /** * \brief Blowfish-CTR buffer encryption/decryption * - * Warning: You have to keep the maximum use of your counter in mind! + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**64 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 4 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 4 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**32 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. + * + * Note that for both stategies, sizes are measured in blocks and + * that a Blowfish block is 8 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. * * \param ctx Blowfish context * \param length The length of the data @@ -198,8 +241,4 @@ int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx, } #endif -#else /* MBEDTLS_BLOWFISH_ALT */ -#include "blowfish_alt.h" -#endif /* MBEDTLS_BLOWFISH_ALT */ - #endif /* blowfish.h */ diff --git a/thirdparty/mbedtls/include/mbedtls/bn_mul.h b/thirdparty/mbedtls/include/mbedtls/bn_mul.h index 354c1cc1ab..f4b2b561d1 100644 --- a/thirdparty/mbedtls/include/mbedtls/bn_mul.h +++ b/thirdparty/mbedtls/include/mbedtls/bn_mul.h @@ -521,7 +521,7 @@ "swi r3, %2 \n\t" \ : "=m" (c), "=m" (d), "=m" (s) \ : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "r3", "r4" "r5", "r6", "r7", "r8", \ + : "r3", "r4", "r5", "r6", "r7", "r8", \ "r9", "r10", "r11", "r12", "r13" \ ); diff --git a/thirdparty/mbedtls/include/mbedtls/camellia.h b/thirdparty/mbedtls/include/mbedtls/camellia.h index cf07629d9b..7e4721af78 100644 --- a/thirdparty/mbedtls/include/mbedtls/camellia.h +++ b/thirdparty/mbedtls/include/mbedtls/camellia.h @@ -40,14 +40,14 @@ #define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */ #define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED -0x0027 /**< Camellia hardware accelerator failed. */ -#if !defined(MBEDTLS_CAMELLIA_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_CAMELLIA_ALT) +// Regular implementation +// + /** * \brief CAMELLIA context structure */ @@ -58,6 +58,10 @@ typedef struct } mbedtls_camellia_context; +#else /* MBEDTLS_CAMELLIA_ALT */ +#include "camellia_alt.h" +#endif /* MBEDTLS_CAMELLIA_ALT */ + /** * \brief Initialize CAMELLIA context * @@ -183,12 +187,54 @@ int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx, /** * \brief CAMELLIA-CTR buffer encryption/decryption * - * Warning: You have to keep the maximum use of your counter in mind! - * * Note: Due to the nature of CTR you should use the same key schedule for * both encryption and decryption. So a context initialized with * mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and MBEDTLS_CAMELLIA_DECRYPT. * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that a CAMELLIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * * \param ctx CAMELLIA context * \param length The length of the data * \param nc_off The offset in the current stream_block (for resuming @@ -211,18 +257,6 @@ int mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CTR */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_CAMELLIA_ALT */ -#include "camellia_alt.h" -#endif /* MBEDTLS_CAMELLIA_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * diff --git a/thirdparty/mbedtls/include/mbedtls/ccm.h b/thirdparty/mbedtls/include/mbedtls/ccm.h index 630b7fdf6c..8585ce5e7c 100644 --- a/thirdparty/mbedtls/include/mbedtls/ccm.h +++ b/thirdparty/mbedtls/include/mbedtls/ccm.h @@ -1,8 +1,11 @@ /** * \file ccm.h * - * \brief CCM combines Counter mode encryption with CBC-MAC authentication - * for 128-bit block ciphers. + * \brief This file provides an API for the CCM authenticated encryption + * mode for block ciphers. + * + * CCM combines Counter mode encryption with CBC-MAC authentication + * for 128-bit block ciphers. * * Input to CCM includes the following elements: * <ul><li>Payload - data that is both authenticated and encrypted.</li> @@ -40,14 +43,15 @@ #define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ #define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */ -#if !defined(MBEDTLS_CCM_ALT) -// Regular implementation -// #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_CCM_ALT) +// Regular implementation +// + /** * \brief The CCM context-type definition. The CCM context is passed * to the APIs called. @@ -57,6 +61,10 @@ typedef struct { } mbedtls_ccm_context; +#else /* MBEDTLS_CCM_ALT */ +#include "ccm_alt.h" +#endif /* MBEDTLS_CCM_ALT */ + /** * \brief This function initializes the specified CCM context, * to make references valid, and prepare the context @@ -75,7 +83,8 @@ void mbedtls_ccm_init( mbedtls_ccm_context *ctx ); * \param key The encryption key. * \param keybits The key size in bits. This must be acceptable by the cipher. * - * \return \c 0 on success, or a cipher-specific error code. + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx, mbedtls_cipher_id_t cipher, @@ -93,6 +102,13 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx ); /** * \brief This function encrypts a buffer using CCM. * + * + * \note The tag is written to a separate buffer. To concatenate + * the \p tag with the \p output, as done in <em>RFC-3610: + * Counter with CBC-MAC (CCM)</em>, use + * \p tag = \p output + \p length, and make sure that the + * output buffer is at least \p length + \p tag_len wide. + * * \param ctx The CCM context to use for encryption. * \param length The length of the input data in Bytes. * \param iv Initialization vector (nonce). @@ -107,13 +123,8 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx ); * \param tag_len The length of the tag to generate in Bytes: * 4, 6, 8, 10, 12, 14 or 16. * - * \note The tag is written to a separate buffer. To concatenate - * the \p tag with the \p output, as done in <em>RFC-3610: - * Counter with CBC-MAC (CCM)</em>, use - * \p tag = \p output + \p length, and make sure that the - * output buffer is at least \p length + \p tag_len wide. - * * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, @@ -139,8 +150,9 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, * \param tag_len The length of the tag in Bytes. * 4, 6, 8, 10, 12, 14 or 16. * - * \return 0 if successful and authenticated, or - * #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return \c 0 on success. This indicates that the message is authentic. + * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return A cipher-specific error code on calculation failure. */ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, @@ -148,23 +160,13 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *input, unsigned char *output, const unsigned char *tag, size_t tag_len ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_CCM_ALT */ -#include "ccm_alt.h" -#endif /* MBEDTLS_CCM_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) /** * \brief The CCM checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_ccm_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ diff --git a/thirdparty/mbedtls/include/mbedtls/cipher.h b/thirdparty/mbedtls/include/mbedtls/cipher.h index d1f4efef8e..46b3bdfefa 100644 --- a/thirdparty/mbedtls/include/mbedtls/cipher.h +++ b/thirdparty/mbedtls/include/mbedtls/cipher.h @@ -1,7 +1,9 @@ /** * \file cipher.h * - * \brief The generic cipher wrapper. + * \brief This file contains an abstraction interface for use with the cipher + * primitives provided by the library. It provides a common interface to all of + * the available cipher operations. * * \author Adriaan de Jong <dejong@fox-it.com> */ @@ -69,93 +71,112 @@ extern "C" { #endif /** - * \brief An enumeration of supported ciphers. + * \brief Supported cipher types. * - * \warning ARC4 and DES are considered weak ciphers and their use - * constitutes a security risk. We recommend considering stronger + * \warning RC4 and DES are considered weak ciphers and their use + * constitutes a security risk. Arm recommends considering stronger * ciphers instead. */ typedef enum { - MBEDTLS_CIPHER_ID_NONE = 0, - MBEDTLS_CIPHER_ID_NULL, - MBEDTLS_CIPHER_ID_AES, - MBEDTLS_CIPHER_ID_DES, - MBEDTLS_CIPHER_ID_3DES, - MBEDTLS_CIPHER_ID_CAMELLIA, - MBEDTLS_CIPHER_ID_BLOWFISH, - MBEDTLS_CIPHER_ID_ARC4, + MBEDTLS_CIPHER_ID_NONE = 0, /**< Placeholder to mark the end of cipher ID lists. */ + MBEDTLS_CIPHER_ID_NULL, /**< The identity cipher, treated as a stream cipher. */ + MBEDTLS_CIPHER_ID_AES, /**< The AES cipher. */ + MBEDTLS_CIPHER_ID_DES, /**< The DES cipher. */ + MBEDTLS_CIPHER_ID_3DES, /**< The Triple DES cipher. */ + MBEDTLS_CIPHER_ID_CAMELLIA, /**< The Camellia cipher. */ + MBEDTLS_CIPHER_ID_BLOWFISH, /**< The Blowfish cipher. */ + MBEDTLS_CIPHER_ID_ARC4, /**< The RC4 cipher. */ + MBEDTLS_CIPHER_ID_ARIA, /**< The Aria cipher. */ } mbedtls_cipher_id_t; /** - * \brief An enumeration of supported (cipher, mode) pairs. + * \brief Supported {cipher type, cipher mode} pairs. * - * \warning ARC4 and DES are considered weak ciphers and their use - * constitutes a security risk. We recommend considering stronger + * \warning RC4 and DES are considered weak ciphers and their use + * constitutes a security risk. Arm recommends considering stronger * ciphers instead. */ typedef enum { - MBEDTLS_CIPHER_NONE = 0, - MBEDTLS_CIPHER_NULL, - MBEDTLS_CIPHER_AES_128_ECB, - MBEDTLS_CIPHER_AES_192_ECB, - MBEDTLS_CIPHER_AES_256_ECB, - MBEDTLS_CIPHER_AES_128_CBC, - MBEDTLS_CIPHER_AES_192_CBC, - MBEDTLS_CIPHER_AES_256_CBC, - MBEDTLS_CIPHER_AES_128_CFB128, - MBEDTLS_CIPHER_AES_192_CFB128, - MBEDTLS_CIPHER_AES_256_CFB128, - MBEDTLS_CIPHER_AES_128_CTR, - MBEDTLS_CIPHER_AES_192_CTR, - MBEDTLS_CIPHER_AES_256_CTR, - MBEDTLS_CIPHER_AES_128_GCM, - MBEDTLS_CIPHER_AES_192_GCM, - MBEDTLS_CIPHER_AES_256_GCM, - MBEDTLS_CIPHER_CAMELLIA_128_ECB, - MBEDTLS_CIPHER_CAMELLIA_192_ECB, - MBEDTLS_CIPHER_CAMELLIA_256_ECB, - MBEDTLS_CIPHER_CAMELLIA_128_CBC, - MBEDTLS_CIPHER_CAMELLIA_192_CBC, - MBEDTLS_CIPHER_CAMELLIA_256_CBC, - MBEDTLS_CIPHER_CAMELLIA_128_CFB128, - MBEDTLS_CIPHER_CAMELLIA_192_CFB128, - MBEDTLS_CIPHER_CAMELLIA_256_CFB128, - MBEDTLS_CIPHER_CAMELLIA_128_CTR, - MBEDTLS_CIPHER_CAMELLIA_192_CTR, - MBEDTLS_CIPHER_CAMELLIA_256_CTR, - MBEDTLS_CIPHER_CAMELLIA_128_GCM, - MBEDTLS_CIPHER_CAMELLIA_192_GCM, - MBEDTLS_CIPHER_CAMELLIA_256_GCM, - MBEDTLS_CIPHER_DES_ECB, - MBEDTLS_CIPHER_DES_CBC, - MBEDTLS_CIPHER_DES_EDE_ECB, - MBEDTLS_CIPHER_DES_EDE_CBC, - MBEDTLS_CIPHER_DES_EDE3_ECB, - MBEDTLS_CIPHER_DES_EDE3_CBC, - MBEDTLS_CIPHER_BLOWFISH_ECB, - MBEDTLS_CIPHER_BLOWFISH_CBC, - MBEDTLS_CIPHER_BLOWFISH_CFB64, - MBEDTLS_CIPHER_BLOWFISH_CTR, - MBEDTLS_CIPHER_ARC4_128, - MBEDTLS_CIPHER_AES_128_CCM, - MBEDTLS_CIPHER_AES_192_CCM, - MBEDTLS_CIPHER_AES_256_CCM, - MBEDTLS_CIPHER_CAMELLIA_128_CCM, - MBEDTLS_CIPHER_CAMELLIA_192_CCM, - MBEDTLS_CIPHER_CAMELLIA_256_CCM, + MBEDTLS_CIPHER_NONE = 0, /**< Placeholder to mark the end of cipher-pair lists. */ + MBEDTLS_CIPHER_NULL, /**< The identity stream cipher. */ + MBEDTLS_CIPHER_AES_128_ECB, /**< AES cipher with 128-bit ECB mode. */ + MBEDTLS_CIPHER_AES_192_ECB, /**< AES cipher with 192-bit ECB mode. */ + MBEDTLS_CIPHER_AES_256_ECB, /**< AES cipher with 256-bit ECB mode. */ + MBEDTLS_CIPHER_AES_128_CBC, /**< AES cipher with 128-bit CBC mode. */ + MBEDTLS_CIPHER_AES_192_CBC, /**< AES cipher with 192-bit CBC mode. */ + MBEDTLS_CIPHER_AES_256_CBC, /**< AES cipher with 256-bit CBC mode. */ + MBEDTLS_CIPHER_AES_128_CFB128, /**< AES cipher with 128-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_192_CFB128, /**< AES cipher with 192-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_256_CFB128, /**< AES cipher with 256-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_128_CTR, /**< AES cipher with 128-bit CTR mode. */ + MBEDTLS_CIPHER_AES_192_CTR, /**< AES cipher with 192-bit CTR mode. */ + MBEDTLS_CIPHER_AES_256_CTR, /**< AES cipher with 256-bit CTR mode. */ + MBEDTLS_CIPHER_AES_128_GCM, /**< AES cipher with 128-bit GCM mode. */ + MBEDTLS_CIPHER_AES_192_GCM, /**< AES cipher with 192-bit GCM mode. */ + MBEDTLS_CIPHER_AES_256_GCM, /**< AES cipher with 256-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_ECB, /**< Camellia cipher with 128-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_ECB, /**< Camellia cipher with 192-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_ECB, /**< Camellia cipher with 256-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CBC, /**< Camellia cipher with 128-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CBC, /**< Camellia cipher with 192-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CBC, /**< Camellia cipher with 256-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CFB128, /**< Camellia cipher with 128-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CFB128, /**< Camellia cipher with 192-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CFB128, /**< Camellia cipher with 256-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CTR, /**< Camellia cipher with 128-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CTR, /**< Camellia cipher with 192-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CTR, /**< Camellia cipher with 256-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_GCM, /**< Camellia cipher with 128-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_GCM, /**< Camellia cipher with 192-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_GCM, /**< Camellia cipher with 256-bit GCM mode. */ + MBEDTLS_CIPHER_DES_ECB, /**< DES cipher with ECB mode. */ + MBEDTLS_CIPHER_DES_CBC, /**< DES cipher with CBC mode. */ + MBEDTLS_CIPHER_DES_EDE_ECB, /**< DES cipher with EDE ECB mode. */ + MBEDTLS_CIPHER_DES_EDE_CBC, /**< DES cipher with EDE CBC mode. */ + MBEDTLS_CIPHER_DES_EDE3_ECB, /**< DES cipher with EDE3 ECB mode. */ + MBEDTLS_CIPHER_DES_EDE3_CBC, /**< DES cipher with EDE3 CBC mode. */ + MBEDTLS_CIPHER_BLOWFISH_ECB, /**< Blowfish cipher with ECB mode. */ + MBEDTLS_CIPHER_BLOWFISH_CBC, /**< Blowfish cipher with CBC mode. */ + MBEDTLS_CIPHER_BLOWFISH_CFB64, /**< Blowfish cipher with CFB64 mode. */ + MBEDTLS_CIPHER_BLOWFISH_CTR, /**< Blowfish cipher with CTR mode. */ + MBEDTLS_CIPHER_ARC4_128, /**< RC4 cipher with 128-bit mode. */ + MBEDTLS_CIPHER_AES_128_CCM, /**< AES cipher with 128-bit CCM mode. */ + MBEDTLS_CIPHER_AES_192_CCM, /**< AES cipher with 192-bit CCM mode. */ + MBEDTLS_CIPHER_AES_256_CCM, /**< AES cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CCM, /**< Camellia cipher with 128-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CCM, /**< Camellia cipher with 192-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CCM, /**< Camellia cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_ARIA_128_ECB, /**< Aria cipher with 128-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_192_ECB, /**< Aria cipher with 192-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_256_ECB, /**< Aria cipher with 256-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_128_CBC, /**< Aria cipher with 128-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_192_CBC, /**< Aria cipher with 192-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_256_CBC, /**< Aria cipher with 256-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_128_CFB128, /**< Aria cipher with 128-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_192_CFB128, /**< Aria cipher with 192-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_256_CFB128, /**< Aria cipher with 256-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_128_CTR, /**< Aria cipher with 128-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_192_CTR, /**< Aria cipher with 192-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_256_CTR, /**< Aria cipher with 256-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_128_GCM, /**< Aria cipher with 128-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_192_GCM, /**< Aria cipher with 192-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_256_GCM, /**< Aria cipher with 256-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_128_CCM, /**< Aria cipher with 128-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_192_CCM, /**< Aria cipher with 192-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_256_CCM, /**< Aria cipher with 256-bit key and CCM mode. */ } mbedtls_cipher_type_t; /** Supported cipher modes. */ typedef enum { - MBEDTLS_MODE_NONE = 0, - MBEDTLS_MODE_ECB, - MBEDTLS_MODE_CBC, - MBEDTLS_MODE_CFB, - MBEDTLS_MODE_OFB, /* Unused! */ - MBEDTLS_MODE_CTR, - MBEDTLS_MODE_GCM, - MBEDTLS_MODE_STREAM, - MBEDTLS_MODE_CCM, + MBEDTLS_MODE_NONE = 0, /**< None. */ + MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */ + MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */ + MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */ + MBEDTLS_MODE_OFB, /**< The OFB cipher mode - unsupported. */ + MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */ + MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */ + MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */ + MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */ } mbedtls_cipher_mode_t; /** Supported cipher padding types. */ @@ -163,8 +184,8 @@ typedef enum { MBEDTLS_PADDING_PKCS7 = 0, /**< PKCS7 padding (default). */ MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding. */ MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding. */ - MBEDTLS_PADDING_ZEROS, /**< zero padding (not reversible). */ - MBEDTLS_PADDING_NONE, /**< never pad (full blocks only). */ + MBEDTLS_PADDING_ZEROS, /**< Zero padding (not reversible). */ + MBEDTLS_PADDING_NONE, /**< Never pad (full blocks only). */ } mbedtls_cipher_padding_t; /** Type of operation. */ @@ -228,7 +249,10 @@ typedef struct { */ unsigned int iv_size; - /** Flags to set. For example, if the cipher supports variable IV sizes or variable key sizes. */ + /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and + * MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the + * cipher supports variable IV or variable key sizes, respectively. + */ int flags; /** The block size, in Bytes. */ @@ -299,7 +323,8 @@ const int *mbedtls_cipher_list( void ); * \param cipher_name Name of the cipher to search for. * * \return The cipher information structure associated with the - * given \p cipher_name, or NULL if not found. + * given \p cipher_name. + * \return NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ); @@ -310,7 +335,8 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher * \param cipher_type Type of the cipher to search for. * * \return The cipher information structure associated with the - * given \p cipher_type, or NULL if not found. + * given \p cipher_type. + * \return NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ); @@ -325,7 +351,8 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher * \param mode The cipher mode. For example, #MBEDTLS_MODE_CBC. * * \return The cipher information structure associated with the - * given \p cipher_id, or NULL if not found. + * given \p cipher_id. + * \return NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, int key_bitlen, @@ -352,10 +379,11 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ); * \param ctx The context to initialize. May not be NULL. * \param cipher_info The cipher to use. * - * \return \c 0 on success, - * #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on parameter failure, - * #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the - * cipher-specific context failed. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the + * cipher-specific context fails. * * \internal Currently, the function also clears the structure. * In future versions, the caller will be required to call @@ -368,8 +396,8 @@ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_in * * \param ctx The context of the cipher. Must be initialized. * - * \return The size of the blocks of the cipher, or zero if \p ctx - * has not been initialized. + * \return The size of the blocks of the cipher. + * \return 0 if \p ctx has not been initialized. */ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx ) { @@ -385,8 +413,8 @@ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_c * * \param ctx The context of the cipher. Must be initialized. * - * \return The mode of operation, or #MBEDTLS_MODE_NONE if - * \p ctx has not been initialized. + * \return The mode of operation. + * \return #MBEDTLS_MODE_NONE if \p ctx has not been initialized. */ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx ) { @@ -402,9 +430,9 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtl * * \param ctx The context of the cipher. Must be initialized. * - * \return <ul><li>If no IV has been set: the recommended IV size. - * 0 for ciphers not using IV or nonce.</li> - * <li>If IV has already been set: the actual size.</li></ul> + * \return The recommended IV size if no IV has been set. + * \return \c 0 for ciphers not using an IV or a nonce. + * \return The actual size if an IV has been set. */ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx ) { @@ -422,8 +450,8 @@ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ct * * \param ctx The context of the cipher. Must be initialized. * - * \return The type of the cipher, or #MBEDTLS_CIPHER_NONE if - * \p ctx has not been initialized. + * \return The type of the cipher. + * \return #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized. */ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx ) { @@ -439,8 +467,8 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_ciphe * * \param ctx The context of the cipher. Must be initialized. * - * \return The name of the cipher, or NULL if \p ctx has not - * been not initialized. + * \return The name of the cipher. + * \return NULL if \p ctx has not been not initialized. */ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx ) { @@ -455,8 +483,8 @@ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_ * * \param ctx The context of the cipher. Must be initialized. * - * \return The key length of the cipher in bits, or - * #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been + * \return The key length of the cipher in bits. + * \return #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been * initialized. */ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx ) @@ -472,9 +500,8 @@ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t * * \param ctx The context of the cipher. Must be initialized. * - * \return The type of operation: #MBEDTLS_ENCRYPT or - * #MBEDTLS_DECRYPT, or #MBEDTLS_OPERATION_NONE if \p ctx - * has not been initialized. + * \return The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. + * \return #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized. */ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx ) { @@ -495,9 +522,10 @@ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_ci * \param operation The operation that the key will be used for: * #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. * - * \returns \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if - * parameter verification fails, or a cipher-specific - * error code. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, int key_bitlen, const mbedtls_operation_t operation ); @@ -512,9 +540,10 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *k * \param ctx The generic cipher context. * \param mode The padding mode. * - * \returns \c 0 on success, #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE - * if the selected padding mode is not supported, or - * #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE + * if the selected padding mode is not supported. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode * does not support padding. */ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ); @@ -524,15 +553,17 @@ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_ciph * \brief This function sets the initialization vector (IV) * or nonce. * + * \note Some ciphers do not use IVs nor nonce. For these + * ciphers, this function has no effect. + * * \param ctx The generic cipher context. * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. * \param iv_len The IV length for ciphers with variable-size IV. * This parameter is discarded by ciphers with fixed-size IV. * - * \returns \c 0 on success, or #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA - * - * \note Some ciphers do not use IVs nor nonce. For these - * ciphers, this function has no effect. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. */ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len ); @@ -542,8 +573,9 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, * * \param ctx The generic cipher context. * - * \returns \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA - * if parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. */ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); @@ -557,7 +589,8 @@ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); * \param ad The additional data to use. * \param ad_len the Length of \p ad. * - * \return \c 0 on success, or a specific error code on failure. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, const unsigned char *ad, size_t ad_len ); @@ -573,6 +606,11 @@ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, * Exception: For MBEDTLS_MODE_ECB, expects a single block * in size. For example, 16 Bytes for AES. * + * \note If the underlying cipher is used in GCM mode, all calls + * to this function, except for the last one before + * mbedtls_cipher_finish(), must have \p ilen as a + * multiple of the block size of the cipher. + * * \param ctx The generic cipher context. * \param input The buffer holding the input data. * \param ilen The length of the input data. @@ -582,16 +620,12 @@ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, * \param olen The length of the output data, to be updated with the * actual number of Bytes written. * - * \returns \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if - * parameter verification fails, - * #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an - * unsupported mode for a cipher, or a cipher-specific - * error code. - * - * \note If the underlying cipher is GCM, all calls to this - * function, except the last one before - * mbedtls_cipher_finish(). Must have \p ilen as a - * multiple of the block_size. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an + * unsupported mode for a cipher. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen ); @@ -606,13 +640,14 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i * \param output The buffer to write data to. Needs block_size available. * \param olen The length of the data written to the \p output buffer. * - * \returns \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if - * parameter verification fails, - * #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption - * expected a full block but was not provided one, - * #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding - * while decrypting, or a cipher-specific error code - * on failure for any other reason. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption + * expecting a full block but not receiving one. + * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding + * while decrypting. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen ); @@ -627,7 +662,8 @@ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, * \param tag The buffer to write the tag to. * \param tag_len The length of the tag to write. * - * \return \c 0 on success, or a specific error code on failure. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len ); @@ -641,7 +677,8 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, * \param tag The buffer holding the tag. * \param tag_len The length of the tag to check. * - * \return \c 0 on success, or a specific error code on failure. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, const unsigned char *tag, size_t tag_len ); @@ -667,13 +704,14 @@ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, * \note Some ciphers do not use IVs nor nonce. For these * ciphers, use \p iv = NULL and \p iv_len = 0. * - * \returns \c 0 on success, or - * #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or - * #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption - * expected a full block but was not provided one, or - * #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding - * while decrypting, or a cipher-specific error code on - * failure for any other reason. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption + * expecting a full block but not receiving one. + * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding + * while decrypting. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, @@ -699,9 +737,10 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, * \param tag The buffer for the authentication tag. * \param tag_len The desired length of the authentication tag. * - * \returns \c 0 on success, or - * #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or - * a cipher-specific error code. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, @@ -713,6 +752,10 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, /** * \brief The generic autenticated decryption (AEAD) function. * + * \note If the data is not authentic, then the output buffer + * is zeroed out to prevent the unauthentic plaintext being + * used, making this interface safer. + * * \param ctx The generic cipher context. * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. * \param iv_len The IV length for ciphers with variable-size IV. @@ -728,14 +771,11 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, * \param tag The buffer holding the authentication tag. * \param tag_len The length of the authentication tag. * - * \returns \c 0 on success, or - * #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or - * #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic, - * or a cipher-specific error code on failure for any other reason. - * - * \note If the data is not authentic, then the output buffer - * is zeroed out to prevent the unauthentic plaintext being - * used, making this interface safer. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, diff --git a/thirdparty/mbedtls/include/mbedtls/cmac.h b/thirdparty/mbedtls/include/mbedtls/cmac.h index 628c9daba2..913c05f8a7 100644 --- a/thirdparty/mbedtls/include/mbedtls/cmac.h +++ b/thirdparty/mbedtls/include/mbedtls/cmac.h @@ -1,8 +1,10 @@ /** * \file cmac.h * - * \brief The Cipher-based Message Authentication Code (CMAC) Mode for - * Authentication. + * \brief This file contains CMAC definitions and functions. + * + * The Cipher-based Message Authentication Code (CMAC) Mode for + * Authentication is defined in <em>RFC-4493: The AES-CMAC Algorithm</em>. */ /* * Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -38,9 +40,9 @@ extern "C" { #define MBEDTLS_DES3_BLOCK_SIZE 8 #if defined(MBEDTLS_AES_C) -#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /* The longest block used by CMAC is that of AES. */ +#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /**< The longest block used by CMAC is that of AES. */ #else -#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /* The longest block used by CMAC is that of 3DES. */ +#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /**< The longest block used by CMAC is that of 3DES. */ #endif #if !defined(MBEDTLS_CMAC_ALT) @@ -61,22 +63,25 @@ struct mbedtls_cmac_context_t size_t unprocessed_len; }; +#else /* !MBEDTLS_CMAC_ALT */ +#include "cmac_alt.h" +#endif /* !MBEDTLS_CMAC_ALT */ + /** * \brief This function sets the CMAC key, and prepares to authenticate * the input data. * Must be called with an initialized cipher context. * * \param ctx The cipher context used for the CMAC operation, initialized - * as one of the following types:<ul> - * <li>MBEDTLS_CIPHER_AES_128_ECB</li> - * <li>MBEDTLS_CIPHER_AES_192_ECB</li> - * <li>MBEDTLS_CIPHER_AES_256_ECB</li> - * <li>MBEDTLS_CIPHER_DES_EDE3_ECB</li></ul> + * as one of the following types: MBEDTLS_CIPHER_AES_128_ECB, + * MBEDTLS_CIPHER_AES_192_ECB, MBEDTLS_CIPHER_AES_256_ECB, + * or MBEDTLS_CIPHER_DES_EDE3_ECB. * \param key The CMAC key. * \param keybits The length of the CMAC key in bits. * Must be supported by the cipher. * - * \return \c 0 on success, or a cipher-specific error code. + * \return \c 0 on success. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx, const unsigned char *key, size_t keybits ); @@ -93,8 +98,9 @@ int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx, * \param input The buffer holding the input data. * \param ilen The length of the input data. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA - * if parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. */ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, size_t ilen ); @@ -110,7 +116,8 @@ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx, * \param ctx The cipher context used for the CMAC operation. * \param output The output buffer for the CMAC checksum result. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA * if parameter verification fails. */ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, @@ -126,7 +133,8 @@ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, * * \param ctx The cipher context used for the CMAC operation. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA * if parameter verification fails. */ int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx ); @@ -149,7 +157,8 @@ int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx ); * \param ilen The length of the input data. * \param output The buffer for the generic CMAC result. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA * if parameter verification fails. */ int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info, @@ -180,23 +189,12 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len, unsigned char output[16] ); #endif /* MBEDTLS_AES_C */ -#ifdef __cplusplus -} -#endif - -#else /* !MBEDTLS_CMAC_ALT */ -#include "cmac_alt.h" -#endif /* !MBEDTLS_CMAC_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - #if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) ) /** * \brief The CMAC checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_cmac_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ diff --git a/thirdparty/mbedtls/include/mbedtls/config.h b/thirdparty/mbedtls/include/mbedtls/config.h index b5905ef9d0..ae10a4d728 100644 --- a/thirdparty/mbedtls/include/mbedtls/config.h +++ b/thirdparty/mbedtls/include/mbedtls/config.h @@ -48,10 +48,14 @@ * Requires support for asm() in compiler. * * Used in: + * library/aria.c * library/timing.c - * library/padlock.c * include/mbedtls/bn_mul.h * + * Required by: + * MBEDTLS_AESNI_C + * MBEDTLS_PADLOCK_C + * * Comment to disable the use of assembly code. */ #define MBEDTLS_HAVE_ASM @@ -271,6 +275,7 @@ */ //#define MBEDTLS_AES_ALT //#define MBEDTLS_ARC4_ALT +//#define MBEDTLS_ARIA_ALT //#define MBEDTLS_BLOWFISH_ALT //#define MBEDTLS_CAMELLIA_ALT //#define MBEDTLS_CCM_ALT @@ -288,6 +293,7 @@ //#define MBEDTLS_SHA256_ALT //#define MBEDTLS_SHA512_ALT //#define MBEDTLS_XTEA_ALT + /* * When replacing the elliptic curve module, pleace consider, that it is * implemented with two .c files: @@ -440,13 +446,46 @@ /** * \def MBEDTLS_AES_ROM_TABLES * - * Store the AES tables in ROM. + * Use precomputed AES tables stored in ROM. + * + * Uncomment this macro to use precomputed AES tables stored in ROM. + * Comment this macro to generate AES tables in RAM at runtime. + * + * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb + * (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the + * initialization time before the first AES operation can be performed. + * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c + * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded + * performance if ROM access is slower than RAM access. + * + * This option is independent of \c MBEDTLS_AES_FEWER_TABLES. * - * Uncomment this macro to store the AES tables in ROM. */ //#define MBEDTLS_AES_ROM_TABLES /** + * \def MBEDTLS_AES_FEWER_TABLES + * + * Use less ROM/RAM for AES tables. + * + * Uncommenting this macro omits 75% of the AES tables from + * ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES) + * by computing their values on the fly during operations + * (the tables are entry-wise rotations of one another). + * + * Tradeoff: Uncommenting this reduces the RAM / ROM footprint + * by ~6kb but at the cost of more arithmetic operations during + * runtime. Specifically, one has to compare 4 accesses within + * different tables to 4 accesses with additional arithmetic + * operations within the same table. The performance gain/loss + * depends on the system and memory details. + * + * This option is independent of \c MBEDTLS_AES_ROM_TABLES. + * + */ +//#define MBEDTLS_AES_FEWER_TABLES + +/** * \def MBEDTLS_CAMELLIA_SMALL_MEMORY * * Use less ROM for the Camellia implementation (saves about 768 bytes). @@ -576,6 +615,7 @@ #define MBEDTLS_ECP_DP_BP384R1_ENABLED #define MBEDTLS_ECP_DP_BP512R1_ENABLED #define MBEDTLS_ECP_DP_CURVE25519_ENABLED +#define MBEDTLS_ECP_DP_CURVE448_ENABLED /** * \def MBEDTLS_ECP_NIST_OPTIM @@ -1583,7 +1623,7 @@ * Enable the AES block cipher. * * Module: library/aes.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * library/pem.c * library/ctr_drbg.c * @@ -1658,7 +1698,7 @@ * Enable the ARCFOUR stream cipher. * * Module: library/arc4.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1752,7 +1792,7 @@ * Enable the Camellia block cipher. * * Module: library/camellia.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1802,6 +1842,58 @@ #define MBEDTLS_CAMELLIA_C /** + * \def MBEDTLS_ARIA_C + * + * Enable the ARIA block cipher. + * + * Module: library/aria.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * + * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 + */ +//#define MBEDTLS_ARIA_C + +/** * \def MBEDTLS_CCM_C * * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher. @@ -1887,7 +1979,7 @@ * * Module: library/des.c * Caller: library/pem.c - * library/ssl_tls.c + * library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -2818,6 +2910,26 @@ */ #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE +/** + * Uncomment the macro to let mbed TLS use your alternate implementation of + * mbedtls_platform_zeroize(). This replaces the default implementation in + * platform_util.c. + * + * mbedtls_platform_zeroize() is a widely used function across the library to + * zero a block of memory. The implementation is expected to be secure in the + * sense that it has been written to prevent the compiler from removing calls + * to mbedtls_platform_zeroize() as part of redundant code elimination + * optimizations. However, it is difficult to guarantee that calls to + * mbedtls_platform_zeroize() will not be optimized by the compiler as older + * versions of the C language standards do not provide a secure implementation + * of memset(). Therefore, MBEDTLS_PLATFORM_ZEROIZE_ALT enables users to + * configure their own implementation of mbedtls_platform_zeroize(), for + * example by using directives specific to their compiler, features from newer + * C standards (e.g using memset_s() in C11) or calling a secure memset() from + * their system (e.g explicit_bzero() in BSD). + */ +//#define MBEDTLS_PLATFORM_ZEROIZE_ALT + /* \} name SECTION: Customisation configuration options */ /* Target and application specific configurations */ diff --git a/thirdparty/mbedtls/include/mbedtls/ctr_drbg.h b/thirdparty/mbedtls/include/mbedtls/ctr_drbg.h index 121575a51b..dcbc047924 100644 --- a/thirdparty/mbedtls/include/mbedtls/ctr_drbg.h +++ b/thirdparty/mbedtls/include/mbedtls/ctr_drbg.h @@ -1,10 +1,15 @@ /** * \file ctr_drbg.h * - * \brief CTR_DRBG is based on AES-256, as defined in <em>NIST SP 800-90A: - * Recommendation for Random Number Generation Using Deterministic - * Random Bit Generators</em>. + * \brief This file contains CTR_DRBG definitions and functions. * + * CTR_DRBG is a standardized way of building a PRNG from a block-cipher + * in counter mode operation, as defined in <em>NIST SP 800-90A: + * Recommendation for Random Number Generation Using Deterministic Random + * Bit Generators</em>. + * + * The Mbed TLS implementation of CTR_DRBG uses AES-256 as the underlying + * block cipher. */ /* * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -156,8 +161,8 @@ void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx ); identifiers. Can be NULL. * \param len The length of the personalization data. * - * \return \c 0 on success, or - * #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. */ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx, int (*f_entropy)(void *, unsigned char *, size_t), @@ -216,22 +221,24 @@ void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx, * \param additional Additional data to add to the state. Can be NULL. * \param len The length of the additional data. * - * \return \c 0 on success, or - * #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. */ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx, const unsigned char *additional, size_t len ); /** - * \brief This function updates the state of the CTR_DRBG context. + * \brief This function updates the state of the CTR_DRBG context. * - * \param ctx The CTR_DRBG context. - * \param additional The data to update the state with. - * \param add_len Length of \p additional data. + * \note If \p add_len is greater than + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, only the first + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used. + * The remaining Bytes are silently discarded. + * + * \param ctx The CTR_DRBG context. + * \param additional The data to update the state with. + * \param add_len Length of \p additional data. * - * \note If \p add_len is greater than #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, - * only the first #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used. - * The remaining Bytes are silently discarded. */ void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx, const unsigned char *additional, size_t add_len ); @@ -249,8 +256,8 @@ void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx, * \param additional Additional data to update. Can be NULL. * \param add_len The length of the additional data. * - * \return \c 0 on success, or - * #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure. */ int mbedtls_ctr_drbg_random_with_add( void *p_rng, @@ -267,8 +274,8 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng, * \param output The buffer to fill. * \param output_len The length of the buffer. * - * \return \c 0 on success, or - * #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure. */ int mbedtls_ctr_drbg_random( void *p_rng, @@ -281,9 +288,9 @@ int mbedtls_ctr_drbg_random( void *p_rng, * \param ctx The CTR_DRBG context. * \param path The name of the file. * - * \return \c 0 on success, - * #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or - * #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on * failure. */ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path ); @@ -295,9 +302,9 @@ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char * \param ctx The CTR_DRBG context. * \param path The name of the file. * - * \return \c 0 on success, - * #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, - * #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or * #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure. */ int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path ); @@ -306,7 +313,8 @@ int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char /** * \brief The CTR_DRBG checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_ctr_drbg_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/des.h b/thirdparty/mbedtls/include/mbedtls/des.h index 5a1a636522..6eb7d03bae 100644 --- a/thirdparty/mbedtls/include/mbedtls/des.h +++ b/thirdparty/mbedtls/include/mbedtls/des.h @@ -46,14 +46,14 @@ #define MBEDTLS_DES_KEY_SIZE 8 -#if !defined(MBEDTLS_DES_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_DES_ALT) +// Regular implementation +// + /** * \brief DES context structure * @@ -76,6 +76,10 @@ typedef struct } mbedtls_des3_context; +#else /* MBEDTLS_DES_ALT */ +#include "des_alt.h" +#endif /* MBEDTLS_DES_ALT */ + /** * \brief Initialize DES context * @@ -331,17 +335,6 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx, */ void mbedtls_des_setkey( uint32_t SK[32], const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_DES_ALT */ -#include "des_alt.h" -#endif /* MBEDTLS_DES_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif /** * \brief Checkup routine diff --git a/thirdparty/mbedtls/include/mbedtls/dhm.h b/thirdparty/mbedtls/include/mbedtls/dhm.h index 00fafd8d16..75317a8e6d 100644 --- a/thirdparty/mbedtls/include/mbedtls/dhm.h +++ b/thirdparty/mbedtls/include/mbedtls/dhm.h @@ -1,7 +1,13 @@ /** * \file dhm.h * - * \brief Diffie-Hellman-Merkle key exchange. + * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange + * definitions and functions. + * + * Diffie-Hellman-Merkle (DHM) key exchange is defined in + * <em>RFC-2631: Diffie-Hellman Key Agreement Method</em> and + * <em>Public-Key Cryptography Standards (PKCS) #3: Diffie + * Hellman Key Agreement Standard</em>. * * <em>RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for * Internet Key Exchange (IKE)</em> defines a number of standardized @@ -65,7 +71,6 @@ #include MBEDTLS_CONFIG_FILE #endif #include "bignum.h" -#if !defined(MBEDTLS_DHM_ALT) /* * DHM Error codes @@ -86,6 +91,8 @@ extern "C" { #endif +#if !defined(MBEDTLS_DHM_ALT) + /** * \brief The DHM context structure. */ @@ -105,6 +112,10 @@ typedef struct } mbedtls_dhm_context; +#else /* MBEDTLS_DHM_ALT */ +#include "dhm_alt.h" +#endif /* MBEDTLS_DHM_ALT */ + /** * \brief This function initializes the DHM context. * @@ -125,8 +136,8 @@ void mbedtls_dhm_init( mbedtls_dhm_context *ctx ); * failures. * \param end The end of the input buffer. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, unsigned char **p, @@ -136,13 +147,6 @@ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, * \brief This function sets up and writes the ServerKeyExchange * parameters. * - * \param ctx The DHM context. - * \param x_size The private value size in Bytes. - * \param olen The number of characters written. - * \param output The destination buffer. - * \param f_rng The RNG function. - * \param p_rng The RNG parameter. - * * \note The destination buffer must be large enough to hold * the reduced binary presentation of the modulus, the generator * and the public key, each wrapped with a 2-byte length field. @@ -155,8 +159,15 @@ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, * mbedtls_dhm_set_group() below in conjunction with * mbedtls_mpi_read_binary() and mbedtls_mpi_read_string(). * - * \return \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code - * on failure. + * \param ctx The DHM context. + * \param x_size The private key size in Bytes. + * \param olen The number of characters written. + * \param output The destination buffer. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t *olen, @@ -164,54 +175,54 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, void *p_rng ); /** - * \brief Set prime modulus and generator + * \brief This function sets the prime modulus and generator. * - * \param ctx The DHM context. - * \param P The MPI holding DHM prime modulus. - * \param G The MPI holding DHM generator. + * \note This function can be used to set \p P, \p G + * in preparation for mbedtls_dhm_make_params(). * - * \note This function can be used to set P, G - * in preparation for \c mbedtls_dhm_make_params. + * \param ctx The DHM context. + * \param P The MPI holding the DHM prime modulus. + * \param G The MPI holding the DHM generator. * - * \return \c 0 if successful, or an \c MBEDTLS_ERR_DHM_XXX error code - * on failure. + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx, const mbedtls_mpi *P, const mbedtls_mpi *G ); /** - * \brief This function imports the public value G^Y of the peer. + * \brief This function imports the public value of the peer, G^Y. * * \param ctx The DHM context. - * \param input The input buffer. + * \param input The input buffer containing the G^Y value of the peer. * \param ilen The size of the input buffer. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx, const unsigned char *input, size_t ilen ); /** - * \brief This function creates its own private value \c X and + * \brief This function creates its own private key, \c X, and * exports \c G^X. * + * \note The destination buffer is always fully written + * so as to contain a big-endian representation of G^X mod P. + * If it is larger than ctx->len, it is padded accordingly + * with zero-bytes at the beginning. + * * \param ctx The DHM context. - * \param x_size The private value size in Bytes. + * \param x_size The private key size in Bytes. * \param output The destination buffer. * \param olen The length of the destination buffer. Must be at least - equal to ctx->len (the size of \c P). + * equal to ctx->len (the size of \c P). * \param f_rng The RNG function. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * - * \note The destination buffer will always be fully written - * so as to contain a big-endian presentation of G^X mod P. - * If it is larger than ctx->len, it will accordingly be - * padded with zero-bytes in the beginning. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t olen, @@ -222,22 +233,22 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, * \brief This function derives and exports the shared secret * \c (G^Y)^X mod \c P. * + * \note If \p f_rng is not NULL, it is used to blind the input as + * a countermeasure against timing attacks. Blinding is used + * only if our private key \c X is re-used, and not used + * otherwise. We recommend always passing a non-NULL + * \p f_rng argument. + * * \param ctx The DHM context. * \param output The destination buffer. * \param output_size The size of the destination buffer. Must be at least - * the size of ctx->len. + * the size of ctx->len (the size of \c P). * \param olen On exit, holds the actual number of Bytes written. * \param f_rng The RNG function, for blinding purposes. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code - * on failure. - * - * \note If non-NULL, \p f_rng is used to blind the input as - * a countermeasure against timing attacks. Blinding is used - * only if our secret value \p X is re-used and omitted - * otherwise. Therefore, we recommend always passing a - * non-NULL \p f_rng argument. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, unsigned char *output, size_t output_size, size_t *olen, @@ -245,7 +256,7 @@ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, void *p_rng ); /** - * \brief This function frees and clears the components of a DHM key. + * \brief This function frees and clears the components of a DHM context. * * \param ctx The DHM context to free and clear. */ @@ -261,8 +272,9 @@ void mbedtls_dhm_free( mbedtls_dhm_context *ctx ); * \param dhminlen The size of the buffer, including the terminating null * Byte for PEM data. * - * \return \c 0 on success, or a specific DHM or PEM error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error code + * error code on failure. */ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, size_t dhminlen ); @@ -275,29 +287,19 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, * \param dhm The DHM context to load the parameters to. * \param path The filename to read the DHM parameters from. * - * \return \c 0 on success, or a specific DHM or PEM error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error code + * error code on failure. */ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path ); #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_ASN1_PARSE_C */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_DHM_ALT */ -#include "dhm_alt.h" -#endif /* MBEDTLS_DHM_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief The DMH checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_dhm_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/ecdh.h b/thirdparty/mbedtls/include/mbedtls/ecdh.h index 99cfde00d0..5fdf55a88a 100644 --- a/thirdparty/mbedtls/include/mbedtls/ecdh.h +++ b/thirdparty/mbedtls/include/mbedtls/ecdh.h @@ -1,10 +1,11 @@ /** * \file ecdh.h * - * \brief The Elliptic Curve Diffie-Hellman (ECDH) protocol APIs. + * \brief This file contains ECDH definitions and functions. * - * ECDH is an anonymous key agreement protocol allowing two parties to - * establish a shared secret over an insecure channel. Each party must have an + * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous + * key agreement protocol allowing two parties to establish a shared + * secret over an insecure channel. Each party must have an * elliptic-curve public–private key pair. * * For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for @@ -40,14 +41,12 @@ extern "C" { #endif /** - * Defines the source of the imported EC key: - * <ul><li>Our key.</li> - * <li>The key of the peer.</li></ul> + * Defines the source of the imported EC key. */ typedef enum { - MBEDTLS_ECDH_OURS, - MBEDTLS_ECDH_THEIRS, + MBEDTLS_ECDH_OURS, /**< Our key. */ + MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */ } mbedtls_ecdh_side; /** @@ -75,16 +74,18 @@ mbedtls_ecdh_context; * implemented during the ECDH key exchange. The second core * computation is performed by mbedtls_ecdh_compute_shared(). * + * \see ecp.h + * * \param grp The ECP group. * \param d The destination MPI (private key). * \param Q The destination point (public key). * \param f_rng The RNG function. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX or + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or * \c MBEDTLS_MPI_XXX error code on failure. * - * \see ecp.h */ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), @@ -97,21 +98,22 @@ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp * implemented during the ECDH key exchange. The first core * computation is performed by mbedtls_ecdh_gen_public(). * + * \see ecp.h + * + * \note If \p f_rng is not NULL, it is used to implement + * countermeasures against side-channel attacks. + * For more information, see mbedtls_ecp_mul(). + * * \param grp The ECP group. * \param z The destination MPI (shared secret). * \param Q The public key from another party. * \param d Our secret exponent (private key). * \param f_rng The RNG function. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX or + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or * \c MBEDTLS_MPI_XXX error code on failure. - * - * \see ecp.h - * - * \note If \p f_rng is not NULL, it is used to implement - * countermeasures against potential elaborate timing - * attacks. For more information, see mbedtls_ecp_mul(). */ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, const mbedtls_ecp_point *Q, const mbedtls_mpi *d, @@ -139,21 +141,21 @@ void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx ); * This is the first function used by a TLS server for ECDHE * ciphersuites. * + * \note This function assumes that the ECP group (grp) of the + * \p ctx context has already been properly set, + * for example, using mbedtls_ecp_group_load(). + * + * \see ecp.h + * * \param ctx The ECDH context. * \param olen The number of characters written. * \param buf The destination buffer. * \param blen The length of the destination buffer. * \param f_rng The RNG function. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * - * \note This function assumes that the ECP group (grp) of the - * \p ctx context has already been properly set, - * for example, using mbedtls_ecp_group_load(). - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code - * on failure. - * - * \see ecp.h + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, @@ -167,14 +169,15 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, * This is the first function used by a TLS client for ECDHE * ciphersuites. * + * \see ecp.h + * * \param ctx The ECDH context. * \param buf The pointer to the start of the input buffer. * \param end The address for one Byte past the end of the buffer. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. * - * \see ecp.h */ int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx, const unsigned char **buf, const unsigned char *end ); @@ -186,16 +189,16 @@ int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx, * ServerKeyEchange for static ECDH, and imports ECDH * parameters from the EC key information of a certificate. * + * \see ecp.h + * * \param ctx The ECDH context to set up. * \param key The EC key to use. - * \param side Defines the source of the key: - * <ul><li>1: Our key.</li> - <li>0: The key of the peer.</li></ul> + * \param side Defines the source of the key: 1: Our key, or + * 0: The key of the peer. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. * - * \see ecp.h */ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key, mbedtls_ecdh_side side ); @@ -207,17 +210,17 @@ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypai * This is the second function used by a TLS client for ECDH(E) * ciphersuites. * + * \see ecp.h + * * \param ctx The ECDH context. * \param olen The number of Bytes written. * \param buf The destination buffer. * \param blen The size of the destination buffer. * \param f_rng The RNG function. - * \param p_rng The RNG parameter. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code - * on failure. + * \param p_rng The RNG context. * - * \see ecp.h + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, @@ -231,14 +234,14 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, * This is the second function used by a TLS server for ECDH(E) * ciphersuites. * + * \see ecp.h + * * \param ctx The ECDH context. * \param buf The start of the input buffer. * \param blen The length of the input buffer. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code - * on failure. - * - * \see ecp.h + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx, const unsigned char *buf, size_t blen ); @@ -249,21 +252,21 @@ int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx, * This is the last function used by both TLS client * and servers. * + * \note If \p f_rng is not NULL, it is used to implement + * countermeasures against side-channel attacks. + * For more information, see mbedtls_ecp_mul(). + * + * \see ecp.h + * * \param ctx The ECDH context. * \param olen The number of Bytes written. * \param buf The destination buffer. * \param blen The length of the destination buffer. * \param f_rng The RNG function. - * \param p_rng The RNG parameter. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code - * on failure. + * \param p_rng The RNG context. * - * \see ecp.h - * - * \note If \p f_rng is not NULL, it is used to implement - * countermeasures against potential elaborate timing - * attacks. For more information, see mbedtls_ecp_mul(). + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, diff --git a/thirdparty/mbedtls/include/mbedtls/ecdsa.h b/thirdparty/mbedtls/include/mbedtls/ecdsa.h index aa23d67f99..ce1a03d791 100644 --- a/thirdparty/mbedtls/include/mbedtls/ecdsa.h +++ b/thirdparty/mbedtls/include/mbedtls/ecdsa.h @@ -1,9 +1,10 @@ /** * \file ecdsa.h * - * \brief The Elliptic Curve Digital Signature Algorithm (ECDSA). + * \brief This file contains ECDSA definitions and functions. * - * ECDSA is defined in <em>Standards for Efficient Cryptography Group (SECG): + * The Elliptic Curve Digital Signature Algorithm (ECDSA) is defined in + * <em>Standards for Efficient Cryptography Group (SECG): * SEC1 Elliptic Curve Cryptography</em>. * The use of ECDSA for TLS is defined in <em>RFC-4492: Elliptic Curve * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)</em>. @@ -69,6 +70,14 @@ extern "C" { * * \note The deterministic version is usually preferred. * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated + * as defined in <em>Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography</em>, section + * 4.1.3, step 5. + * + * \see ecp.h + * * \param grp The ECP group. * \param r The first output integer. * \param s The second output integer. @@ -76,18 +85,11 @@ extern "C" { * \param buf The message hash. * \param blen The length of \p buf. * \param f_rng The RNG function. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * - * \note If the bitlength of the message hash is larger than the - * bitlength of the group order, then the hash is truncated - * as defined in <em>Standards for Efficient Cryptography Group - * (SECG): SEC1 Elliptic Curve Cryptography</em>, section - * 4.1.3, step 5. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX * or \c MBEDTLS_MPI_XXX error code on failure. - * - * \see ecp.h */ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, @@ -97,10 +99,19 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, /** * \brief This function computes the ECDSA signature of a * previously-hashed message, deterministic version. + * * For more information, see <em>RFC-6979: Deterministic * Usage of the Digital Signature Algorithm (DSA) and Elliptic * Curve Digital Signature Algorithm (ECDSA)</em>. * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in <em>Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography</em>, section + * 4.1.3, step 5. + * + * \see ecp.h + * * \param grp The ECP group. * \param r The first output integer. * \param s The second output integer. @@ -109,17 +120,9 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, * \param blen The length of \p buf. * \param md_alg The MD algorithm used to hash the message. * - * \note If the bitlength of the message hash is larger than the - * bitlength of the group order, then the hash is truncated as - * defined in <em>Standards for Efficient Cryptography Group - * (SECG): SEC1 Elliptic Curve Cryptography</em>, section - * 4.1.3, step 5. - * - * \return \c 0 on success, - * or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX * error code on failure. - * - * \see ecp.h */ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, @@ -130,6 +133,14 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi * \brief This function verifies the ECDSA signature of a * previously-hashed message. * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in <em>Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography</em>, section + * 4.1.4, step 3. + * + * \see ecp.h + * * \param grp The ECP group. * \param buf The message hash. * \param blen The length of \p buf. @@ -137,18 +148,11 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi * \param r The first integer of the signature. * \param s The second integer of the signature. * - * \note If the bitlength of the message hash is larger than the - * bitlength of the group order, then the hash is truncated as - * defined in <em>Standards for Efficient Cryptography Group - * (SECG): SEC1 Elliptic Curve Cryptography</em>, section - * 4.1.4, step 3. - * - * \return \c 0 on success, - * #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid, - * or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the signature + * is invalid. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX * error code on failure for any other reason. - * - * \see ecp.h */ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, @@ -169,15 +173,6 @@ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, * of the Digital Signature Algorithm (DSA) and Elliptic * Curve Digital Signature Algorithm (ECDSA)</em>. * - * \param ctx The ECDSA context. - * \param md_alg The message digest that was used to hash the message. - * \param hash The message hash. - * \param hlen The length of the hash. - * \param sig The buffer that holds the signature. - * \param slen The length of the signature written. - * \param f_rng The RNG function. - * \param p_rng The RNG parameter. - * * \note The \p sig buffer must be at least twice as large as the * size of the curve used, plus 9. For example, 73 Bytes if * a 256-bit curve is used. A buffer length of @@ -189,11 +184,20 @@ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.3, step 5. * - * \return \c 0 on success, - * or an \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or - * \c MBEDTLS_ERR_ASN1_XXX error code on failure. - * * \see ecp.h + * + * \param ctx The ECDSA context. + * \param md_alg The message digest that was used to hash the message. + * \param hash The message hash. + * \param hlen The length of the hash. + * \param sig The buffer that holds the signature. + * \param slen The length of the signature written. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, @@ -209,26 +213,17 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t #define MBEDTLS_DEPRECATED #endif /** - * \brief This function computes an ECDSA signature and writes it to a buffer, - * serialized as defined in <em>RFC-4492: Elliptic Curve Cryptography - * (ECC) Cipher Suites for Transport Layer Security (TLS)</em>. + * \brief This function computes an ECDSA signature and writes + * it to a buffer, serialized as defined in <em>RFC-4492: + * Elliptic Curve Cryptography (ECC) Cipher Suites for + * Transport Layer Security (TLS)</em>. * - * The deterministic version is defined in <em>RFC-6979: - * Deterministic Usage of the Digital Signature Algorithm (DSA) and - * Elliptic Curve Digital Signature Algorithm (ECDSA)</em>. + * The deterministic version is defined in <em>RFC-6979: + * Deterministic Usage of the Digital Signature Algorithm (DSA) + * and Elliptic Curve Digital Signature Algorithm (ECDSA)</em>. * * \warning It is not thread-safe to use the same context in * multiple threads. - - * - * \deprecated Superseded by mbedtls_ecdsa_write_signature() in 2.0.0 - * - * \param ctx The ECDSA context. - * \param hash The Message hash. - * \param hlen The length of the hash. - * \param sig The buffer that holds the signature. - * \param slen The length of the signature written. - * \param md_alg The MD algorithm used to hash the message. * * \note The \p sig buffer must be at least twice as large as the * size of the curve used, plus 9. For example, 73 Bytes if a @@ -241,11 +236,21 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.3, step 5. * - * \return \c 0 on success, - * or an \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or - * \c MBEDTLS_ERR_ASN1_XXX error code on failure. - * * \see ecp.h + * + * \deprecated Superseded by mbedtls_ecdsa_write_signature() in + * Mbed TLS version 2.0 and later. + * + * \param ctx The ECDSA context. + * \param hash The message hash. + * \param hlen The length of the hash. + * \param sig The buffer that holds the signature. + * \param slen The length of the signature written. + * \param md_alg The MD algorithm used to hash the message. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, @@ -258,26 +263,26 @@ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, /** * \brief This function reads and verifies an ECDSA signature. * - * \param ctx The ECDSA context. - * \param hash The message hash. - * \param hlen The size of the hash. - * \param sig The signature to read and verify. - * \param slen The size of \p sig. - * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as * defined in <em>Standards for Efficient Cryptography Group * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.4, step 3. * - * \return \c 0 on success, - * #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid, - * #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if the signature is - * valid but its actual length is less than \p siglen, - * or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX - * error code on failure for any other reason. - * * \see ecp.h + * + * \param ctx The ECDSA context. + * \param hash The message hash. + * \param hlen The size of the hash. + * \param sig The signature to read and verify. + * \param slen The size of \p sig. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. + * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid + * signature in \p sig, but its length is less than \p siglen. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX + * error code on failure for any other reason. */ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, @@ -286,16 +291,16 @@ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, /** * \brief This function generates an ECDSA keypair on the given curve. * + * \see ecp.h + * * \param ctx The ECDSA context to store the keypair in. * \param gid The elliptic curve to use. One of the various * \c MBEDTLS_ECP_DP_XXX macros depending on configuration. * \param f_rng The RNG function. - * \param p_rng The RNG parameter. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX code on - * failure. + * \param p_rng The RNG context. * - * \see ecp.h + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. */ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); @@ -303,13 +308,13 @@ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, /** * \brief This function sets an ECDSA context from an EC key pair. * + * \see ecp.h + * * \param ctx The ECDSA context to set. * \param key The EC key to use. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX code on - * failure. - * - * \see ecp.h + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. */ int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ); diff --git a/thirdparty/mbedtls/include/mbedtls/ecjpake.h b/thirdparty/mbedtls/include/mbedtls/ecjpake.h index d86e8207f1..cc2b316f5e 100644 --- a/thirdparty/mbedtls/include/mbedtls/ecjpake.h +++ b/thirdparty/mbedtls/include/mbedtls/ecjpake.h @@ -44,8 +44,6 @@ #include "ecp.h" #include "md.h" -#if !defined(MBEDTLS_ECJPAKE_ALT) - #ifdef __cplusplus extern "C" { #endif @@ -58,6 +56,7 @@ typedef enum { MBEDTLS_ECJPAKE_SERVER, /**< Server */ } mbedtls_ecjpake_role; +#if !defined(MBEDTLS_ECJPAKE_ALT) /** * EC J-PAKE context structure. * @@ -88,6 +87,10 @@ typedef struct mbedtls_mpi s; /**< Pre-shared secret (passphrase) */ } mbedtls_ecjpake_context; +#else /* MBEDTLS_ECJPAKE_ALT */ +#include "ecjpake_alt.h" +#endif /* MBEDTLS_ECJPAKE_ALT */ + /** * \brief Initialize a context * (just makes it ready for setup() or free()). @@ -225,20 +228,10 @@ int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx, */ void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx ); -#ifdef __cplusplus -} -#endif -#else /* MBEDTLS_ECJPAKE_ALT */ -#include "ecjpake_alt.h" -#endif /* MBEDTLS_ECJPAKE_ALT */ #if defined(MBEDTLS_SELF_TEST) -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * @@ -246,10 +239,11 @@ extern "C" { */ int mbedtls_ecjpake_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + #ifdef __cplusplus } #endif -#endif /* MBEDTLS_SELF_TEST */ #endif /* ecjpake.h */ diff --git a/thirdparty/mbedtls/include/mbedtls/ecp.h b/thirdparty/mbedtls/include/mbedtls/ecp.h index b00ba4da87..3a407986dd 100644 --- a/thirdparty/mbedtls/include/mbedtls/ecp.h +++ b/thirdparty/mbedtls/include/mbedtls/ecp.h @@ -1,10 +1,21 @@ /** * \file ecp.h * - * \brief Elliptic curves over GF(p) + * \brief This file provides an API for Elliptic Curves over GF(P) (ECP). + * + * The use of ECP in cryptography and TLS is defined in + * <em>Standards for Efficient Cryptography Group (SECG): SEC1 + * Elliptic Curve Cryptography</em> and + * <em>RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites + * for Transport Layer Security (TLS)</em>. + * + * <em>RFC-2409: The Internet Key Exchange (IKE)</em> defines ECP + * group types. + * */ + /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,8 +30,9 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This file is part of mbed TLS (https://tls.mbed.org) + * This file is part of Mbed TLS (https://tls.mbed.org) */ + #ifndef MBEDTLS_ECP_H #define MBEDTLS_ECP_H @@ -31,160 +43,157 @@ */ #define MBEDTLS_ERR_ECP_BAD_INPUT_DATA -0x4F80 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL -0x4F00 /**< The buffer is too small to write to. */ -#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80 /**< Requested curve not available. */ +#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80 /**< The requested feature is not available, for example, the requested curve is not supported. */ #define MBEDTLS_ERR_ECP_VERIFY_FAILED -0x4E00 /**< The signature is not valid. */ #define MBEDTLS_ERR_ECP_ALLOC_FAILED -0x4D80 /**< Memory allocation failed. */ -#define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as (ephemeral) key, failed. */ +#define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as ephemeral key, failed. */ #define MBEDTLS_ERR_ECP_INVALID_KEY -0x4C80 /**< Invalid private or public key. */ -#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< Signature is valid but shorter than the user-supplied length. */ -#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED -0x4B80 /**< ECP hardware accelerator failed. */ - -#if !defined(MBEDTLS_ECP_ALT) -/* - * default mbed TLS elliptic curve arithmetic implementation - * - * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an - * alternative implementation for the whole module and it will replace this - * one.) - */ +#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< The buffer contains a valid signature followed by more data. */ +#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED -0x4B80 /**< The ECP hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif /** - * Domain parameters (curve, subgroup and generator) identifiers. + * Domain-parameter identifiers: curve, subgroup, and generator. * - * Only curves over prime fields are supported. + * \note Only curves over prime fields are supported. * * \warning This library does not support validation of arbitrary domain - * parameters. Therefore, only well-known domain parameters from trusted + * parameters. Therefore, only standardized domain parameters from trusted * sources should be used. See mbedtls_ecp_group_load(). */ typedef enum { - MBEDTLS_ECP_DP_NONE = 0, - MBEDTLS_ECP_DP_SECP192R1, /*!< 192-bits NIST curve */ - MBEDTLS_ECP_DP_SECP224R1, /*!< 224-bits NIST curve */ - MBEDTLS_ECP_DP_SECP256R1, /*!< 256-bits NIST curve */ - MBEDTLS_ECP_DP_SECP384R1, /*!< 384-bits NIST curve */ - MBEDTLS_ECP_DP_SECP521R1, /*!< 521-bits NIST curve */ - MBEDTLS_ECP_DP_BP256R1, /*!< 256-bits Brainpool curve */ - MBEDTLS_ECP_DP_BP384R1, /*!< 384-bits Brainpool curve */ - MBEDTLS_ECP_DP_BP512R1, /*!< 512-bits Brainpool curve */ - MBEDTLS_ECP_DP_CURVE25519, /*!< Curve25519 */ - MBEDTLS_ECP_DP_SECP192K1, /*!< 192-bits "Koblitz" curve */ - MBEDTLS_ECP_DP_SECP224K1, /*!< 224-bits "Koblitz" curve */ - MBEDTLS_ECP_DP_SECP256K1, /*!< 256-bits "Koblitz" curve */ + MBEDTLS_ECP_DP_NONE = 0, /*!< Curve not defined. */ + MBEDTLS_ECP_DP_SECP192R1, /*!< Domain parameters for the 192-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP224R1, /*!< Domain parameters for the 224-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP256R1, /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP384R1, /*!< Domain parameters for the 384-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP521R1, /*!< Domain parameters for the 521-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_BP256R1, /*!< Domain parameters for 256-bit Brainpool curve. */ + MBEDTLS_ECP_DP_BP384R1, /*!< Domain parameters for 384-bit Brainpool curve. */ + MBEDTLS_ECP_DP_BP512R1, /*!< Domain parameters for 512-bit Brainpool curve. */ + MBEDTLS_ECP_DP_CURVE25519, /*!< Domain parameters for Curve25519. */ + MBEDTLS_ECP_DP_SECP192K1, /*!< Domain parameters for 192-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_SECP224K1, /*!< Domain parameters for 224-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_SECP256K1, /*!< Domain parameters for 256-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_CURVE448, /*!< Domain parameters for Curve448. */ } mbedtls_ecp_group_id; /** - * Number of supported curves (plus one for NONE). + * The number of supported curves, plus one for #MBEDTLS_ECP_DP_NONE. * - * (Montgomery curves excluded for now.) + * \note Montgomery curves are currently excluded. */ #define MBEDTLS_ECP_DP_MAX 12 /** - * Curve information for use by other modules + * Curve information, for use by other modules. */ typedef struct { - mbedtls_ecp_group_id grp_id; /*!< Internal identifier */ - uint16_t tls_id; /*!< TLS NamedCurve identifier */ - uint16_t bit_size; /*!< Curve size in bits */ - const char *name; /*!< Human-friendly name */ + mbedtls_ecp_group_id grp_id; /*!< An internal identifier. */ + uint16_t tls_id; /*!< The TLS NamedCurve identifier. */ + uint16_t bit_size; /*!< The curve size in bits. */ + const char *name; /*!< A human-friendly name. */ } mbedtls_ecp_curve_info; /** - * \brief ECP point structure (jacobian coordinates) + * \brief The ECP point structure, in Jacobian coordinates. * * \note All functions expect and return points satisfying - * the following condition: Z == 0 or Z == 1. (Other - * values of Z are used by internal functions only.) - * The point is zero, or "at infinity", if Z == 0. - * Otherwise, X and Y are its standard (affine) coordinates. + * the following condition: <code>Z == 0</code> or + * <code>Z == 1</code>. Other values of \p Z are + * used only by internal functions. + * The point is zero, or "at infinity", if <code>Z == 0</code>. + * Otherwise, \p X and \p Y are its standard (affine) + * coordinates. */ typedef struct { - mbedtls_mpi X; /*!< the point's X coordinate */ - mbedtls_mpi Y; /*!< the point's Y coordinate */ - mbedtls_mpi Z; /*!< the point's Z coordinate */ + mbedtls_mpi X; /*!< The X coordinate of the ECP point. */ + mbedtls_mpi Y; /*!< The Y coordinate of the ECP point. */ + mbedtls_mpi Z; /*!< The Z coordinate of the ECP point. */ } mbedtls_ecp_point; -/** - * \brief ECP group structure - * - * We consider two types of curves equations: - * 1. Short Weierstrass y^2 = x^3 + A x + B mod P (SEC1 + RFC 4492) - * 2. Montgomery, y^2 = x^3 + A x^2 + x mod P (Curve25519 + draft) - * In both cases, a generator G for a prime-order subgroup is fixed. In the - * short weierstrass, this subgroup is actually the whole curve, and its - * cardinal is denoted by N. - * - * In the case of Short Weierstrass curves, our code requires that N is an odd - * prime. (Use odd in mbedtls_ecp_mul() and prime in mbedtls_ecdsa_sign() for blinding.) - * - * In the case of Montgomery curves, we don't store A but (A + 2) / 4 which is - * the quantity actually used in the formulas. Also, nbits is not the size of N - * but the required size for private keys. +#if !defined(MBEDTLS_ECP_ALT) +/* + * default mbed TLS elliptic curve arithmetic implementation * - * If modp is NULL, reduction modulo P is done using a generic algorithm. - * Otherwise, it must point to a function that takes an mbedtls_mpi in the range - * 0..2^(2*pbits)-1 and transforms it in-place in an integer of little more - * than pbits, so that the integer may be efficiently brought in the 0..P-1 - * range by a few additions or substractions. It must return 0 on success and - * non-zero on failure. + * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an + * alternative implementation for the whole module and it will replace this + * one.) */ -typedef struct -{ - mbedtls_ecp_group_id id; /*!< internal group identifier */ - mbedtls_mpi P; /*!< prime modulus of the base field */ - mbedtls_mpi A; /*!< 1. A in the equation, or 2. (A + 2) / 4 */ - mbedtls_mpi B; /*!< 1. B in the equation, or 2. unused */ - mbedtls_ecp_point G; /*!< generator of the (sub)group used */ - mbedtls_mpi N; /*!< 1. the order of G, or 2. unused */ - size_t pbits; /*!< number of bits in P */ - size_t nbits; /*!< number of bits in 1. P, or 2. private keys */ - unsigned int h; /*!< internal: 1 if the constants are static */ - int (*modp)(mbedtls_mpi *); /*!< function for fast reduction mod P */ - int (*t_pre)(mbedtls_ecp_point *, void *); /*!< unused */ - int (*t_post)(mbedtls_ecp_point *, void *); /*!< unused */ - void *t_data; /*!< unused */ - mbedtls_ecp_point *T; /*!< pre-computed points for ecp_mul_comb() */ - size_t T_size; /*!< number for pre-computed points */ -} -mbedtls_ecp_group; /** - * \brief ECP key pair structure + * \brief The ECP group structure. + * + * We consider two types of curve equations: + * <ul><li>Short Weierstrass: <code>y^2 = x^3 + A x + B mod P</code> + * (SEC1 + RFC-4492)</li> + * <li>Montgomery: <code>y^2 = x^3 + A x^2 + x mod P</code> (Curve25519, + * Curve448)</li></ul> + * In both cases, the generator (\p G) for a prime-order subgroup is fixed. * - * A generic key pair that could be used for ECDSA, fixed ECDH, etc. + * For Short Weierstrass, this subgroup is the whole curve, and its + * cardinality is denoted by \p N. Our code requires that \p N is an + * odd prime as mbedtls_ecp_mul() requires an odd number, and + * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes. + * + * For Montgomery curves, we do not store \p A, but <code>(A + 2) / 4</code>, + * which is the quantity used in the formulas. Additionally, \p nbits is + * not the size of \p N but the required size for private keys. + * + * If \p modp is NULL, reduction modulo \p P is done using a generic algorithm. + * Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the + * range of <code>0..2^(2*pbits)-1</code>, and transforms it in-place to an integer + * which is congruent mod \p P to the given MPI, and is close enough to \p pbits + * in size, so that it may be efficiently brought in the 0..P-1 range by a few + * additions or subtractions. Therefore, it is only an approximative modular + * reduction. It must return 0 on success and non-zero on failure. * - * \note Members purposefully in the same order as struc mbedtls_ecdsa_context. */ typedef struct { - mbedtls_ecp_group grp; /*!< Elliptic curve and base point */ - mbedtls_mpi d; /*!< our secret value */ - mbedtls_ecp_point Q; /*!< our public value */ + mbedtls_ecp_group_id id; /*!< An internal group identifier. */ + mbedtls_mpi P; /*!< The prime modulus of the base field. */ + mbedtls_mpi A; /*!< For Short Weierstrass: \p A in the equation. For + Montgomery curves: <code>(A + 2) / 4</code>. */ + mbedtls_mpi B; /*!< For Short Weierstrass: \p B in the equation. + For Montgomery curves: unused. */ + mbedtls_ecp_point G; /*!< The generator of the subgroup used. */ + mbedtls_mpi N; /*!< The order of \p G. */ + size_t pbits; /*!< The number of bits in \p P.*/ + size_t nbits; /*!< For Short Weierstrass: The number of bits in \p P. + For Montgomery curves: the number of bits in the + private keys. */ + unsigned int h; /*!< \internal 1 if the constants are static. */ + int (*modp)(mbedtls_mpi *); /*!< The function for fast pseudo-reduction + mod \p P (see above).*/ + int (*t_pre)(mbedtls_ecp_point *, void *); /*!< Unused. */ + int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */ + void *t_data; /*!< Unused. */ + mbedtls_ecp_point *T; /*!< Pre-computed points for ecp_mul_comb(). */ + size_t T_size; /*!< The number of pre-computed points. */ } -mbedtls_ecp_keypair; +mbedtls_ecp_group; /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. - * Either change them in config.h or define them on the compiler command line. + * Either change them in config.h, or define them using the compiler command line. * \{ */ #if !defined(MBEDTLS_ECP_MAX_BITS) /** - * Maximum size of the groups (that is, of N and P) + * The maximum size of the groups, that is, of \c N and \c P. */ -#define MBEDTLS_ECP_MAX_BITS 521 /**< Maximum bit size of groups */ +#define MBEDTLS_ECP_MAX_BITS 521 /**< The maximum size of groups, in bits. */ #endif #define MBEDTLS_ECP_MAX_BYTES ( ( MBEDTLS_ECP_MAX_BITS + 7 ) / 8 ) @@ -207,11 +216,10 @@ mbedtls_ecp_keypair; * 521 145 141 135 120 97 * 384 214 209 198 177 146 * 256 320 320 303 262 226 - * 224 475 475 453 398 342 * 192 640 640 633 587 476 */ -#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< Maximum window size used */ +#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< The maximum window size used. */ #endif /* MBEDTLS_ECP_WINDOW_SIZE */ #if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM) @@ -226,33 +234,55 @@ mbedtls_ecp_keypair; * * Change this value to 0 to reduce peak memory usage. */ -#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ +#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */ #endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */ /* \} name SECTION: Module settings */ +#else /* MBEDTLS_ECP_ALT */ +#include "ecp_alt.h" +#endif /* MBEDTLS_ECP_ALT */ + +/** + * \brief The ECP key-pair structure. + * + * A generic key-pair that may be used for ECDSA and fixed ECDH, for example. + * + * \note Members are deliberately in the same order as in the + * ::mbedtls_ecdsa_context structure. + */ +typedef struct +{ + mbedtls_ecp_group grp; /*!< Elliptic curve and base point */ + mbedtls_mpi d; /*!< our secret value */ + mbedtls_ecp_point Q; /*!< our public value */ +} +mbedtls_ecp_keypair; + /* * Point formats, from RFC 4492's enum ECPointFormat */ -#define MBEDTLS_ECP_PF_UNCOMPRESSED 0 /**< Uncompressed point format */ -#define MBEDTLS_ECP_PF_COMPRESSED 1 /**< Compressed point format */ +#define MBEDTLS_ECP_PF_UNCOMPRESSED 0 /**< Uncompressed point format. */ +#define MBEDTLS_ECP_PF_COMPRESSED 1 /**< Compressed point format. */ /* * Some other constants from RFC 4492 */ -#define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< ECCurveType's named_curve */ +#define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< The named_curve of ECCurveType. */ /** - * \brief Get the list of supported curves in order of preferrence - * (full information) + * \brief This function retrieves the information defined in + * mbedtls_ecp_curve_info() for all supported curves in order + * of preference. * - * \return A statically allocated array, the last entry is 0. + * \return A statically allocated array. The last entry is 0. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ); /** - * \brief Get the list of supported curves in order of preferrence - * (grp_id only) + * \brief This function retrieves the list of internal group + * identifiers of all supported curves in the order of + * preference. * * \return A statically allocated array, * terminated with MBEDTLS_ECP_DP_NONE. @@ -260,357 +290,400 @@ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ); const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void ); /** - * \brief Get curve information from an internal group identifier + * \brief This function retrieves curve information from an internal + * group identifier. * - * \param grp_id A MBEDTLS_ECP_DP_XXX value + * \param grp_id An \c MBEDTLS_ECP_DP_XXX value. * - * \return The associated curve information or NULL + * \return The associated curve information on success. + * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id ); /** - * \brief Get curve information from a TLS NamedCurve value + * \brief This function retrieves curve information from a TLS + * NamedCurve value. * - * \param tls_id A MBEDTLS_ECP_DP_XXX value + * \param tls_id An \c MBEDTLS_ECP_DP_XXX value. * - * \return The associated curve information or NULL + * \return The associated curve information on success. + * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id ); /** - * \brief Get curve information from a human-readable name + * \brief This function retrieves curve information from a + * human-readable name. * - * \param name The name + * \param name The human-readable name. * - * \return The associated curve information or NULL + * \return The associated curve information on success. + * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name ); /** - * \brief Initialize a point (as zero) + * \brief This function initializes a point as zero. + * + * \param pt The point to initialize. */ void mbedtls_ecp_point_init( mbedtls_ecp_point *pt ); /** - * \brief Initialize a group (to something meaningless) + * \brief This function initializes an ECP group context + * without loading any domain parameters. + * + * \note After this function is called, domain parameters + * for various ECP groups can be loaded through the + * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group() + * functions. */ void mbedtls_ecp_group_init( mbedtls_ecp_group *grp ); /** - * \brief Initialize a key pair (as an invalid one) + * \brief This function initializes a key pair as an invalid one. + * + * \param key The key pair to initialize. */ void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key ); /** - * \brief Free the components of a point + * \brief This function frees the components of a point. + * + * \param pt The point to free. */ void mbedtls_ecp_point_free( mbedtls_ecp_point *pt ); /** - * \brief Free the components of an ECP group + * \brief This function frees the components of an ECP group. + * \param grp The group to free. */ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ); /** - * \brief Free the components of a key pair + * \brief This function frees the components of a key pair. + * \param key The key pair to free. */ void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key ); /** - * \brief Copy the contents of point Q into P + * \brief This function copies the contents of point \p Q into + * point \p P. * - * \param P Destination point - * \param Q Source point + * \param P The destination point. + * \param Q The source point. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); /** - * \brief Copy the contents of a group object + * \brief This function copies the contents of group \p src into + * group \p dst. * - * \param dst Destination group - * \param src Source group + * \param dst The destination group. + * \param src The source group. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src ); /** - * \brief Set a point to zero + * \brief This function sets a point to zero. * - * \param pt Destination point + * \param pt The point to set. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt ); /** - * \brief Tell if a point is zero + * \brief This function checks if a point is zero. * - * \param pt Point to test + * \param pt The point to test. * - * \return 1 if point is zero, 0 otherwise + * \return \c 1 if the point is zero. + * \return \c 0 if the point is non-zero. */ int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt ); /** - * \brief Compare two points + * \brief This function compares two points. * - * \note This assumes the points are normalized. Otherwise, + * \note This assumes that the points are normalized. Otherwise, * they may compare as "not equal" even if they are. * - * \param P First point to compare - * \param Q Second point to compare + * \param P The first point to compare. + * \param Q The second point to compare. * - * \return 0 if the points are equal, - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise + * \return \c 0 if the points are equal. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal. */ int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); /** - * \brief Import a non-zero point from two ASCII strings + * \brief This function imports a non-zero point from two ASCII + * strings. * - * \param P Destination point - * \param radix Input numeric base - * \param x First affine coordinate as a null-terminated string - * \param y Second affine coordinate as a null-terminated string + * \param P The destination point. + * \param radix The numeric base of the input. + * \param x The first affine coordinate, as a null-terminated string. + * \param y The second affine coordinate, as a null-terminated string. * - * \return 0 if successful, or a MBEDTLS_ERR_MPI_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on failure. */ int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix, const char *x, const char *y ); /** - * \brief Export a point into unsigned binary data + * \brief This function exports a point into unsigned binary data. * - * \param grp Group to which the point should belong - * \param P Point to export - * \param format Point format, should be a MBEDTLS_ECP_PF_XXX macro - * \param olen Length of the actual output - * \param buf Output buffer - * \param buflen Length of the output buffer + * \param grp The group to which the point should belong. + * \param P The point to export. + * \param format The point format. Should be an \c MBEDTLS_ECP_PF_XXX macro. + * \param olen The length of the output. + * \param buf The output buffer. + * \param buflen The length of the output buffer. * - * \return 0 if successful, - * or MBEDTLS_ERR_ECP_BAD_INPUT_DATA - * or MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA + * or #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure. */ int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P, int format, size_t *olen, unsigned char *buf, size_t buflen ); /** - * \brief Import a point from unsigned binary data + * \brief This function imports a point from unsigned binary data. * - * \param grp Group to which the point should belong - * \param P Point to import - * \param buf Input buffer - * \param ilen Actual length of input + * \note This function does not check that the point actually + * belongs to the given group, see mbedtls_ecp_check_pubkey() + * for that. * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed, - * MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format + * \param grp The group to which the point should belong. + * \param P The point to import. + * \param buf The input buffer. + * \param ilen The length of the input. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format * is not implemented. * - * \note This function does NOT check that the point actually - * belongs to the given group, see mbedtls_ecp_check_pubkey() for - * that. */ int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P, const unsigned char *buf, size_t ilen ); /** - * \brief Import a point from a TLS ECPoint record + * \brief This function imports a point from a TLS ECPoint record. * - * \param grp ECP group used - * \param pt Destination point - * \param buf $(Start of input buffer) - * \param len Buffer length + * \note On function return, \p buf is updated to point to immediately + * after the ECPoint record. * - * \note buf is updated to point right after the ECPoint on exit + * \param grp The ECP group used. + * \param pt The destination point. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the buffer. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_XXX if initialization failed - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization failure. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. */ int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt, const unsigned char **buf, size_t len ); /** - * \brief Export a point as a TLS ECPoint record + * \brief This function exports a point as a TLS ECPoint record. * - * \param grp ECP group used - * \param pt Point to export - * \param format Export format - * \param olen length of data written - * \param buf Buffer to write to - * \param blen Buffer length + * \param grp The ECP group used. + * \param pt The point format to export to. The point format is an + * \c MBEDTLS_ECP_PF_XXX constant. + * \param format The export format. + * \param olen The length of the data written. + * \param buf The buffer to write to. + * \param blen The length of the buffer. * - * \return 0 if successful, - * or MBEDTLS_ERR_ECP_BAD_INPUT_DATA - * or MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA or + * #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure. */ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt, int format, size_t *olen, unsigned char *buf, size_t blen ); /** - * \brief Set a group using well-known domain parameters + * \brief This function sets a group using standardized domain parameters. * - * \param grp Destination group - * \param id Index in the list of well-known domain parameters + * \note The index should be a value of the NamedCurve enum, + * as defined in <em>RFC-4492: Elliptic Curve Cryptography + * (ECC) Cipher Suites for Transport Layer Security (TLS)</em>, + * usually in the form of an \c MBEDTLS_ECP_DP_XXX macro. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_XXX if initialization failed - * MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE for unkownn groups + * \param grp The destination group. + * \param id The identifier of the domain parameter set to load. * - * \note Index should be a value of RFC 4492's enum NamedCurve, - * usually in the form of a MBEDTLS_ECP_DP_XXX macro. + * \return \c 0 on success, + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization failure. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE for unkownn groups. + */ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id ); /** - * \brief Set a group from a TLS ECParameters record + * \brief This function sets a group from a TLS ECParameters record. * - * \param grp Destination group - * \param buf &(Start of input buffer) - * \param len Buffer length + * \note \p buf is updated to point right after the ECParameters record + * on exit. * - * \note buf is updated to point right after ECParameters on exit + * \param grp The destination group. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the buffer. * - * \return 0 if successful, - * MBEDTLS_ERR_MPI_XXX if initialization failed - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization failure. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. */ int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len ); /** - * \brief Write the TLS ECParameters record for a group + * \brief This function writes the TLS ECParameters record for a group. * - * \param grp ECP group used - * \param olen Number of bytes actually written - * \param buf Buffer to write to - * \param blen Buffer length + * \param grp The ECP group used. + * \param olen The number of Bytes written. + * \param buf The buffer to write to. + * \param blen The length of the buffer. * - * \return 0 if successful, - * or MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure. */ int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen, unsigned char *buf, size_t blen ); /** - * \brief Multiplication by an integer: R = m * P - * (Not thread-safe to use same group in multiple threads) + * \brief This function performs multiplication of a point by + * an integer: \p R = \p m * \p P. * - * \note In order to prevent timing attacks, this function - * executes the exact same sequence of (base field) - * operations for any valid m. It avoids any if-branch or - * array index depending on the value of m. + * It is not thread-safe to use same group in multiple threads. * - * \note If f_rng is not NULL, it is used to randomize intermediate - * results in order to prevent potential timing attacks - * targeting these results. It is recommended to always - * provide a non-NULL f_rng (the overhead is negligible). + * \note To prevent timing attacks, this function + * executes the exact same sequence of base-field + * operations for any valid \p m. It avoids any if-branch or + * array index depending on the value of \p m. * - * \param grp ECP group - * \param R Destination point - * \param m Integer by which to multiply - * \param P Point to multiply - * \param f_rng RNG function (see notes) - * \param p_rng RNG parameter + * \note If \p f_rng is not NULL, it is used to randomize + * intermediate results to prevent potential timing attacks + * targeting these results. We recommend always providing + * a non-NULL \p f_rng. The overhead is negligible. * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_INVALID_KEY if m is not a valid privkey - * or P is not a valid pubkey, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \param grp The ECP group. + * \param R The destination point. + * \param m The integer by which to multiply. + * \param P The point to multiply. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private + * key, or \p P is not a valid public key. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Multiplication and addition of two points by integers: - * R = m * P + n * Q - * (Not thread-safe to use same group in multiple threads) + * \brief This function performs multiplication and addition of two + * points by integers: \p R = \p m * \p P + \p n * \p Q + * + * It is not thread-safe to use same group in multiple threads. * - * \note In contrast to mbedtls_ecp_mul(), this function does not guarantee - * a constant execution flow and timing. + * \note In contrast to mbedtls_ecp_mul(), this function does not + * guarantee a constant execution flow and timing. * - * \param grp ECP group - * \param R Destination point - * \param m Integer by which to multiply P - * \param P Point to multiply by m - * \param n Integer by which to multiply Q - * \param Q Point to be multiplied by n + * \param grp The ECP group. + * \param R The destination point. + * \param m The integer by which to multiply \p P. + * \param P The point to multiply by \p m. + * \param n The integer by which to multiply \p Q. + * \param Q The point to be multiplied by \p n. * - * \return 0 if successful, - * MBEDTLS_ERR_ECP_INVALID_KEY if m or n is not a valid privkey - * or P or Q is not a valid pubkey, - * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not + * valid private keys, or \p P or \p Q are not valid public + * keys. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q ); /** - * \brief Check that a point is a valid public key on this curve + * \brief This function checks that a point is a valid public key + * on this curve. * - * \param grp Curve/group the point should belong to - * \param pt Point to check + * It only checks that the point is non-zero, has + * valid coordinates and lies on the curve. It does not verify + * that it is indeed a multiple of \p G. This additional + * check is computationally more expensive, is not required + * by standards, and should not be necessary if the group + * used has a small cofactor. In particular, it is useless for + * the NIST groups which all have a cofactor of 1. * - * \return 0 if point is a valid public key, - * MBEDTLS_ERR_ECP_INVALID_KEY otherwise. + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure, to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \note This function only checks the point is non-zero, has valid - * coordinates and lies on the curve, but not that it is - * indeed a multiple of G. This is additional check is more - * expensive, isn't required by standards, and shouldn't be - * necessary if the group used has a small cofactor. In - * particular, it is useless for the NIST groups which all - * have a cofactor of 1. + * \param grp The curve the point should lie on. + * \param pt The point to check. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 if the point is a valid public key. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY on failure. */ int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ); /** - * \brief Check that an mbedtls_mpi is a valid private key for this curve + * \brief This function checks that an \p mbedtls_mpi is a valid private + * key for this curve. * - * \param grp Group used - * \param d Integer to check + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \return 0 if point is a valid private key, - * MBEDTLS_ERR_ECP_INVALID_KEY otherwise. + * \param grp The group used. + * \param d The integer to check. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 if the point is a valid private key. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY on failure. */ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d ); /** - * \brief Generate a keypair with configurable base point + * \brief This function generates a keypair with a configurable base + * point. * - * \param grp ECP group - * \param G Chosen base point - * \param d Destination MPI (secret part) - * \param Q Destination point (public part) - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * \param grp The ECP group. + * \param G The chosen base point. + * \param d The destination MPI (secret part). + * \param Q The destination point (public part). + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. */ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, const mbedtls_ecp_point *G, @@ -619,57 +692,66 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, void *p_rng ); /** - * \brief Generate a keypair + * \brief This function generates an ECP keypair. * - * \param grp ECP group - * \param d Destination MPI (secret part) - * \param Q Destination point (public part) - * \param f_rng RNG function - * \param p_rng RNG parameter + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * \param grp The ECP group. + * \param d The destination MPI (secret part). + * \param Q The destination point (public part). + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \note Uses bare components rather than an mbedtls_ecp_keypair structure - * in order to ease use with other structures such as - * mbedtls_ecdh_context of mbedtls_ecdsa_context. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. */ int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Generate a keypair + * \brief This function generates an ECP key. * - * \param grp_id ECP group identifier - * \param key Destination keypair - * \param f_rng RNG function - * \param p_rng RNG parameter + * \param grp_id The ECP group identifier. + * \param key The destination key. + * \param f_rng The RNG function. + * \param p_rng The RNG context. * - * \return 0 if successful, - * or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. */ int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** - * \brief Check a public-private key pair + * \brief This function checks that the keypair objects + * \p pub and \p prv have the same group and the + * same public point, and that the private key in + * \p prv is consistent with the public key. * - * \param pub Keypair structure holding a public key - * \param prv Keypair structure holding a private (plus public) key + * \param pub The keypair structure holding the public key. + * If it contains a private key, that part is ignored. + * \param prv The keypair structure holding the full keypair. * - * \return 0 if successful (keys are valid and match), or - * MBEDTLS_ERR_ECP_BAD_INPUT_DATA, or - * a MBEDTLS_ERR_ECP_XXX or MBEDTLS_ERR_MPI_XXX code. + * \return \c 0 on success, meaning that the keys are valid and match. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match. + * \return An \c MBEDTLS_ERR_ECP_XXX or an \c MBEDTLS_ERR_MPI_XXX + * error code on calculation failure. */ int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv ); #if defined(MBEDTLS_SELF_TEST) /** - * \brief Checkup routine + * \brief The ECP checkup routine. * - * \return 0 if successful, or 1 if a test failed + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_ecp_self_test( int verbose ); @@ -679,8 +761,4 @@ int mbedtls_ecp_self_test( int verbose ); } #endif -#else /* MBEDTLS_ECP_ALT */ -#include "ecp_alt.h" -#endif /* MBEDTLS_ECP_ALT */ - #endif /* ecp.h */ diff --git a/thirdparty/mbedtls/include/mbedtls/ecp_internal.h b/thirdparty/mbedtls/include/mbedtls/ecp_internal.h index 8a6d517ed0..18040697ad 100644 --- a/thirdparty/mbedtls/include/mbedtls/ecp_internal.h +++ b/thirdparty/mbedtls/include/mbedtls/ecp_internal.h @@ -48,7 +48,7 @@ * [6] Digital Signature Standard (DSS), FIPS 186-4. * <http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf> * - * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer + * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer * Security (TLS), RFC 4492. * <https://tools.ietf.org/search/rfc4492> * diff --git a/thirdparty/mbedtls/include/mbedtls/entropy.h b/thirdparty/mbedtls/include/mbedtls/entropy.h index fcb4d02557..a5cb05a584 100644 --- a/thirdparty/mbedtls/include/mbedtls/entropy.h +++ b/thirdparty/mbedtls/include/mbedtls/entropy.h @@ -166,7 +166,7 @@ void mbedtls_entropy_free( mbedtls_entropy_context *ctx ); * \param threshold Minimum required from source before entropy is released * ( with mbedtls_entropy_func() ) (in bytes) * \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or - * MBEDTSL_ENTROPY_SOURCE_WEAK. + * MBEDTLS_ENTROPY_SOURCE_WEAK. * At least one strong source needs to be added. * Weaker sources (such as the cycle counter) can be used as * a complement. diff --git a/thirdparty/mbedtls/include/mbedtls/error.h b/thirdparty/mbedtls/include/mbedtls/error.h index 8b4d3a8755..a17f8d8ace 100644 --- a/thirdparty/mbedtls/include/mbedtls/error.h +++ b/thirdparty/mbedtls/include/mbedtls/error.h @@ -53,7 +53,7 @@ * GCM 3 0x0012-0x0014 0x0013-0x0013 * BLOWFISH 3 0x0016-0x0018 0x0017-0x0017 * THREADING 3 0x001A-0x001E - * AES 4 0x0020-0x0022 0x0023-0x0025 + * AES 5 0x0020-0x0022 0x0021-0x0025 * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027 * XTEA 2 0x0028-0x0028 0x0029-0x0029 * BASE64 2 0x002A-0x002C @@ -63,6 +63,7 @@ * CTR_DBRG 4 0x0034-0x003A * ENTROPY 3 0x003C-0x0040 0x003D-0x003F * NET 11 0x0042-0x0052 0x0043-0x0045 + * ARIA 4 0x0058-0x005E * ASN1 7 0x0060-0x006C * CMAC 1 0x007A-0x007A * PBKDF2 1 0x007C-0x007C diff --git a/thirdparty/mbedtls/include/mbedtls/gcm.h b/thirdparty/mbedtls/include/mbedtls/gcm.h index 1e5a507a26..bec5577142 100644 --- a/thirdparty/mbedtls/include/mbedtls/gcm.h +++ b/thirdparty/mbedtls/include/mbedtls/gcm.h @@ -1,9 +1,11 @@ /** * \file gcm.h * - * \brief Galois/Counter Mode (GCM) for 128-bit block ciphers, as defined - * in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation - * (GCM), Natl. Inst. Stand. Technol.</em> + * \brief This file contains GCM definitions and functions. + * + * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined + * in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation + * (GCM), Natl. Inst. Stand. Technol.</em> * * For more information on GCM, see <em>NIST SP 800-38D: Recommendation for * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>. @@ -42,12 +44,12 @@ #define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */ #define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */ -#if !defined(MBEDTLS_GCM_ALT) - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_GCM_ALT) + /** * \brief The GCM context structure. */ @@ -66,6 +68,10 @@ typedef struct { } mbedtls_gcm_context; +#else /* !MBEDTLS_GCM_ALT */ +#include "gcm_alt.h" +#endif /* !MBEDTLS_GCM_ALT */ + /** * \brief This function initializes the specified GCM context, * to make references valid, and prepares the context @@ -91,7 +97,8 @@ void mbedtls_gcm_init( mbedtls_gcm_context *ctx ); * <li>192 bits</li> * <li>256 bits</li></ul> * - * \return \c 0 on success, or a cipher specific error code. + * \return \c 0 on success. + * \return A cipher-specific error code on failure. */ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, mbedtls_cipher_id_t cipher, @@ -101,15 +108,16 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, /** * \brief This function performs GCM encryption or decryption of a buffer. * - * \note For encryption, the output buffer can be the same as the input buffer. - * For decryption, the output buffer cannot be the same as input buffer. - * If the buffers overlap, the output buffer must trail at least 8 Bytes - * behind the input buffer. + * \note For encryption, the output buffer can be the same as the + * input buffer. For decryption, the output buffer cannot be + * the same as input buffer. If the buffers overlap, the output + * buffer must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context to use for encryption or decryption. * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or * #MBEDTLS_GCM_DECRYPT. - * \param length The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish(). + * \param length The length of the input data. This must be a multiple of + * 16 except in the last call before mbedtls_gcm_finish(). * \param iv The initialization vector. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. @@ -137,12 +145,13 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, * \brief This function performs a GCM authenticated decryption of a * buffer. * - * \note For decryption, the output buffer cannot be the same as input buffer. - * If the buffers overlap, the output buffer must trail at least 8 Bytes - * behind the input buffer. + * \note For decryption, the output buffer cannot be the same as + * input buffer. If the buffers overlap, the output buffer + * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. - * \param length The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish(). + * \param length The length of the input data. This must be a multiple + * of 16 except in the last call before mbedtls_gcm_finish(). * \param iv The initialization vector. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. @@ -152,8 +161,8 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, * \param input The buffer holding the input data. * \param output The buffer for holding the output data. * - * \return 0 if successful and authenticated, or - * #MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match. + * \return 0 if successful and authenticated. + * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. */ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, @@ -175,10 +184,12 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, * #MBEDTLS_GCM_DECRYPT. * \param iv The initialization vector. * \param iv_len The length of the IV. - * \param add The buffer holding the additional data, or NULL if \p add_len is 0. - * \param add_len The length of the additional data. If 0, \p add is NULL. + * \param add The buffer holding the additional data, or NULL + * if \p add_len is 0. + * \param add_len The length of the additional data. If 0, + * \p add is NULL. * - * \return \c 0 on success. + * \return \c 0 on success. */ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, int mode, @@ -195,16 +206,18 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, * Bytes. Only the last call before calling * mbedtls_gcm_finish() can be less than 16 Bytes. * - * \note For decryption, the output buffer cannot be the same as input buffer. - * If the buffers overlap, the output buffer must trail at least 8 Bytes - * behind the input buffer. + * \note For decryption, the output buffer cannot be the same as + * input buffer. If the buffers overlap, the output buffer + * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. - * \param length The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish(). + * \param length The length of the input data. This must be a multiple of + * 16 except in the last call before mbedtls_gcm_finish(). * \param input The buffer holding the input data. * \param output The buffer for holding the output data. * - * \return \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_update( mbedtls_gcm_context *ctx, size_t length, @@ -222,7 +235,8 @@ int mbedtls_gcm_update( mbedtls_gcm_context *ctx, * \param tag The buffer for holding the tag. * \param tag_len The length of the tag to generate. Must be at least four. * - * \return \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, unsigned char *tag, @@ -236,22 +250,11 @@ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, */ void mbedtls_gcm_free( mbedtls_gcm_context *ctx ); -#ifdef __cplusplus -} -#endif - -#else /* !MBEDTLS_GCM_ALT */ -#include "gcm_alt.h" -#endif /* !MBEDTLS_GCM_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief The GCM checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_gcm_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/md.h b/thirdparty/mbedtls/include/mbedtls/md.h index 06538c3827..6b6f5c53dd 100644 --- a/thirdparty/mbedtls/include/mbedtls/md.h +++ b/thirdparty/mbedtls/include/mbedtls/md.h @@ -1,7 +1,7 @@ /** * \file md.h * - * \brief The generic message-digest wrapper. + * \brief This file contains the generic message-digest wrapper. * * \author Adriaan de Jong <dejong@fox-it.com> */ @@ -46,7 +46,7 @@ extern "C" { #endif /** - * \brief Enumeration of supported message digests + * \brief Supported message digests. * * \warning MD2, MD4, MD5 and SHA-1 are considered weak message digests and * their use constitutes a security risk. We recommend considering @@ -54,16 +54,16 @@ extern "C" { * */ typedef enum { - MBEDTLS_MD_NONE=0, - MBEDTLS_MD_MD2, - MBEDTLS_MD_MD4, - MBEDTLS_MD_MD5, - MBEDTLS_MD_SHA1, - MBEDTLS_MD_SHA224, - MBEDTLS_MD_SHA256, - MBEDTLS_MD_SHA384, - MBEDTLS_MD_SHA512, - MBEDTLS_MD_RIPEMD160, + MBEDTLS_MD_NONE=0, /**< None. */ + MBEDTLS_MD_MD2, /**< The MD2 message digest. */ + MBEDTLS_MD_MD4, /**< The MD4 message digest. */ + MBEDTLS_MD_MD5, /**< The MD5 message digest. */ + MBEDTLS_MD_SHA1, /**< The SHA-1 message digest. */ + MBEDTLS_MD_SHA224, /**< The SHA-224 message digest. */ + MBEDTLS_MD_SHA256, /**< The SHA-256 message digest. */ + MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */ + MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */ + MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */ } mbedtls_md_type_t; #if defined(MBEDTLS_SHA512_C) @@ -108,8 +108,8 @@ const int *mbedtls_md_list( void ); * * \param md_name The name of the digest to search for. * - * \return The message-digest information associated with \p md_name, - * or NULL if not found. + * \return The message-digest information associated with \p md_name. + * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name ); @@ -119,8 +119,8 @@ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name ); * * \param md_type The type of digest to search for. * - * \return The message-digest information associated with \p md_type, - * or NULL if not found. + * \return The message-digest information associated with \p md_type. + * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type ); @@ -168,9 +168,10 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx ); * \param md_info The information structure of the message-digest algorithm * to use. * - * \returns \c 0 on success, - * #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure, - * #MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED; #undef MBEDTLS_DEPRECATED @@ -187,12 +188,13 @@ int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_ * \param ctx The context to set up. * \param md_info The information structure of the message-digest algorithm * to use. - * \param hmac <ul><li>0: HMAC is not used. Saves some memory.</li> - * <li>non-zero: HMAC is used with this context.</li></ul> + * \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory), + * or non-zero: HMAC is used with this context. * - * \returns \c 0 on success, - * #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure, or - * #MBEDTLS_ERR_MD_ALLOC_FAILED on memory allocation failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac ); @@ -212,8 +214,8 @@ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_inf * \param dst The destination context. * \param src The context to be cloned. * - * \return \c 0 on success, - * #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure. */ int mbedtls_md_clone( mbedtls_md_context_t *dst, const mbedtls_md_context_t *src ); @@ -260,8 +262,9 @@ const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info ); * * \param ctx The generic message-digest context. * - * \returns \c 0 on success, #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_starts( mbedtls_md_context_t *ctx ); @@ -277,8 +280,9 @@ int mbedtls_md_starts( mbedtls_md_context_t *ctx ); * \param input The buffer holding the input data. * \param ilen The length of the input data. * - * \returns \c 0 on success, #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); @@ -296,8 +300,9 @@ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, si * \param ctx The generic message-digest context. * \param output The buffer for the generic message-digest checksum result. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ); @@ -315,8 +320,9 @@ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ); * \param ilen The length of the input data. * \param output The generic message-digest checksum result. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen, unsigned char *output ); @@ -334,9 +340,10 @@ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, si * \param path The input file name. * \param output The generic message-digest checksum result. * - * \return \c 0 on success, - * #MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed, or - * #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing + * the file pointed by \p path. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL. */ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output ); @@ -356,8 +363,9 @@ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, * \param key The HMAC secret key. * \param keylen The length of the HMAC key in Bytes. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen ); @@ -377,8 +385,9 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, * \param input The buffer holding the input data. * \param ilen The length of the input data. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); @@ -397,8 +406,9 @@ int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *inpu * context. * \param output The generic HMAC checksum result. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output); @@ -413,8 +423,9 @@ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output); * \param ctx The message digest context containing an embedded HMAC * context. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx ); @@ -436,8 +447,9 @@ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx ); * \param ilen The length of the input data. * \param output The generic HMAC result. * - * \returns \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if - * parameter verification fails. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. */ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen, const unsigned char *input, size_t ilen, diff --git a/thirdparty/mbedtls/include/mbedtls/md2.h b/thirdparty/mbedtls/include/mbedtls/md2.h index 0fd8b5afcc..08e75b247b 100644 --- a/thirdparty/mbedtls/include/mbedtls/md2.h +++ b/thirdparty/mbedtls/include/mbedtls/md2.h @@ -39,14 +39,14 @@ #define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED -0x002B /**< MD2 hardware accelerator failed */ -#if !defined(MBEDTLS_MD2_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_MD2_ALT) +// Regular implementation +// + /** * \brief MD2 context structure * @@ -64,6 +64,10 @@ typedef struct } mbedtls_md2_context; +#else /* MBEDTLS_MD2_ALT */ +#include "md2_alt.h" +#endif /* MBEDTLS_MD2_ALT */ + /** * \brief Initialize MD2 context * @@ -235,18 +239,6 @@ MBEDTLS_DEPRECATED void mbedtls_md2_process( mbedtls_md2_context *ctx ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_MD2_ALT */ -#include "md2_alt.h" -#endif /* MBEDTLS_MD2_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Output = MD2( input buffer ) * diff --git a/thirdparty/mbedtls/include/mbedtls/md4.h b/thirdparty/mbedtls/include/mbedtls/md4.h index 23fa95e46a..8ee4e5cabf 100644 --- a/thirdparty/mbedtls/include/mbedtls/md4.h +++ b/thirdparty/mbedtls/include/mbedtls/md4.h @@ -40,14 +40,14 @@ #define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED -0x002D /**< MD4 hardware accelerator failed */ -#if !defined(MBEDTLS_MD4_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_MD4_ALT) +// Regular implementation +// + /** * \brief MD4 context structure * @@ -64,6 +64,10 @@ typedef struct } mbedtls_md4_context; +#else /* MBEDTLS_MD4_ALT */ +#include "md4_alt.h" +#endif /* MBEDTLS_MD4_ALT */ + /** * \brief Initialize MD4 context * @@ -238,18 +242,6 @@ MBEDTLS_DEPRECATED void mbedtls_md4_process( mbedtls_md4_context *ctx, #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_MD4_ALT */ -#include "md4_alt.h" -#endif /* MBEDTLS_MD4_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Output = MD4( input buffer ) * diff --git a/thirdparty/mbedtls/include/mbedtls/md5.h b/thirdparty/mbedtls/include/mbedtls/md5.h index 06ea4c5d44..43ead4b747 100644 --- a/thirdparty/mbedtls/include/mbedtls/md5.h +++ b/thirdparty/mbedtls/include/mbedtls/md5.h @@ -39,14 +39,14 @@ #define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */ -#if !defined(MBEDTLS_MD5_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_MD5_ALT) +// Regular implementation +// + /** * \brief MD5 context structure * @@ -63,6 +63,10 @@ typedef struct } mbedtls_md5_context; +#else /* MBEDTLS_MD5_ALT */ +#include "md5_alt.h" +#endif /* MBEDTLS_MD5_ALT */ + /** * \brief Initialize MD5 context * @@ -238,18 +242,6 @@ MBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx, #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_MD5_ALT */ -#include "md5_alt.h" -#endif /* MBEDTLS_MD5_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Output = MD5( input buffer ) * diff --git a/thirdparty/mbedtls/include/mbedtls/net_sockets.h b/thirdparty/mbedtls/include/mbedtls/net_sockets.h index 54e612cc5e..0f9b31ebcb 100644 --- a/thirdparty/mbedtls/include/mbedtls/net_sockets.h +++ b/thirdparty/mbedtls/include/mbedtls/net_sockets.h @@ -46,12 +46,17 @@ #define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */ #define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */ #define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */ +#define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /**< Polling the net context failed. */ +#define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /**< Input invalid. */ #define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */ #define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */ #define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */ +#define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */ +#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */ + #ifdef __cplusplus extern "C" { #endif @@ -118,9 +123,10 @@ int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char * * \param bind_ctx Relevant socket * \param client_ctx Will contain the connected client socket - * \param client_ip Will contain the client IP address + * \param client_ip Will contain the client IP address, can be NULL * \param buf_size Size of the client_ip buffer - * \param ip_len Will receive the size of the client IP written + * \param ip_len Will receive the size of the client IP written, + * can be NULL if client_ip is null * * \return 0 if successful, or * MBEDTLS_ERR_NET_ACCEPT_FAILED, or @@ -133,6 +139,29 @@ int mbedtls_net_accept( mbedtls_net_context *bind_ctx, void *client_ip, size_t buf_size, size_t *ip_len ); /** + * \brief Check and wait for the context to be ready for read/write + * + * \param ctx Socket to check + * \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and + * MBEDTLS_NET_POLL_WRITE specifying the events + * to wait for: + * - If MBEDTLS_NET_POLL_READ is set, the function + * will return as soon as the net context is available + * for reading. + * - If MBEDTLS_NET_POLL_WRITE is set, the function + * will return as soon as the net context is available + * for writing. + * \param timeout Maximal amount of time to wait before returning, + * in milliseconds. If \c timeout is zero, the + * function returns immediately. If \c timeout is + * -1u, the function blocks potentially indefinitely. + * + * \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE + * on success or timeout, or a negative return code otherwise. + */ +int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout ); + +/** * \brief Set the socket blocking * * \param ctx Socket to set diff --git a/thirdparty/mbedtls/include/mbedtls/pk.h b/thirdparty/mbedtls/include/mbedtls/pk.h index 1059bdaa5b..ee06b2fd20 100644 --- a/thirdparty/mbedtls/include/mbedtls/pk.h +++ b/thirdparty/mbedtls/include/mbedtls/pk.h @@ -63,7 +63,7 @@ #define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80 /**< The algorithm tag or value is invalid. */ #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00 /**< Elliptic curve is unsupported (only NIST curves are supported). */ #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980 /**< Unavailable feature, e.g. RSA disabled for RSA key. */ -#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The signature is valid but its length is less than expected. */ +#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The buffer contains a valid signature followed by more data. */ #define MBEDTLS_ERR_PK_HW_ACCEL_FAILED -0x3880 /**< PK hardware accelerator failed. */ #ifdef __cplusplus @@ -269,8 +269,8 @@ int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type ); * \param sig_len Signature length * * \return 0 on success (signature is valid), - * MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is - * valid but its actual length is less than sig_len, + * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid + * signature in sig but its length is less than \p siglen, * or a specific error code. * * \note For RSA keys, the default padding type is PKCS#1 v1.5. @@ -300,10 +300,10 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, * \param sig_len Signature length * * \return 0 on success (signature is valid), - * MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be + * #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be * used for this type of signatures, - * MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is - * valid but its actual length is less than sig_len, + * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid + * signature in sig but its length is less than \p siglen, * or a specific error code. * * \note If hash_len is 0, then the length associated with md_alg diff --git a/thirdparty/mbedtls/include/mbedtls/platform.h b/thirdparty/mbedtls/include/mbedtls/platform.h index ed10775848..bba770911e 100644 --- a/thirdparty/mbedtls/include/mbedtls/platform.h +++ b/thirdparty/mbedtls/include/mbedtls/platform.h @@ -1,7 +1,16 @@ /** * \file platform.h * - * \brief The Mbed TLS platform abstraction layer. + * \brief This file contains the definitions and functions of the + * Mbed TLS platform abstraction layer. + * + * The platform abstraction layer removes the need for the library + * to directly link to standard C library functions or operating + * system services, making the library easier to port and embed. + * Application developers and users of the library can provide their own + * implementations of these functions, or implementations specific to + * their platform, which can be statically linked to the library or + * dynamically configured at runtime. */ /* * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -102,7 +111,7 @@ extern "C" { /* \} name SECTION: Module settings */ /* - * The function pointers for calloc and free + * The function pointers for calloc and free. */ #if defined(MBEDTLS_PLATFORM_MEMORY) #if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \ @@ -116,7 +125,8 @@ extern void * (*mbedtls_calloc)( size_t n, size_t size ); extern void (*mbedtls_free)( void *ptr ); /** - * \brief This function allows configuring custom memory-management functions. + * \brief This function dynamically sets the memory-management + * functions used by the library, during runtime. * * \param calloc_func The \c calloc function implementation. * \param free_func The \c free function implementation. @@ -140,7 +150,9 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... ); /** - * \brief This function allows configuring a custom \p fprintf function pointer. + * \brief This function dynamically configures the fprintf + * function that is called when the + * mbedtls_fprintf() function is invoked by the library. * * \param fprintf_func The \c fprintf function implementation. * @@ -163,8 +175,9 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char extern int (*mbedtls_printf)( const char *format, ... ); /** - * \brief This function allows configuring a custom \c printf function - * pointer. + * \brief This function dynamically configures the snprintf + * function that is called when the mbedtls_snprintf() + * function is invoked by the library. * * \param printf_func The \c printf function implementation. * @@ -197,12 +210,12 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... ); extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... ); /** - * \brief This function allows configuring a custom \c snprintf function - * pointer. + * \brief This function allows configuring a custom + * \c snprintf function pointer. * * \param snprintf_func The \c snprintf function implementation. * - * \return \c 0 on success. + * \return \c 0 on success. */ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, const char * format, ... ) ); @@ -210,7 +223,7 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) #define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO #else -#define mbedtls_snprintf snprintf +#define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ @@ -221,12 +234,13 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, extern void (*mbedtls_exit)( int status ); /** - * \brief This function allows configuring a custom \c exit function - * pointer. + * \brief This function dynamically configures the exit + * function that is called when the mbedtls_exit() + * function is invoked by the library. * * \param exit_func The \c exit function implementation. * - * \return \c 0 on success. + * \return \c 0 on success. */ int mbedtls_platform_set_exit( void (*exit_func)( int status ) ); #else @@ -302,7 +316,7 @@ int mbedtls_platform_set_nv_seed( * setup or teardown operations. */ typedef struct { - char dummy; /**< Placeholder member, as empty structs are not portable. */ + char dummy; /**< A placeholder member, as empty structs are not portable. */ } mbedtls_platform_context; @@ -311,33 +325,34 @@ mbedtls_platform_context; #endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */ /** - * \brief This function performs any platform initialization operations. - * - * \param ctx The Mbed TLS context. + * \brief This function performs any platform-specific initialization + * operations. * - * \return \c 0 on success. + * \note This function should be called before any other library functions. * - * \note This function is intended to allow platform-specific initialization, - * and should be called before any other library functions. Its - * implementation is platform-specific, and unless + * Its implementation is platform-specific, and unless * platform-specific code is provided, it does nothing. * - * Its use and whether it is necessary to call it is dependent on the - * platform. + * \note The usage and necessity of this function is dependent on the platform. + * + * \param ctx The platform context. + * + * \return \c 0 on success. */ int mbedtls_platform_setup( mbedtls_platform_context *ctx ); /** * \brief This function performs any platform teardown operations. * - * \param ctx The Mbed TLS context. - * * \note This function should be called after every other Mbed TLS module * has been correctly freed using the appropriate free function. + * * Its implementation is platform-specific, and unless * platform-specific code is provided, it does nothing. * - * Its use and whether it is necessary to call it is dependent on the - * platform. + * \note The usage and necessity of this function is dependent on the platform. + * + * \param ctx The platform context. + * */ void mbedtls_platform_teardown( mbedtls_platform_context *ctx ); diff --git a/thirdparty/mbedtls/include/mbedtls/platform_util.h b/thirdparty/mbedtls/include/mbedtls/platform_util.h new file mode 100644 index 0000000000..84f0732eeb --- /dev/null +++ b/thirdparty/mbedtls/include/mbedtls/platform_util.h @@ -0,0 +1,62 @@ +/** + * \file platform_util.h + * + * \brief Common and shared functions used by multiple modules in the Mbed TLS + * library. + */ +/* + * Copyright (C) 2018, Arm Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * 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. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PLATFORM_UTIL_H +#define MBEDTLS_PLATFORM_UTIL_H + +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Securely zeroize a buffer + * + * The function is meant to wipe the data contained in a buffer so + * that it can no longer be recovered even if the program memory + * is later compromised. Call this function on sensitive data + * stored on the stack before returning from a function, and on + * sensitive data stored on the heap before freeing the heap + * object. + * + * It is extremely difficult to guarantee that calls to + * mbedtls_platform_zeroize() are not removed by aggressive + * compiler optimizations in a portable way. For this reason, Mbed + * TLS provides the configuration option + * MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure + * mbedtls_platform_zeroize() to use a suitable implementation for + * their platform and needs + * + * \param buf Buffer to be zeroized + * \param len Length of the buffer in bytes + * + */ +void mbedtls_platform_zeroize( void *buf, size_t len ); + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_PLATFORM_UTIL_H */ diff --git a/thirdparty/mbedtls/include/mbedtls/ripemd160.h b/thirdparty/mbedtls/include/mbedtls/ripemd160.h index 3a8b50a621..a0dac0c360 100644 --- a/thirdparty/mbedtls/include/mbedtls/ripemd160.h +++ b/thirdparty/mbedtls/include/mbedtls/ripemd160.h @@ -35,14 +35,14 @@ #define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED -0x0031 /**< RIPEMD160 hardware accelerator failed */ -#if !defined(MBEDTLS_RIPEMD160_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_RIPEMD160_ALT) +// Regular implementation +// + /** * \brief RIPEMD-160 context structure */ @@ -54,6 +54,10 @@ typedef struct } mbedtls_ripemd160_context; +#else /* MBEDTLS_RIPEMD160_ALT */ +#include "ripemd160.h" +#endif /* MBEDTLS_RIPEMD160_ALT */ + /** * \brief Initialize RIPEMD-160 context * @@ -178,18 +182,6 @@ MBEDTLS_DEPRECATED void mbedtls_ripemd160_process( #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_RIPEMD160_ALT */ -#include "ripemd160_alt.h" -#endif /* MBEDTLS_RIPEMD160_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Output = RIPEMD-160( input buffer ) * diff --git a/thirdparty/mbedtls/include/mbedtls/rsa.h b/thirdparty/mbedtls/include/mbedtls/rsa.h index 5548f3c127..19eb2ee74c 100644 --- a/thirdparty/mbedtls/include/mbedtls/rsa.h +++ b/thirdparty/mbedtls/include/mbedtls/rsa.h @@ -1,11 +1,12 @@ /** * \file rsa.h * - * \brief The RSA public-key cryptosystem. + * \brief This file provides an API for the RSA public-key cryptosystem. * - * For more information, see <em>Public-Key Cryptography Standards (PKCS) - * #1 v1.5: RSA Encryption</em> and <em>Public-Key Cryptography Standards - * (PKCS) #1 v2.1: RSA Cryptography Specifications</em>. + * The RSA public-key cryptosystem is defined in <em>Public-Key + * Cryptography Standards (PKCS) #1 v1.5: RSA Encryption</em> + * and <em>Public-Key Cryptography Standards (PKCS) #1 v2.1: + * RSA Cryptography Specifications</em>. * */ /* @@ -63,8 +64,8 @@ #define MBEDTLS_RSA_PUBLIC 0 /**< Request private key operation. */ #define MBEDTLS_RSA_PRIVATE 1 /**< Request public key operation. */ -#define MBEDTLS_RSA_PKCS_V15 0 /**< Use PKCS-1 v1.5 encoding. */ -#define MBEDTLS_RSA_PKCS_V21 1 /**< Use PKCS-1 v2.1 encoding. */ +#define MBEDTLS_RSA_PKCS_V15 0 /**< Use PKCS#1 v1.5 encoding. */ +#define MBEDTLS_RSA_PKCS_V21 1 /**< Use PKCS#1 v2.1 encoding. */ #define MBEDTLS_RSA_SIGN 1 /**< Identifier for RSA signature operations. */ #define MBEDTLS_RSA_CRYPT 2 /**< Identifier for RSA encryption and decryption operations. */ @@ -76,14 +77,14 @@ * eg for alternative (PKCS#11) RSA implemenations in the PK layers. */ -#if !defined(MBEDTLS_RSA_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_RSA_ALT) +// Regular implementation +// + /** * \brief The RSA context structure. * @@ -96,24 +97,24 @@ typedef struct int ver; /*!< Always 0.*/ size_t len; /*!< The size of \p N in Bytes. */ - mbedtls_mpi N; /*!< The public modulus. */ - mbedtls_mpi E; /*!< The public exponent. */ + mbedtls_mpi N; /*!< The public modulus. */ + mbedtls_mpi E; /*!< The public exponent. */ - mbedtls_mpi D; /*!< The private exponent. */ - mbedtls_mpi P; /*!< The first prime factor. */ - mbedtls_mpi Q; /*!< The second prime factor. */ + mbedtls_mpi D; /*!< The private exponent. */ + mbedtls_mpi P; /*!< The first prime factor. */ + mbedtls_mpi Q; /*!< The second prime factor. */ - mbedtls_mpi DP; /*!< \p D % (P - 1) */ - mbedtls_mpi DQ; /*!< \p D % (Q - 1) */ - mbedtls_mpi QP; /*!< 1 / (Q % P) */ + mbedtls_mpi DP; /*!< <code>D % (P - 1)</code>. */ + mbedtls_mpi DQ; /*!< <code>D % (Q - 1)</code>. */ + mbedtls_mpi QP; /*!< <code>1 / (Q % P)</code>. */ - mbedtls_mpi RN; /*!< cached R^2 mod \p N */ + mbedtls_mpi RN; /*!< cached <code>R^2 mod N</code>. */ - mbedtls_mpi RP; /*!< cached R^2 mod \p P */ - mbedtls_mpi RQ; /*!< cached R^2 mod \p Q */ + mbedtls_mpi RP; /*!< cached <code>R^2 mod P</code>. */ + mbedtls_mpi RQ; /*!< cached <code>R^2 mod Q</code>. */ - mbedtls_mpi Vi; /*!< The cached blinding value. */ - mbedtls_mpi Vf; /*!< The cached un-blinding value. */ + mbedtls_mpi Vi; /*!< The cached blinding value. */ + mbedtls_mpi Vf; /*!< The cached un-blinding value. */ int padding; /*!< Selects padding mode: #MBEDTLS_RSA_PKCS_V15 for 1.5 padding and @@ -128,18 +129,16 @@ typedef struct } mbedtls_rsa_context; +#else /* MBEDTLS_RSA_ALT */ +#include "rsa_alt.h" +#endif /* MBEDTLS_RSA_ALT */ + /** * \brief This function initializes an RSA context. * * \note Set padding to #MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP * encryption scheme and the RSASSA-PSS signature scheme. * - * \param ctx The RSA context to initialize. - * \param padding Selects padding mode: #MBEDTLS_RSA_PKCS_V15 or - * #MBEDTLS_RSA_PKCS_V21. - * \param hash_id The hash identifier of #mbedtls_md_type_t type, if - * \p padding is #MBEDTLS_RSA_PKCS_V21. - * * \note The \p hash_id parameter is ignored when using * #MBEDTLS_RSA_PKCS_V15 padding. * @@ -153,6 +152,12 @@ mbedtls_rsa_context; * encryption. For PSS signatures, it is always used for * making signatures, but can be overriden for verifying them. * If set to #MBEDTLS_MD_NONE, it is always overriden. + * + * \param ctx The RSA context to initialize. + * \param padding Selects padding mode: #MBEDTLS_RSA_PKCS_V15 or + * #MBEDTLS_RSA_PKCS_V21. + * \param hash_id The hash identifier of #mbedtls_md_type_t type, if + * \p padding is #MBEDTLS_RSA_PKCS_V21. */ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, int padding, @@ -162,13 +167,6 @@ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, * \brief This function imports a set of core parameters into an * RSA context. * - * \param ctx The initialized RSA context to store the parameters in. - * \param N The RSA modulus, or NULL. - * \param P The first prime factor of \p N, or NULL. - * \param Q The second prime factor of \p N, or NULL. - * \param D The private exponent, or NULL. - * \param E The public exponent, or NULL. - * * \note This function can be called multiple times for successive * imports, if the parameters are not simultaneously present. * @@ -184,7 +182,15 @@ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, * \note The imported parameters are copied and need not be preserved * for the lifetime of the RSA context being set up. * - * \return \c 0 on success, or a non-zero error code on failure. + * \param ctx The initialized RSA context to store the parameters in. + * \param N The RSA modulus, or NULL. + * \param P The first prime factor of \p N, or NULL. + * \param Q The second prime factor of \p N, or NULL. + * \param D The private exponent, or NULL. + * \param E The public exponent, or NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. */ int mbedtls_rsa_import( mbedtls_rsa_context *ctx, const mbedtls_mpi *N, @@ -195,18 +201,6 @@ int mbedtls_rsa_import( mbedtls_rsa_context *ctx, * \brief This function imports core RSA parameters, in raw big-endian * binary format, into an RSA context. * - * \param ctx The initialized RSA context to store the parameters in. - * \param N The RSA modulus, or NULL. - * \param N_len The Byte length of \p N, ignored if \p N == NULL. - * \param P The first prime factor of \p N, or NULL. - * \param P_len The Byte length of \p P, ignored if \p P == NULL. - * \param Q The second prime factor of \p N, or NULL. - * \param Q_len The Byte length of \p Q, ignored if \p Q == NULL. - * \param D The private exponent, or NULL. - * \param D_len The Byte length of \p D, ignored if \p D == NULL. - * \param E The public exponent, or NULL. - * \param E_len The Byte length of \p E, ignored if \p E == NULL. - * * \note This function can be called multiple times for successive * imports, if the parameters are not simultaneously present. * @@ -222,7 +216,20 @@ int mbedtls_rsa_import( mbedtls_rsa_context *ctx, * \note The imported parameters are copied and need not be preserved * for the lifetime of the RSA context being set up. * - * \return \c 0 on success, or a non-zero error code on failure. + * \param ctx The initialized RSA context to store the parameters in. + * \param N The RSA modulus, or NULL. + * \param N_len The Byte length of \p N, ignored if \p N == NULL. + * \param P The first prime factor of \p N, or NULL. + * \param P_len The Byte length of \p P, ignored if \p P == NULL. + * \param Q The second prime factor of \p N, or NULL. + * \param Q_len The Byte length of \p Q, ignored if \p Q == NULL. + * \param D The private exponent, or NULL. + * \param D_len The Byte length of \p D, ignored if \p D == NULL. + * \param E The public exponent, or NULL. + * \param E_len The Byte length of \p E, ignored if \p E == NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. */ int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, unsigned char const *N, size_t N_len, @@ -250,17 +257,18 @@ int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, * the RSA context can be used for RSA operations without * the risk of failure or crash. * - * \param ctx The initialized RSA context holding imported parameters. - * - * \return \c 0 on success, or #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the - * attempted derivations failed. - * * \warning This function need not perform consistency checks * for the imported parameters. In particular, parameters that * are not needed by the implementation might be silently * discarded and left unchecked. To check the consistency * of the key material, see mbedtls_rsa_check_privkey(). * + * \param ctx The initialized RSA context holding imported parameters. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted derivations + * failed. + * */ int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); @@ -292,11 +300,11 @@ int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); * \param D The MPI to hold the private exponent, or NULL. * \param E The MPI to hold the public exponent, or NULL. * - * \return \c 0 on success, - * #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the * requested parameters cannot be done due to missing - * functionality or because of security policies, - * or a non-zero return code on any other failure. + * functionality or because of security policies. + * \return A non-zero return code on any other failure. * */ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, @@ -324,6 +332,9 @@ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, * If the function fails due to an unsupported operation, * the RSA context stays intact and remains usable. * + * \note The length parameters are ignored if the corresponding + * buffer pointers are NULL. + * * \param ctx The initialized RSA context. * \param N The Byte array to store the RSA modulus, or NULL. * \param N_len The size of the buffer for the modulus. @@ -331,21 +342,18 @@ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, * NULL. * \param P_len The size of the buffer for the first prime factor. * \param Q The Byte array to hold the second prime factor of \p N, or - NULL. + * NULL. * \param Q_len The size of the buffer for the second prime factor. * \param D The Byte array to hold the private exponent, or NULL. * \param D_len The size of the buffer for the private exponent. * \param E The Byte array to hold the public exponent, or NULL. * \param E_len The size of the buffer for the public exponent. * - * \note The length fields are ignored if the corresponding - * buffer pointers are NULL. - * - * \return \c 0 on success, - * #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the * requested parameters cannot be done due to missing - * functionality or because of security policies, - * or a non-zero return code on any other failure. + * functionality or because of security policies. + * \return A non-zero return code on any other failure. */ int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, unsigned char *N, size_t N_len, @@ -357,16 +365,17 @@ int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, /** * \brief This function exports CRT parameters of a private RSA key. * + * \note Alternative RSA implementations not using CRT-parameters + * internally can implement this function based on + * mbedtls_rsa_deduce_opt(). + * * \param ctx The initialized RSA context. * \param DP The MPI to hold D modulo P-1, or NULL. * \param DQ The MPI to hold D modulo Q-1, or NULL. * \param QP The MPI to hold modular inverse of Q modulo P, or NULL. * - * \return \c 0 on success, non-zero error code otherwise. - * - * \note Alternative RSA implementations not using CRT-parameters - * internally can implement this function based on - * mbedtls_rsa_deduce_opt(). + * \return \c 0 on success. + * \return A non-zero error code on failure. * */ int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx, @@ -397,17 +406,17 @@ size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ); /** * \brief This function generates an RSA keypair. * + * \note mbedtls_rsa_init() must be called before this function, + * to set up the RSA context. + * * \param ctx The RSA context used to hold the key. * \param f_rng The RNG function. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * \param nbits The size of the public key in bits. * \param exponent The public exponent. For example, 65537. * - * \note mbedtls_rsa_init() must be called before this function, - * to set up the RSA context. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -424,8 +433,8 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, * * \param ctx The RSA context to check. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. * */ int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); @@ -434,11 +443,6 @@ int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); * \brief This function checks if a context contains an RSA private key * and perform basic consistency checks. * - * \param ctx The RSA context to check. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code on - * failure. - * * \note The consistency checks performed by this function not only * ensure that mbedtls_rsa_private() can be called successfully * on the given context, but that the various parameters are @@ -465,6 +469,11 @@ int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); * user to ensure the trustworthiness of the source of his RSA * parameters, which goes beyond what is effectively checkable * by the library.</li></ul> + * + * \param ctx The RSA context to check. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); @@ -476,8 +485,8 @@ int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); * \param pub The RSA context holding the public key. * \param prv The RSA context holding the private key. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv ); @@ -485,13 +494,6 @@ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, /** * \brief This function performs an RSA public key operation. * - * \param ctx The RSA context. - * \param input The input buffer. - * \param output The output buffer. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * * \note This function does not handle message padding. * * \note Make sure to set \p input[0] = 0 or ensure that @@ -499,6 +501,13 @@ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, * * \note The input and output buffers must be large * enough. For example, 128 Bytes if RSA-1024 is used. + * + * \param ctx The RSA context. + * \param input The input buffer. + * \param output The output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, const unsigned char *input, @@ -507,15 +516,6 @@ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, /** * \brief This function performs an RSA private key operation. * - * \param ctx The RSA context. - * \param f_rng The RNG function. Needed for blinding. - * \param p_rng The RNG parameter. - * \param input The input buffer. - * \param output The output buffer. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * * \note The input and output buffers must be large * enough. For example, 128 Bytes if RSA-1024 is used. * @@ -530,6 +530,15 @@ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, * Future versions of the library may enforce the presence * of a PRNG. * + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for blinding. + * \param p_rng The RNG context. + * \param input The input buffer. + * \param output The output buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + * */ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -544,15 +553,8 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, * It is the generic wrapper for performing a PKCS#1 encryption * operation using the \p mode from the context. * - * - * \param ctx The RSA context. - * \param f_rng The RNG function. Needed for padding, PKCS#1 v2.1 - * encoding, and #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param ilen The length of the plaintext. - * \param input The buffer holding the data to encrypt. - * \param output The buffer used to hold the ciphertext. + * \note The input and output buffers must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library @@ -563,11 +565,17 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PRIVATE and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for padding, PKCS#1 v2.1 + * encoding, and #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param ilen The length of the plaintext. + * \param input The buffer holding the data to encrypt. + * \param output The buffer used to hold the ciphertext. * - * \note The input and output buffers must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -580,14 +588,8 @@ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, * \brief This function performs a PKCS#1 v1.5 encryption operation * (RSAES-PKCS1-v1_5-ENCRYPT). * - * \param ctx The RSA context. - * \param f_rng The RNG function. Needed for padding and - * #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param ilen The length of the plaintext. - * \param input The buffer holding the data to encrypt. - * \param output The buffer used to hold the ciphertext. + * \note The output buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library @@ -598,11 +600,17 @@ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PRIVATE and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for padding and + * #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param ilen The length of the plaintext. + * \param input The buffer holding the data to encrypt. + * \param output The buffer used to hold the ciphertext. * - * \note The output buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -615,10 +623,22 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, * \brief This function performs a PKCS#1 v2.1 OAEP encryption * operation (RSAES-OAEP-ENCRYPT). * + * \note The output buffer must be as large as the size + * of ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * * \param ctx The RSA context. * \param f_rng The RNG function. Needed for padding and PKCS#1 v2.1 * encoding and #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. * \param label The buffer holding the custom label to use. * \param label_len The length of the label. @@ -626,20 +646,8 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, * \param input The buffer holding the data to encrypt. * \param output The buffer used to hold the ciphertext. * - * \deprecated It is deprecated and discouraged to call this function - * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library - * are likely to remove the \p mode argument and have it - * implicitly set to #MBEDTLS_RSA_PUBLIC. - * - * \note Alternative implementations of RSA need not support - * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The output buffer must be as large as the size - * of ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -657,14 +665,15 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, * It is the generic wrapper for performing a PKCS#1 decryption * operation using the \p mode from the context. * - * \param ctx The RSA context. - * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param olen The length of the plaintext. - * \param input The buffer holding the encrypted data. - * \param output The buffer used to hold the plaintext. - * \param output_max_len The maximum length of the output buffer. + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N (for example, + * 128 Bytes if RSA-1024 is used) to be able to hold an + * arbitrary decrypted message. If it is not large enough to + * hold the decryption of the particular ciphertext provided, + * the function returns \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \note The input buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library @@ -675,18 +684,17 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PUBLIC and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The output buffer length \c output_max_len should be - * as large as the size \p ctx->len of \p ctx->N (for example, - * 128 Bytes if RSA-1024 is used) to be able to hold an - * arbitrary decrypted message. If it is not large enough to - * hold the decryption of the particular ciphertext provided, - * the function returns \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param olen The length of the plaintext. + * \param input The buffer holding the encrypted data. + * \param output The buffer used to hold the plaintext. + * \param output_max_len The maximum length of the output buffer. * - * \note The input buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -700,14 +708,15 @@ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, * \brief This function performs a PKCS#1 v1.5 decryption * operation (RSAES-PKCS1-v1_5-DECRYPT). * - * \param ctx The RSA context. - * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param olen The length of the plaintext. - * \param input The buffer holding the encrypted data. - * \param output The buffer to hold the plaintext. - * \param output_max_len The maximum length of the output buffer. + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N, for example, + * 128 Bytes if RSA-1024 is used, to be able to hold an + * arbitrary decrypted message. If it is not large enough to + * hold the decryption of the particular ciphertext provided, + * the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \note The input buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library @@ -718,18 +727,18 @@ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PUBLIC and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param olen The length of the plaintext. + * \param input The buffer holding the encrypted data. + * \param output The buffer to hold the plaintext. + * \param output_max_len The maximum length of the output buffer. * - * \note The output buffer length \c output_max_len should be - * as large as the size \p ctx->len of \p ctx->N, for example, - * 128 Bytes if RSA-1024 is used, to be able to hold an - * arbitrary decrypted message. If it is not large enough to - * hold the decryption of the particular ciphertext provided, - * the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. * - * \note The input buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. */ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -740,12 +749,32 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, size_t output_max_len ); /** - * \brief This function performs a PKCS#1 v2.1 OAEP decryption - * operation (RSAES-OAEP-DECRYPT). + * \brief This function performs a PKCS#1 v2.1 OAEP decryption + * operation (RSAES-OAEP-DECRYPT). + * + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N, for + * example, 128 Bytes if RSA-1024 is used, to be able to + * hold an arbitrary decrypted message. If it is not + * large enough to hold the decryption of the particular + * ciphertext provided, the function returns + * #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \note The input buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * * \param ctx The RSA context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. * \param label The buffer holding the custom label to use. * \param label_len The length of the label. @@ -754,28 +783,8 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, * \param output The buffer to hold the plaintext. * \param output_max_len The maximum length of the output buffer. * - * \deprecated It is deprecated and discouraged to call this function - * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library - * are likely to remove the \p mode argument and have it - * implicitly set to #MBEDTLS_RSA_PRIVATE. - * - * \note Alternative implementations of RSA need not support - * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. - * - * \return \c 0 on success, or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The output buffer length \c output_max_len should be - * as large as the size \p ctx->len of \p ctx->N, for - * example, 128 Bytes if RSA-1024 is used, to be able to - * hold an arbitrary decrypted message. If it is not - * large enough to hold the decryption of the particular - * ciphertext provided, the function returns - * #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. - * - * \note The input buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -794,16 +803,12 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, * It is the generic wrapper for performing a PKCS#1 * signature using the \p mode from the context. * - * \param ctx The RSA context. - * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for - * #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param md_alg The message-digest algorithm used to hash the original data. - * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. - * \param hash The buffer holding the message digest. - * \param sig The buffer to hold the ciphertext. + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note For PKCS#1 v2.1 encoding, see comments on + * mbedtls_rsa_rsassa_pss_sign() for details on + * \p md_alg and \p hash_id. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library @@ -814,15 +819,19 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PUBLIC and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 if the signing operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code on failure. - * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for + * #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer to hold the ciphertext. * - * \note For PKCS#1 v2.1 encoding, see comments on - * mbedtls_rsa_rsassa_pss_sign() for details on - * \p md_alg and \p hash_id. + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -837,15 +846,8 @@ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, * \brief This function performs a PKCS#1 v1.5 signature * operation (RSASSA-PKCS1-v1_5-SIGN). * - * \param ctx The RSA context. - * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param md_alg The message-digest algorithm used to hash the original data. - * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. - * \param hash The buffer holding the message digest. - * \param sig The buffer to hold the ciphertext. + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library @@ -856,12 +858,18 @@ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PUBLIC and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 if the signing operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \param ctx The RSA context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer to hold the ciphertext. * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -876,16 +884,15 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, * \brief This function performs a PKCS#1 v2.1 PSS signature * operation (RSASSA-PSS-SIGN). * - * \param ctx The RSA context. - * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for - * #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param md_alg The message-digest algorithm used to hash the original data. - * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. - * \param hash The buffer holding the message digest. - * \param sig The buffer to hold the ciphertext. + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is the one used for the + * encoding. \p md_alg in the function call is the type of hash + * that is encoded. According to <em>RFC-3447: Public-Key + * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography + * Specifications</em> it is advised to keep both hashes the + * same. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library @@ -896,19 +903,19 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PUBLIC and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 if the signing operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \param ctx The RSA context. + * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for + * #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer to hold the ciphertext. * - * \note The \p hash_id in the RSA context is the one used for the - * encoding. \p md_alg in the function call is the type of hash - * that is encoded. According to <em>RFC-3447: Public-Key - * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography - * Specifications</em> it is advised to keep both hashes the - * same. + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -926,15 +933,12 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, * This is the generic wrapper for performing a PKCS#1 * verification using the mode from the context. * - * \param ctx The RSA public key context. - * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param md_alg The message-digest algorithm used to hash the original data. - * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. - * \param hash The buffer holding the message digest. - * \param sig The buffer holding the ciphertext. + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note For PKCS#1 v2.1 encoding, see comments on + * mbedtls_rsa_rsassa_pss_verify() about \p md_alg and + * \p hash_id. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library @@ -945,16 +949,18 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PRIVATE and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 if the verify operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer holding the ciphertext. * - * \note For PKCS#1 v2.1 encoding, see comments on - * mbedtls_rsa_rsassa_pss_verify() about \p md_alg and - * \p hash_id. + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -969,15 +975,8 @@ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, * \brief This function performs a PKCS#1 v1.5 verification * operation (RSASSA-PKCS1-v1_5-VERIFY). * - * \param ctx The RSA public key context. - * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param md_alg The message-digest algorithm used to hash the original data. - * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. - * \param hash The buffer holding the message digest. - * \param sig The buffer holding the ciphertext. + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library @@ -988,12 +987,18 @@ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PRIVATE and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 if the verify operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer holding the ciphertext. * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -1011,15 +1016,16 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, * The hash function for the MGF mask generating function * is that specified in the RSA context. * - * \param ctx The RSA public key context. - * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. - * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. - * \param md_alg The message-digest algorithm used to hash the original data. - * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. - * \param hash The buffer holding the message digest. - * \param sig The buffer holding the ciphertext. + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is the one used for the + * verification. \p md_alg in the function call is the type of + * hash that is verified. According to <em>RFC-3447: Public-Key + * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography + * Specifications</em> it is advised to keep both hashes the + * same. If \p hash_id in the RSA context is unset, + * the \p md_alg from the function call is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library @@ -1030,20 +1036,18 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, * mode being set to #MBEDTLS_RSA_PRIVATE and might instead * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. * - * \return \c 0 if the verify operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * \param ctx The RSA public key context. + * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. + * \param p_rng The RNG context. + * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest. + * \param sig The buffer holding the ciphertext. * - * \note The \p hash_id in the RSA context is the one used for the - * verification. \p md_alg in the function call is the type of - * hash that is verified. According to <em>RFC-3447: Public-Key - * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography - * Specifications</em> it is advised to keep both hashes the - * same. If \p hash_id in the RSA context is unset, - * the \p md_alg from the function call is used. + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -1061,27 +1065,27 @@ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, * The hash function for the MGF mask generating function * is that specified in \p mgf1_hash_id. * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is ignored. + * * \param ctx The RSA public key context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. - * \param p_rng The RNG parameter. + * \param p_rng The RNG context. * \param mode #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. - * \param hashlen The length of the message digest. Only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hashlen The length of the message digest. Only used if \p md_alg is + * #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest. - * \param mgf1_hash_id The message digest used for mask generation. - * \param expected_salt_len The length of the salt used in padding. Use - * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length. + * \param mgf1_hash_id The message digest used for mask generation. + * \param expected_salt_len The length of the salt used in padding. Use + * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length. * \param sig The buffer holding the ciphertext. * - * \return \c 0 if the verify operation was successful, - * or an \c MBEDTLS_ERR_RSA_XXX error code - * on failure. - * - * \note The \p sig buffer must be as large as the size - * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. - * - * \note The \p hash_id in the RSA context is ignored. + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -1100,8 +1104,8 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, * \param dst The destination context. * \param src The source context. * - * \return \c 0 on success, - * #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure. + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure. */ int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ); @@ -1112,22 +1116,11 @@ int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ) */ void mbedtls_rsa_free( mbedtls_rsa_context *ctx ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_RSA_ALT */ -#include "rsa_alt.h" -#endif /* MBEDTLS_RSA_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief The RSA checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_rsa_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/rsa_internal.h b/thirdparty/mbedtls/include/mbedtls/rsa_internal.h index bcb3c9401d..53abd3c5b0 100644 --- a/thirdparty/mbedtls/include/mbedtls/rsa_internal.h +++ b/thirdparty/mbedtls/include/mbedtls/rsa_internal.h @@ -2,6 +2,37 @@ * \file rsa_internal.h * * \brief Context-independent RSA helper functions + * + * This module declares some RSA-related helper functions useful when + * implementing the RSA interface. These functions are provided in a separate + * compilation unit in order to make it easy for designers of alternative RSA + * implementations to use them in their own code, as it is conceived that the + * functionality they provide will be necessary for most complete + * implementations. + * + * End-users of Mbed TLS who are not providing their own alternative RSA + * implementations should not use these functions directly, and should instead + * use only the functions declared in rsa.h. + * + * The interface provided by this module will be maintained through LTS (Long + * Term Support) branches of Mbed TLS, but may otherwise be subject to change, + * and must be considered an internal interface of the library. + * + * There are two classes of helper functions: + * + * (1) Parameter-generating helpers. These are: + * - mbedtls_rsa_deduce_primes + * - mbedtls_rsa_deduce_private_exponent + * - mbedtls_rsa_deduce_crt + * Each of these functions takes a set of core RSA parameters and + * generates some other, or CRT related parameters. + * + * (2) Parameter-checking helpers. These are: + * - mbedtls_rsa_validate_params + * - mbedtls_rsa_validate_crt + * They take a set of core or CRT related RSA parameters and check their + * validity. + * */ /* * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved @@ -21,31 +52,6 @@ * * This file is part of mbed TLS (https://tls.mbed.org) * - * - * This file declares some RSA-related helper functions useful when - * implementing the RSA interface. They are public and provided in a - * separate compilation unit in order to make it easy for designers of - * alternative RSA implementations to use them in their code, as it is - * conceived that the functionality they provide will be necessary - * for most complete implementations. - * - * End-users of Mbed TLS not intending to re-implement the RSA functionality - * are not expected to get into the need of making use of these functions directly, - * but instead should be able to use the functions declared in rsa.h. - * - * There are two classes of helper functions: - * (1) Parameter-generating helpers. These are: - * - mbedtls_rsa_deduce_primes - * - mbedtls_rsa_deduce_private_exponent - * - mbedtls_rsa_deduce_crt - * Each of these functions takes a set of core RSA parameters - * and generates some other, or CRT related parameters. - * (2) Parameter-checking helpers. These are: - * - mbedtls_rsa_validate_params - * - mbedtls_rsa_validate_crt - * They take a set of core or CRT related RSA parameters - * and check their validity. - * */ #ifndef MBEDTLS_RSA_INTERNAL_H @@ -213,4 +219,8 @@ int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *DP, const mbedtls_mpi *DQ, const mbedtls_mpi *QP ); +#ifdef __cplusplus +} +#endif + #endif /* rsa_internal.h */ diff --git a/thirdparty/mbedtls/include/mbedtls/sha1.h b/thirdparty/mbedtls/include/mbedtls/sha1.h index 05540cde12..65a124c94b 100644 --- a/thirdparty/mbedtls/include/mbedtls/sha1.h +++ b/thirdparty/mbedtls/include/mbedtls/sha1.h @@ -1,7 +1,10 @@ /** * \file sha1.h * - * \brief The SHA-1 cryptographic hash function. + * \brief This file contains SHA-1 definitions and functions. + * + * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in + * <em>FIPS 180-4: Secure Hash Standard (SHS)</em>. * * \warning SHA-1 is considered a weak message digest and its use constitutes * a security risk. We recommend considering stronger message @@ -39,14 +42,14 @@ #define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */ -#if !defined(MBEDTLS_SHA1_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_SHA1_ALT) +// Regular implementation +// + /** * \brief The SHA-1 context structure. * @@ -63,40 +66,44 @@ typedef struct } mbedtls_sha1_context; +#else /* MBEDTLS_SHA1_ALT */ +#include "sha1_alt.h" +#endif /* MBEDTLS_SHA1_ALT */ + /** * \brief This function initializes a SHA-1 context. * - * \param ctx The SHA-1 context to initialize. - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param ctx The SHA-1 context to initialize. + * */ void mbedtls_sha1_init( mbedtls_sha1_context *ctx ); /** * \brief This function clears a SHA-1 context. * - * \param ctx The SHA-1 context to clear. - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param ctx The SHA-1 context to clear. + * */ void mbedtls_sha1_free( mbedtls_sha1_context *ctx ); /** * \brief This function clones the state of a SHA-1 context. * - * \param dst The destination context. - * \param src The context to clone. - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param dst The SHA-1 context to clone to. + * \param src The SHA-1 context to clone from. + * */ void mbedtls_sha1_clone( mbedtls_sha1_context *dst, const mbedtls_sha1_context *src ); @@ -104,14 +111,14 @@ void mbedtls_sha1_clone( mbedtls_sha1_context *dst, /** * \brief This function starts a SHA-1 checksum calculation. * - * \param ctx The context to initialize. - * - * \return \c 0 if successful - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param ctx The SHA-1 context to initialize. + * + * \return \c 0 on success. + * */ int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx ); @@ -119,16 +126,15 @@ int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx ); * \brief This function feeds an input buffer into an ongoing SHA-1 * checksum calculation. * - * \param ctx The SHA-1 context. - * \param input The buffer holding the input data. - * \param ilen The length of the input data. - * - * \return \c 0 if successful - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param ctx The SHA-1 context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. */ int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx, const unsigned char *input, @@ -138,31 +144,30 @@ int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx, * \brief This function finishes the SHA-1 operation, and writes * the result to the output buffer. * - * \param ctx The SHA-1 context. - * \param output The SHA-1 checksum result. - * - * \return \c 0 if successful - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param ctx The SHA-1 context. + * \param output The SHA-1 checksum result. + * + * \return \c 0 on success. */ int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx, unsigned char output[20] ); /** - * \brief SHA-1 process data block (internal use only) - * - * \param ctx SHA-1 context - * \param data The data block being processed. - * - * \return \c 0 if successful + * \brief SHA-1 process data block (internal use only). * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \param ctx The SHA-1 context. + * \param data The data block being processed. + * + * \return \c 0 on success. + * */ int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] ); @@ -174,65 +179,67 @@ int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx, #define MBEDTLS_DEPRECATED #endif /** - * \brief SHA-1 context setup - * - * \deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0 - * - * \param ctx The SHA-1 context to be initialized. + * \brief This function starts a SHA-1 checksum calculation. * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0. + * + * \param ctx The SHA-1 context to initialize. + * */ MBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx ); /** - * \brief SHA-1 process buffer + * \brief This function feeds an input buffer into an ongoing SHA-1 + * checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. * - * \deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0 + * \deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0. * * \param ctx The SHA-1 context. * \param input The buffer holding the input data. * \param ilen The length of the input data. * - * \warning SHA-1 is considered a weak message digest and its use - * constitutes a security risk. We recommend considering - * stronger message digests instead. - * */ MBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen ); /** - * \brief SHA-1 final digest - * - * \deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0 - * - * \param ctx The SHA-1 context. - * \param output The SHA-1 checksum result. + * \brief This function finishes the SHA-1 operation, and writes + * the result to the output buffer. * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0. + * + * \param ctx The SHA-1 context. + * \param output The SHA-1 checksum result. + * */ MBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] ); /** - * \brief SHA-1 process data block (internal use only) - * - * \deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0 - * - * \param ctx The SHA-1 context. - * \param data The data block being processed. + * \brief SHA-1 process data block (internal use only). * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0. + * + * \param ctx The SHA-1 context. + * \param data The data block being processed. + * */ MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] ); @@ -240,18 +247,6 @@ MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx, #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_SHA1_ALT */ -#include "sha1_alt.h" -#endif /* MBEDTLS_SHA1_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief This function calculates the SHA-1 checksum of a buffer. * @@ -261,15 +256,15 @@ extern "C" { * The SHA-1 result is calculated as * output = SHA-1(input buffer). * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * * \param input The buffer holding the input data. * \param ilen The length of the input data. * \param output The SHA-1 checksum result. * - * \return \c 0 if successful - * - * \warning SHA-1 is considered a weak message digest and its use - * constitutes a security risk. We recommend considering - * stronger message digests instead. + * \return \c 0 on success. * */ int mbedtls_sha1_ret( const unsigned char *input, @@ -283,18 +278,24 @@ int mbedtls_sha1_ret( const unsigned char *input, #define MBEDTLS_DEPRECATED #endif /** - * \brief Output = SHA-1( input buffer ) + * \brief This function calculates the SHA-1 checksum of a buffer. * - * \deprecated Superseded by mbedtls_sha1_ret() in 2.7.0 + * The function allocates the context, performs the + * calculation, and frees the context. * - * \param input The buffer holding the input data. - * \param ilen The length of the input data. - * \param output The SHA-1 checksum result. + * The SHA-1 result is calculated as + * output = SHA-1(input buffer). * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \deprecated Superseded by mbedtls_sha1_ret() in 2.7.0 + * + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The SHA-1 checksum result. + * */ MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input, size_t ilen, @@ -306,12 +307,13 @@ MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input, /** * \brief The SHA-1 checkup routine. * - * \return \c 0 on success, or \c 1 on failure. - * * \warning SHA-1 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * + * \return \c 0 on success. + * \return \c 1 on failure. + * */ int mbedtls_sha1_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/sha256.h b/thirdparty/mbedtls/include/mbedtls/sha256.h index ffb16c277a..adf31a82ed 100644 --- a/thirdparty/mbedtls/include/mbedtls/sha256.h +++ b/thirdparty/mbedtls/include/mbedtls/sha256.h @@ -1,7 +1,10 @@ /** * \file sha256.h * - * \brief The SHA-224 and SHA-256 cryptographic hash function. + * \brief This file contains SHA-224 and SHA-256 definitions and functions. + * + * The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic + * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>. */ /* * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -35,14 +38,14 @@ #define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */ -#if !defined(MBEDTLS_SHA256_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_SHA256_ALT) +// Regular implementation +// + /** * \brief The SHA-256 context structure. * @@ -55,12 +58,15 @@ typedef struct uint32_t total[2]; /*!< The number of Bytes processed. */ uint32_t state[8]; /*!< The intermediate digest state. */ unsigned char buffer[64]; /*!< The data block being processed. */ - int is224; /*!< Determines which function to use. - <ul><li>0: Use SHA-256.</li> - <li>1: Use SHA-224.</li></ul> */ + int is224; /*!< Determines which function to use: + 0: Use SHA-256, or 1: Use SHA-224. */ } mbedtls_sha256_context; +#else /* MBEDTLS_SHA256_ALT */ +#include "sha256_alt.h" +#endif /* MBEDTLS_SHA256_ALT */ + /** * \brief This function initializes a SHA-256 context. * @@ -89,9 +95,8 @@ void mbedtls_sha256_clone( mbedtls_sha256_context *dst, * calculation. * * \param ctx The context to initialize. - * \param is224 Determines which function to use. - * <ul><li>0: Use SHA-256.</li> - * <li>1: Use SHA-224.</li></ul> + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. * * \return \c 0 on success. */ @@ -101,9 +106,9 @@ int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 ); * \brief This function feeds an input buffer into an ongoing * SHA-256 checksum calculation. * - * \param ctx SHA-256 context - * \param input buffer holding the data - * \param ilen length of the input data + * \param ctx The SHA-256 context. + * \param input The buffer holding the data. + * \param ilen The length of the input data. * * \return \c 0 on success. */ @@ -143,14 +148,15 @@ int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx, #define MBEDTLS_DEPRECATED #endif /** - * \brief This function starts a SHA-256 checksum calculation. + * \brief This function starts a SHA-224 or SHA-256 checksum + * calculation. + * * * \deprecated Superseded by mbedtls_sha256_starts_ret() in 2.7.0. * - * \param ctx The SHA-256 context to initialize. - * \param is224 Determines which function to use. - * <ul><li>0: Use SHA-256.</li> - * <li>1: Use SHA-224.</li></ul> + * \param ctx The context to initialize. + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. */ MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 ); @@ -176,7 +182,7 @@ MBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx, * \deprecated Superseded by mbedtls_sha256_finish_ret() in 2.7.0. * * \param ctx The SHA-256 context. - * \param output The SHA-224or SHA-256 checksum result. + * \param output The SHA-224 or SHA-256 checksum result. */ MBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] ); @@ -196,17 +202,6 @@ MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx, #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_SHA256_ALT */ -#include "sha256_alt.h" -#endif /* MBEDTLS_SHA256_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif /** * \brief This function calculates the SHA-224 or SHA-256 @@ -221,9 +216,8 @@ extern "C" { * \param input The buffer holding the input data. * \param ilen The length of the input data. * \param output The SHA-224 or SHA-256 checksum result. - * \param is224 Determines which function to use. - * <ul><li>0: Use SHA-256.</li> - * <li>1: Use SHA-224.</li></ul> + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. */ int mbedtls_sha256_ret( const unsigned char *input, size_t ilen, @@ -252,9 +246,8 @@ int mbedtls_sha256_ret( const unsigned char *input, * \param input The buffer holding the data. * \param ilen The length of the input data. * \param output The SHA-224 or SHA-256 checksum result. - * \param is224 Determines which function to use. - * <ul><li>0: Use SHA-256.</li> - * <li>1: Use SHA-224.</li></ul> + * \param is224 Determines which function to use: + * 0: Use SHA-256, or 1: Use SHA-224. */ MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input, size_t ilen, @@ -267,7 +260,8 @@ MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input, /** * \brief The SHA-224 and SHA-256 checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_sha256_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/sha512.h b/thirdparty/mbedtls/include/mbedtls/sha512.h index 8404a2d599..5bb83f43bd 100644 --- a/thirdparty/mbedtls/include/mbedtls/sha512.h +++ b/thirdparty/mbedtls/include/mbedtls/sha512.h @@ -1,7 +1,9 @@ /** * \file sha512.h + * \brief This file contains SHA-384 and SHA-512 definitions and functions. * - * \brief The SHA-384 and SHA-512 cryptographic hash function. + * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic + * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>. */ /* * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -35,14 +37,14 @@ #define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /**< SHA-512 hardware accelerator failed */ -#if !defined(MBEDTLS_SHA512_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_SHA512_ALT) +// Regular implementation +// + /** * \brief The SHA-512 context structure. * @@ -55,12 +57,15 @@ typedef struct uint64_t total[2]; /*!< The number of Bytes processed. */ uint64_t state[8]; /*!< The intermediate digest state. */ unsigned char buffer[128]; /*!< The data block being processed. */ - int is384; /*!< Determines which function to use. - * <ul><li>0: Use SHA-512.</li> - * <li>1: Use SHA-384.</li></ul> */ + int is384; /*!< Determines which function to use: + 0: Use SHA-512, or 1: Use SHA-384. */ } mbedtls_sha512_context; +#else /* MBEDTLS_SHA512_ALT */ +#include "sha512_alt.h" +#endif /* MBEDTLS_SHA512_ALT */ + /** * \brief This function initializes a SHA-512 context. * @@ -89,9 +94,8 @@ void mbedtls_sha512_clone( mbedtls_sha512_context *dst, * calculation. * * \param ctx The SHA-512 context to initialize. - * \param is384 Determines which function to use. - * <ul><li>0: Use SHA-512.</li> - * <li>1: Use SHA-384.</li></ul> + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. * * \return \c 0 on success. */ @@ -148,9 +152,8 @@ int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, * \deprecated Superseded by mbedtls_sha512_starts_ret() in 2.7.0 * * \param ctx The SHA-512 context to initialize. - * \param is384 Determines which function to use. - * <ul><li>0: Use SHA-512.</li> - * <li>1: Use SHA-384.</li></ul> + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. */ MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 ); @@ -159,7 +162,7 @@ MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, * \brief This function feeds an input buffer into an ongoing * SHA-512 checksum calculation. * - * \deprecated Superseded by mbedtls_sha512_update_ret() in 2.7.0 + * \deprecated Superseded by mbedtls_sha512_update_ret() in 2.7.0. * * \param ctx The SHA-512 context. * \param input The buffer holding the data. @@ -173,7 +176,7 @@ MBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx, * \brief This function finishes the SHA-512 operation, and writes * the result to the output buffer. * - * \deprecated Superseded by mbedtls_sha512_finish_ret() in 2.7.0 + * \deprecated Superseded by mbedtls_sha512_finish_ret() in 2.7.0. * * \param ctx The SHA-512 context. * \param output The SHA-384 or SHA-512 checksum result. @@ -186,7 +189,7 @@ MBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, * the ongoing SHA-512 computation. This function is for * internal use only. * - * \deprecated Superseded by mbedtls_internal_sha512_process() in 2.7.0 + * \deprecated Superseded by mbedtls_internal_sha512_process() in 2.7.0. * * \param ctx The SHA-512 context. * \param data The buffer holding one block of data. @@ -198,18 +201,6 @@ MBEDTLS_DEPRECATED void mbedtls_sha512_process( #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_SHA512_ALT */ -#include "sha512_alt.h" -#endif /* MBEDTLS_SHA512_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief This function calculates the SHA-512 or SHA-384 * checksum of a buffer. @@ -223,9 +214,8 @@ extern "C" { * \param input The buffer holding the input data. * \param ilen The length of the input data. * \param output The SHA-384 or SHA-512 checksum result. - * \param is384 Determines which function to use. - * <ul><li>0: Use SHA-512.</li> - * <li>1: Use SHA-384.</li></ul> + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. * * \return \c 0 on success. */ @@ -255,9 +245,8 @@ int mbedtls_sha512_ret( const unsigned char *input, * \param input The buffer holding the data. * \param ilen The length of the input data. * \param output The SHA-384 or SHA-512 checksum result. - * \param is384 Determines which function to use. - * <ul><li>0: Use SHA-512.</li> - * <li>1: Use SHA-384.</li></ul> + * \param is384 Determines which function to use: + * 0: Use SHA-512, or 1: Use SHA-384. */ MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input, size_t ilen, @@ -269,7 +258,8 @@ MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input, /** * \brief The SHA-384 or SHA-512 checkup routine. * - * \return \c 0 on success, or \c 1 on failure. + * \return \c 0 on success. + * \return \c 1 on failure. */ int mbedtls_sha512_self_test( int verbose ); diff --git a/thirdparty/mbedtls/include/mbedtls/ssl.h b/thirdparty/mbedtls/include/mbedtls/ssl.h index dffc162191..250031a6d3 100644 --- a/thirdparty/mbedtls/include/mbedtls/ssl.h +++ b/thirdparty/mbedtls/include/mbedtls/ssl.h @@ -112,13 +112,14 @@ #define MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED -0x6A80 /**< DTLS client must retry for hello verification */ #define MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL -0x6A00 /**< A buffer is too small to receive or write a message */ #define MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE -0x6980 /**< None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages). */ -#define MBEDTLS_ERR_SSL_WANT_READ -0x6900 /**< Connection requires a read call. */ +#define MBEDTLS_ERR_SSL_WANT_READ -0x6900 /**< No data of requested type currently available on underlying transport. */ #define MBEDTLS_ERR_SSL_WANT_WRITE -0x6880 /**< Connection requires a write call. */ #define MBEDTLS_ERR_SSL_TIMEOUT -0x6800 /**< The operation timed out. */ #define MBEDTLS_ERR_SSL_CLIENT_RECONNECT -0x6780 /**< The client initiated a reconnect from the same port. */ #define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD -0x6700 /**< Record header looks valid but is not expected. */ #define MBEDTLS_ERR_SSL_NON_FATAL -0x6680 /**< The alert message received indicates a non-fatal error. */ #define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH -0x6600 /**< Couldn't set the hash for verifying CertificateVerify */ +#define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING -0x6580 /**< Internal-only message signaling that further message-processing should be done */ /* * Various constants @@ -682,10 +683,18 @@ struct mbedtls_ssl_config #endif #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) - unsigned char *psk; /*!< pre-shared key */ - size_t psk_len; /*!< length of the pre-shared key */ - unsigned char *psk_identity; /*!< identity for PSK negotiation */ - size_t psk_identity_len;/*!< length of identity */ + unsigned char *psk; /*!< pre-shared key. This field should + only be set via + mbedtls_ssl_conf_psk() */ + size_t psk_len; /*!< length of the pre-shared key. This + field should only be set via + mbedtls_ssl_conf_psk() */ + unsigned char *psk_identity; /*!< identity for PSK negotiation. This + field should only be set via + mbedtls_ssl_conf_psk() */ + size_t psk_identity_len;/*!< length of identity. This field should + only be set via + mbedtls_ssl_conf_psk() */ #endif #if defined(MBEDTLS_SSL_ALPN) @@ -938,14 +947,6 @@ extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl); #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ /** - * \brief Returns the list of ciphersuites supported by the SSL/TLS module. - * - * \return a statically allocated array of ciphersuites, the last - * entry is 0. - */ -const int *mbedtls_ssl_list_ciphersuites( void ); - -/** * \brief Return the name of the ciphersuite associated with the * given ID * @@ -1601,6 +1602,10 @@ void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, /** * \brief Set the data required to verify peer certificate * + * \note See \c mbedtls_x509_crt_verify() for notes regarding the + * parameters ca_chain (maps to trust_ca for that function) + * and ca_crl. + * * \param conf SSL configuration * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs) * \param ca_crl trusted CA CRLs @@ -1841,21 +1846,21 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, #if defined(MBEDTLS_X509_CRT_PARSE_C) /** - * \brief Set or reset the hostname to check against the received - * server certificate. It sets the ServerName TLS extension, + * \brief Set or reset the hostname to check against the received + * server certificate. It sets the ServerName TLS extension, * too, if that extension is enabled. (client-side only) * * \param ssl SSL context * \param hostname the server hostname, may be NULL to clear hostname - + * \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN. * - * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on - * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on + * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on + * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on * too long input hostname. * * Hostname set to the one provided on success (cleared - * when NULL). On allocation failure hostname is cleared. + * when NULL). On allocation failure hostname is cleared. * On too long input failure, old hostname is unchanged. */ int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ); @@ -2289,11 +2294,59 @@ void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, #endif /* MBEDTLS_SSL_RENEGOTIATION */ /** - * \brief Return the number of data bytes available to read + * \brief Check if there is data already read from the + * underlying transport but not yet processed. + * + * \param ssl SSL context + * + * \return 0 if nothing's pending, 1 otherwise. + * + * \note This is different in purpose and behaviour from + * \c mbedtls_ssl_get_bytes_avail in that it considers + * any kind of unprocessed data, not only unread + * application data. If \c mbedtls_ssl_get_bytes + * returns a non-zero value, this function will + * also signal pending data, but the converse does + * not hold. For example, in DTLS there might be + * further records waiting to be processed from + * the current underlying transport's datagram. + * + * \note If this function returns 1 (data pending), this + * does not imply that a subsequent call to + * \c mbedtls_ssl_read will provide any data; + * e.g., the unprocessed data might turn out + * to be an alert or a handshake message. + * + * \note This function is useful in the following situation: + * If the SSL/TLS module successfully returns from an + * operation - e.g. a handshake or an application record + * read - and you're awaiting incoming data next, you + * must not immediately idle on the underlying transport + * to have data ready, but you need to check the value + * of this function first. The reason is that the desired + * data might already be read but not yet processed. + * If, in contrast, a previous call to the SSL/TLS module + * returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary + * to call this function, as the latter error code entails + * that all internal data has been processed. + * + */ +int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the number of application data bytes + * remaining to be read from the current record. * * \param ssl SSL context * - * \return how many bytes are available in the read buffer + * \return How many bytes are available in the application + * data record read buffer. + * + * \note When working over a datagram transport, this is + * useful to detect the current datagram's boundary + * in case \c mbedtls_ssl_read has written the maximal + * amount of data fitting into the input buffer. + * */ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ); @@ -2408,11 +2461,25 @@ int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session * MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED (see below), or * a specific SSL error code. * + * If this function returns MBEDTLS_ERR_SSL_WANT_READ, the + * handshake is unfinished and no further data is available + * from the underlying transport. In this case, you must call + * the function again at some later stage. + * + * \note Remarks regarding event-driven DTLS: + * If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram + * from the underlying transport layer is currently being processed, + * and it is safe to idle until the timer or the underlying transport + * signal a new event. This is not true for a successful handshake, + * in which case the datagram of the underlying transport that is + * currently being processed might or might not contain further + * DTLS records. + * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. * * \note If DTLS is in use, then you may choose to handle * MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging @@ -2429,10 +2496,10 @@ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ); * call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. * * \param ssl SSL context * @@ -2456,10 +2523,10 @@ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ); * value. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. */ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); #endif /* MBEDTLS_SSL_RENEGOTIATION */ @@ -2471,20 +2538,20 @@ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); * \param buf buffer that will hold the data * \param len maximum number of bytes to read * - * \return the number of bytes read, or - * 0 for EOF, or - * MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE, or - * MBEDTLS_ERR_SSL_CLIENT_RECONNECT (see below), or - * another negative error code. + * \return One of the following: + * - 0 if the read end of the underlying transport was closed, + * - the (positive) number of bytes read, or + * - a negative error code on failure. * - * \note If this function returns something other than a positive - * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE or - * MBEDTLS_ERR_SSL_CLIENT_RECONNECT, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * If MBEDTLS_ERR_SSL_WANT_READ is returned, no application data + * is available from the underlying transport. In this case, + * the function needs to be called again at some later stage. * - * \note When this function return MBEDTLS_ERR_SSL_CLIENT_RECONNECT + * If MBEDTLS_ERR_SSL_WANT_WRITE is returned, a write is pending + * but the underlying transport isn't available for writing. In this + * case, the function needs to be called again at some later stage. + * + * When this function return MBEDTLS_ERR_SSL_CLIENT_RECONNECT * (which can only happen server-side), it means that a client * is initiating a new connection using the same source port. * You can either treat that as a connection close and wait @@ -2497,6 +2564,28 @@ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); * again. WARNING: not validating the identity of the client * again, or not transmitting the new identity to the * application layer, would allow authentication bypass! + * + * \note If this function returns something other than a positive value + * or MBEDTLS_ERR_SSL_WANT_READ/WRITE or MBEDTLS_ERR_SSL_CLIENT_RECONNECT, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() on it + * before re-using it for a new connection; the current connection + * must be closed. + * + * \note Remarks regarding event-driven DTLS: + * - If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram + * from the underlying transport layer is currently being processed, + * and it is safe to idle until the timer or the underlying transport + * signal a new event. + * - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was + * initially available on the underlying transport, as this data may have + * been only e.g. duplicated messages or a renegotiation request. + * Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even + * when reacting to an incoming-data event from the underlying transport. + * - On success, the datagram of the underlying transport that is currently + * being processed may contain further DTLS records. You should call + * \c mbedtls_ssl_check_pending to check for remaining records. + * */ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ); @@ -2517,15 +2606,17 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) * or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ, * or another negative error code. * - * \note If this function returns something other than a positive - * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * \note If this function returns something other than a positive value + * or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. * * \note When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, * it must be called later with the *same* arguments, - * until it returns a positive value. + * until it returns a positive value. When the function returns + * MBEDTLS_ERR_SSL_WANT_WRITE there may be some partial + * data in the output buffer, however this is not yet sent. * * \note If the requested length is greater than the maximum * fragment length (either the built-in limit or the one set @@ -2548,10 +2639,10 @@ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_ * \return 0 if successful, or a specific SSL error code. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. */ int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, unsigned char level, @@ -2564,10 +2655,10 @@ int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, * \return 0 if successful, or a specific SSL error code. * * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, then the ssl context - * becomes unusable, and you should either free it or call - * \c mbedtls_ssl_session_reset() on it before re-using it for - * a new connection; the current connection must be closed. + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. */ int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ); diff --git a/thirdparty/mbedtls/include/mbedtls/ssl_ciphersuites.h b/thirdparty/mbedtls/include/mbedtls/ssl_ciphersuites.h index 545468a510..7d5eba0916 100644 --- a/thirdparty/mbedtls/include/mbedtls/ssl_ciphersuites.h +++ b/thirdparty/mbedtls/include/mbedtls/ssl_ciphersuites.h @@ -169,6 +169,45 @@ extern "C" { #define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 0xC03A /**< Weak! No SSL3! */ #define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 0xC03B /**< Weak! No SSL3! */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 0xC03C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 0xC03D /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC044 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC045 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC04A /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC04B /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC04C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC04D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 0xC04E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 0xC04F /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0xC062 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0xC063 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 0xC064 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 0xC065 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC066 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC067 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 0xC068 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 0xC069 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 0xC06A /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 0xC06B /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0xC06C /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0xC06D /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0xC06E /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0xC06F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC070 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC071 /**< TLS 1.2 */ + #define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072 /**< Not in SSL3! */ #define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073 /**< Not in SSL3! */ #define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC074 /**< Not in SSL3! */ @@ -267,7 +306,7 @@ typedef enum { defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ - defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED #endif diff --git a/thirdparty/mbedtls/include/mbedtls/threading.h b/thirdparty/mbedtls/include/mbedtls/threading.h index 58e6db2f3a..aeea5d0e1a 100644 --- a/thirdparty/mbedtls/include/mbedtls/threading.h +++ b/thirdparty/mbedtls/include/mbedtls/threading.h @@ -96,8 +96,12 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex ); /* * Global mutexes */ +#if defined(MBEDTLS_FS_IO) extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex; +#endif +#if defined(MBEDTLS_HAVE_TIME_DATE) extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex; +#endif #endif /* MBEDTLS_THREADING_C */ #ifdef __cplusplus diff --git a/thirdparty/mbedtls/include/mbedtls/timing.h b/thirdparty/mbedtls/include/mbedtls/timing.h index 2c497bf4eb..bbcb90688a 100644 --- a/thirdparty/mbedtls/include/mbedtls/timing.h +++ b/thirdparty/mbedtls/include/mbedtls/timing.h @@ -30,16 +30,16 @@ #include MBEDTLS_CONFIG_FILE #endif -#if !defined(MBEDTLS_TIMING_ALT) -// Regular implementation -// - #include <stdint.h> #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_TIMING_ALT) +// Regular implementation +// + /** * \brief timer structure */ @@ -58,6 +58,10 @@ typedef struct uint32_t fin_ms; } mbedtls_timing_delay_context; +#else /* MBEDTLS_TIMING_ALT */ +#include "timing_alt.h" +#endif /* MBEDTLS_TIMING_ALT */ + extern volatile int mbedtls_timing_alarmed; /** @@ -133,18 +137,6 @@ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms ); */ int mbedtls_timing_get_delay( void *data ); -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_TIMING_ALT */ -#include "timing_alt.h" -#endif /* MBEDTLS_TIMING_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine diff --git a/thirdparty/mbedtls/include/mbedtls/version.h b/thirdparty/mbedtls/include/mbedtls/version.h index c3ee649f5c..83e3c1726b 100644 --- a/thirdparty/mbedtls/include/mbedtls/version.h +++ b/thirdparty/mbedtls/include/mbedtls/version.h @@ -39,7 +39,7 @@ * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 2 -#define MBEDTLS_VERSION_MINOR 8 +#define MBEDTLS_VERSION_MINOR 10 #define MBEDTLS_VERSION_PATCH 0 /** @@ -47,9 +47,9 @@ * MMNNPP00 * Major version | Minor version | Patch version */ -#define MBEDTLS_VERSION_NUMBER 0x02080000 -#define MBEDTLS_VERSION_STRING "2.8.0" -#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.8.0" +#define MBEDTLS_VERSION_NUMBER 0x020A0000 +#define MBEDTLS_VERSION_STRING "2.10.0" +#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.10.0" #if defined(MBEDTLS_VERSION_C) diff --git a/thirdparty/mbedtls/include/mbedtls/x509_crt.h b/thirdparty/mbedtls/include/mbedtls/x509_crt.h index 2dbb7ec964..ac23cffe84 100644 --- a/thirdparty/mbedtls/include/mbedtls/x509_crt.h +++ b/thirdparty/mbedtls/include/mbedtls/x509_crt.h @@ -287,8 +287,15 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix, * used to sign the certificate, CRL verification is skipped * silently, that is *without* setting any flag. * + * \note The \c trust_ca list can contain two types of certificates: + * (1) those of trusted root CAs, so that certificates + * chaining up to those CAs will be trusted, and (2) + * self-signed end-entity certificates to be trusted (for + * specific peers you know) - in that case, the self-signed + * certificate doesn't need to have the CA bit set. + * * \param crt a certificate (chain) to be verified - * \param trust_ca the list of trusted CAs + * \param trust_ca the list of trusted CAs (see note above) * \param ca_crl the list of CRLs for trusted CAs (see note above) * \param cn expected Common Name (can be set to * NULL if the CN must not be verified) diff --git a/thirdparty/mbedtls/include/mbedtls/xtea.h b/thirdparty/mbedtls/include/mbedtls/xtea.h index 34ccee3c22..8df708a3a5 100644 --- a/thirdparty/mbedtls/include/mbedtls/xtea.h +++ b/thirdparty/mbedtls/include/mbedtls/xtea.h @@ -39,14 +39,14 @@ #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */ #define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */ -#if !defined(MBEDTLS_XTEA_ALT) -// Regular implementation -// - #ifdef __cplusplus extern "C" { #endif +#if !defined(MBEDTLS_XTEA_ALT) +// Regular implementation +// + /** * \brief XTEA context structure */ @@ -56,6 +56,10 @@ typedef struct } mbedtls_xtea_context; +#else /* MBEDTLS_XTEA_ALT */ +#include "xtea_alt.h" +#endif /* MBEDTLS_XTEA_ALT */ + /** * \brief Initialize XTEA context * @@ -115,18 +119,6 @@ int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_CBC */ -#ifdef __cplusplus -} -#endif - -#else /* MBEDTLS_XTEA_ALT */ -#include "xtea_alt.h" -#endif /* MBEDTLS_XTEA_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - /** * \brief Checkup routine * diff --git a/thirdparty/mbedtls/library/aes.c b/thirdparty/mbedtls/library/aes.c index 3d2eac82dd..fea9b5383d 100644 --- a/thirdparty/mbedtls/library/aes.c +++ b/thirdparty/mbedtls/library/aes.c @@ -36,6 +36,7 @@ #include <string.h> #include "mbedtls/aes.h" +#include "mbedtls/platform_util.h" #if defined(MBEDTLS_PADLOCK_C) #include "mbedtls/padlock.h" #endif @@ -54,11 +55,6 @@ #if !defined(MBEDTLS_AES_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (little endian) */ @@ -201,6 +197,8 @@ static const unsigned char FSb[256] = static const uint32_t FT0[256] = { FT }; #undef V +#if !defined(MBEDTLS_AES_FEWER_TABLES) + #define V(a,b,c,d) 0x##b##c##d##a static const uint32_t FT1[256] = { FT }; #undef V @@ -213,6 +211,8 @@ static const uint32_t FT2[256] = { FT }; static const uint32_t FT3[256] = { FT }; #undef V +#endif /* !MBEDTLS_AES_FEWER_TABLES */ + #undef FT /* @@ -328,6 +328,8 @@ static const unsigned char RSb[256] = static const uint32_t RT0[256] = { RT }; #undef V +#if !defined(MBEDTLS_AES_FEWER_TABLES) + #define V(a,b,c,d) 0x##b##c##d##a static const uint32_t RT1[256] = { RT }; #undef V @@ -340,6 +342,8 @@ static const uint32_t RT2[256] = { RT }; static const uint32_t RT3[256] = { RT }; #undef V +#endif /* !MBEDTLS_AES_FEWER_TABLES */ + #undef RT /* @@ -359,18 +363,22 @@ static const uint32_t RCON[10] = */ static unsigned char FSb[256]; static uint32_t FT0[256]; +#if !defined(MBEDTLS_AES_FEWER_TABLES) static uint32_t FT1[256]; static uint32_t FT2[256]; static uint32_t FT3[256]; +#endif /* !MBEDTLS_AES_FEWER_TABLES */ /* * Reverse S-box & tables */ static unsigned char RSb[256]; static uint32_t RT0[256]; +#if !defined(MBEDTLS_AES_FEWER_TABLES) static uint32_t RT1[256]; static uint32_t RT2[256]; static uint32_t RT3[256]; +#endif /* !MBEDTLS_AES_FEWER_TABLES */ /* * Round constants @@ -445,9 +453,11 @@ static void aes_gen_tables( void ) ( (uint32_t) x << 16 ) ^ ( (uint32_t) z << 24 ); +#if !defined(MBEDTLS_AES_FEWER_TABLES) FT1[i] = ROTL8( FT0[i] ); FT2[i] = ROTL8( FT1[i] ); FT3[i] = ROTL8( FT2[i] ); +#endif /* !MBEDTLS_AES_FEWER_TABLES */ x = RSb[i]; @@ -456,14 +466,48 @@ static void aes_gen_tables( void ) ( (uint32_t) MUL( 0x0D, x ) << 16 ) ^ ( (uint32_t) MUL( 0x0B, x ) << 24 ); +#if !defined(MBEDTLS_AES_FEWER_TABLES) RT1[i] = ROTL8( RT0[i] ); RT2[i] = ROTL8( RT1[i] ); RT3[i] = ROTL8( RT2[i] ); +#endif /* !MBEDTLS_AES_FEWER_TABLES */ } } +#undef ROTL8 + #endif /* MBEDTLS_AES_ROM_TABLES */ +#if defined(MBEDTLS_AES_FEWER_TABLES) + +#define ROTL8(x) ( (uint32_t)( ( x ) << 8 ) + (uint32_t)( ( x ) >> 24 ) ) +#define ROTL16(x) ( (uint32_t)( ( x ) << 16 ) + (uint32_t)( ( x ) >> 16 ) ) +#define ROTL24(x) ( (uint32_t)( ( x ) << 24 ) + (uint32_t)( ( x ) >> 8 ) ) + +#define AES_RT0(idx) RT0[idx] +#define AES_RT1(idx) ROTL8( RT0[idx] ) +#define AES_RT2(idx) ROTL16( RT0[idx] ) +#define AES_RT3(idx) ROTL24( RT0[idx] ) + +#define AES_FT0(idx) FT0[idx] +#define AES_FT1(idx) ROTL8( FT0[idx] ) +#define AES_FT2(idx) ROTL16( FT0[idx] ) +#define AES_FT3(idx) ROTL24( FT0[idx] ) + +#else /* MBEDTLS_AES_FEWER_TABLES */ + +#define AES_RT0(idx) RT0[idx] +#define AES_RT1(idx) RT1[idx] +#define AES_RT2(idx) RT2[idx] +#define AES_RT3(idx) RT3[idx] + +#define AES_FT0(idx) FT0[idx] +#define AES_FT1(idx) FT1[idx] +#define AES_FT2(idx) FT2[idx] +#define AES_FT3(idx) FT3[idx] + +#endif /* MBEDTLS_AES_FEWER_TABLES */ + void mbedtls_aes_init( mbedtls_aes_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_aes_context ) ); @@ -474,7 +518,7 @@ void mbedtls_aes_free( mbedtls_aes_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_aes_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aes_context ) ); } /* @@ -641,10 +685,10 @@ int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, { for( j = 0; j < 4; j++, SK++ ) { - *RK++ = RT0[ FSb[ ( *SK ) & 0xFF ] ] ^ - RT1[ FSb[ ( *SK >> 8 ) & 0xFF ] ] ^ - RT2[ FSb[ ( *SK >> 16 ) & 0xFF ] ] ^ - RT3[ FSb[ ( *SK >> 24 ) & 0xFF ] ]; + *RK++ = AES_RT0( FSb[ ( *SK ) & 0xFF ] ) ^ + AES_RT1( FSb[ ( *SK >> 8 ) & 0xFF ] ) ^ + AES_RT2( FSb[ ( *SK >> 16 ) & 0xFF ] ) ^ + AES_RT3( FSb[ ( *SK >> 24 ) & 0xFF ] ); } } @@ -660,50 +704,50 @@ exit: } #endif /* !MBEDTLS_AES_SETKEY_DEC_ALT */ -#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ -{ \ - X0 = *RK++ ^ FT0[ ( Y0 ) & 0xFF ] ^ \ - FT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y3 >> 24 ) & 0xFF ]; \ - \ - X1 = *RK++ ^ FT0[ ( Y1 ) & 0xFF ] ^ \ - FT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y0 >> 24 ) & 0xFF ]; \ - \ - X2 = *RK++ ^ FT0[ ( Y2 ) & 0xFF ] ^ \ - FT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y1 >> 24 ) & 0xFF ]; \ - \ - X3 = *RK++ ^ FT0[ ( Y3 ) & 0xFF ] ^ \ - FT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y2 >> 24 ) & 0xFF ]; \ +#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ +{ \ + X0 = *RK++ ^ AES_FT0( ( Y0 ) & 0xFF ) ^ \ + AES_FT1( ( Y1 >> 8 ) & 0xFF ) ^ \ + AES_FT2( ( Y2 >> 16 ) & 0xFF ) ^ \ + AES_FT3( ( Y3 >> 24 ) & 0xFF ); \ + \ + X1 = *RK++ ^ AES_FT0( ( Y1 ) & 0xFF ) ^ \ + AES_FT1( ( Y2 >> 8 ) & 0xFF ) ^ \ + AES_FT2( ( Y3 >> 16 ) & 0xFF ) ^ \ + AES_FT3( ( Y0 >> 24 ) & 0xFF ); \ + \ + X2 = *RK++ ^ AES_FT0( ( Y2 ) & 0xFF ) ^ \ + AES_FT1( ( Y3 >> 8 ) & 0xFF ) ^ \ + AES_FT2( ( Y0 >> 16 ) & 0xFF ) ^ \ + AES_FT3( ( Y1 >> 24 ) & 0xFF ); \ + \ + X3 = *RK++ ^ AES_FT0( ( Y3 ) & 0xFF ) ^ \ + AES_FT1( ( Y0 >> 8 ) & 0xFF ) ^ \ + AES_FT2( ( Y1 >> 16 ) & 0xFF ) ^ \ + AES_FT3( ( Y2 >> 24 ) & 0xFF ); \ } -#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ -{ \ - X0 = *RK++ ^ RT0[ ( Y0 ) & 0xFF ] ^ \ - RT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y1 >> 24 ) & 0xFF ]; \ - \ - X1 = *RK++ ^ RT0[ ( Y1 ) & 0xFF ] ^ \ - RT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y2 >> 24 ) & 0xFF ]; \ - \ - X2 = *RK++ ^ RT0[ ( Y2 ) & 0xFF ] ^ \ - RT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y3 >> 24 ) & 0xFF ]; \ - \ - X3 = *RK++ ^ RT0[ ( Y3 ) & 0xFF ] ^ \ - RT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y0 >> 24 ) & 0xFF ]; \ +#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ +{ \ + X0 = *RK++ ^ AES_RT0( ( Y0 ) & 0xFF ) ^ \ + AES_RT1( ( Y3 >> 8 ) & 0xFF ) ^ \ + AES_RT2( ( Y2 >> 16 ) & 0xFF ) ^ \ + AES_RT3( ( Y1 >> 24 ) & 0xFF ); \ + \ + X1 = *RK++ ^ AES_RT0( ( Y1 ) & 0xFF ) ^ \ + AES_RT1( ( Y0 >> 8 ) & 0xFF ) ^ \ + AES_RT2( ( Y3 >> 16 ) & 0xFF ) ^ \ + AES_RT3( ( Y2 >> 24 ) & 0xFF ); \ + \ + X2 = *RK++ ^ AES_RT0( ( Y2 ) & 0xFF ) ^ \ + AES_RT1( ( Y1 >> 8 ) & 0xFF ) ^ \ + AES_RT2( ( Y0 >> 16 ) & 0xFF ) ^ \ + AES_RT3( ( Y3 >> 24 ) & 0xFF ); \ + \ + X3 = *RK++ ^ AES_RT0( ( Y3 ) & 0xFF ) ^ \ + AES_RT1( ( Y2 >> 8 ) & 0xFF ) ^ \ + AES_RT2( ( Y1 >> 16 ) & 0xFF ) ^ \ + AES_RT3( ( Y0 >> 24 ) & 0xFF ); \ } /* @@ -1034,6 +1078,9 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, int c, i; size_t n = *nc_off; + if ( n > 0x0F ) + return( MBEDTLS_ERR_AES_BAD_INPUT_DATA ); + while( length-- ) { if( n == 0 ) { diff --git a/thirdparty/mbedtls/library/aesni.c b/thirdparty/mbedtls/library/aesni.c index 1ca3c3ef5b..062708b047 100644 --- a/thirdparty/mbedtls/library/aesni.c +++ b/thirdparty/mbedtls/library/aesni.c @@ -32,6 +32,12 @@ #if defined(MBEDTLS_AESNI_C) +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) +#warning "MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code." +#endif +#endif + #include "mbedtls/aesni.h" #include <string.h> diff --git a/thirdparty/mbedtls/library/arc4.c b/thirdparty/mbedtls/library/arc4.c index 05b33d3fdb..b8998ac6cd 100644 --- a/thirdparty/mbedtls/library/arc4.c +++ b/thirdparty/mbedtls/library/arc4.c @@ -33,6 +33,7 @@ #if defined(MBEDTLS_ARC4_C) #include "mbedtls/arc4.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -47,11 +48,6 @@ #if !defined(MBEDTLS_ARC4_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - void mbedtls_arc4_init( mbedtls_arc4_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_arc4_context ) ); @@ -62,7 +58,7 @@ void mbedtls_arc4_free( mbedtls_arc4_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_arc4_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_arc4_context ) ); } /* diff --git a/thirdparty/mbedtls/library/aria.c b/thirdparty/mbedtls/library/aria.c new file mode 100644 index 0000000000..e9bcd6d135 --- /dev/null +++ b/thirdparty/mbedtls/library/aria.c @@ -0,0 +1,1028 @@ +/* + * ARIA implementation + * + * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * 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. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +/* + * This implementation is based on the following standards: + * [1] http://210.104.33.10/ARIA/doc/ARIA-specification-e.pdf + * [2] https://tools.ietf.org/html/rfc5794 + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_ARIA_C) + +#include "mbedtls/aria.h" + +#include <string.h> + +#if defined(MBEDTLS_SELF_TEST) +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#else +#include <stdio.h> +#define mbedtls_printf printf +#endif /* MBEDTLS_PLATFORM_C */ +#endif /* MBEDTLS_SELF_TEST */ + +#if !defined(MBEDTLS_ARIA_ALT) + +#include "mbedtls/platform_util.h" + +#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ + !defined(inline) && !defined(__cplusplus) +#define inline __inline +#endif + +/* + * 32-bit integer manipulation macros (little endian) + */ +#ifndef GET_UINT32_LE +#define GET_UINT32_LE( n, b, i ) \ +{ \ + (n) = ( (uint32_t) (b)[(i) ] ) \ + | ( (uint32_t) (b)[(i) + 1] << 8 ) \ + | ( (uint32_t) (b)[(i) + 2] << 16 ) \ + | ( (uint32_t) (b)[(i) + 3] << 24 ); \ +} +#endif + +#ifndef PUT_UINT32_LE +#define PUT_UINT32_LE( n, b, i ) \ +{ \ + (b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \ + (b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \ + (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \ + (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \ +} +#endif + +/* + * modify byte order: ( A B C D ) -> ( B A D C ), i.e. swap pairs of bytes + * + * This is submatrix P1 in [1] Appendix B.1 + * + * Common compilers fail to translate this to minimal number of instructions, + * so let's provide asm versions for common platforms with C fallback. + */ +#if defined(MBEDTLS_HAVE_ASM) +#if defined(__arm__) /* rev16 available from v6 up */ +/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */ +#if defined(__GNUC__) && \ + ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \ + __ARM_ARCH >= 6 +static inline uint32_t aria_p1( uint32_t x ) +{ + uint32_t r; + __asm( "rev16 %0, %1" : "=l" (r) : "l" (x) ); + return( r ); +} +#define ARIA_P1 aria_p1 +#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \ + ( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 ) +static inline uint32_t aria_p1( uint32_t x ) +{ + uint32_t r; + __asm( "rev16 r, x" ); + return( r ); +} +#define ARIA_P1 aria_p1 +#endif +#endif /* arm */ +#if defined(__GNUC__) && \ + defined(__i386__) || defined(__amd64__) || defined( __x86_64__) +/* I couldn't find an Intel equivalent of rev16, so two instructions */ +#define ARIA_P1(x) ARIA_P2( ARIA_P3( x ) ) +#endif /* x86 gnuc */ +#endif /* MBEDTLS_HAVE_ASM && GNUC */ +#if !defined(ARIA_P1) +#define ARIA_P1(x) ((((x) >> 8) & 0x00FF00FF) ^ (((x) & 0x00FF00FF) << 8)) +#endif + +/* + * modify byte order: ( A B C D ) -> ( C D A B ), i.e. rotate by 16 bits + * + * This is submatrix P2 in [1] Appendix B.1 + * + * Common compilers will translate this to a single instruction. + */ +#define ARIA_P2(x) (((x) >> 16) ^ ((x) << 16)) + +/* + * modify byte order: ( A B C D ) -> ( D C B A ), i.e. change endianness + * + * This is submatrix P3 in [1] Appendix B.1 + * + * Some compilers fail to translate this to a single instruction, + * so let's provide asm versions for common platforms with C fallback. + */ +#if defined(MBEDTLS_HAVE_ASM) +#if defined(__arm__) /* rev available from v6 up */ +/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */ +#if defined(__GNUC__) && \ + ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \ + __ARM_ARCH >= 6 +static inline uint32_t aria_p3( uint32_t x ) +{ + uint32_t r; + __asm( "rev %0, %1" : "=l" (r) : "l" (x) ); + return( r ); +} +#define ARIA_P3 aria_p3 +#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \ + ( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 ) +static inline uint32_t aria_p3( uint32_t x ) +{ + uint32_t r; + __asm( "rev r, x" ); + return( r ); +} +#define ARIA_P3 aria_p3 +#endif +#endif /* arm */ +#if defined(__GNUC__) && \ + defined(__i386__) || defined(__amd64__) || defined( __x86_64__) +static inline uint32_t aria_p3( uint32_t x ) +{ + __asm( "bswap %0" : "=r" (x) : "0" (x) ); + return( x ); +} +#define ARIA_P3 aria_p3 +#endif /* x86 gnuc */ +#endif /* MBEDTLS_HAVE_ASM && GNUC */ +#if !defined(ARIA_P3) +#define ARIA_P3(x) ARIA_P2( ARIA_P1 ( x ) ) +#endif + +/* + * ARIA Affine Transform + * (a, b, c, d) = state in/out + * + * If we denote the first byte of input by 0, ..., the last byte by f, + * then inputs are: a = 0123, b = 4567, c = 89ab, d = cdef. + * + * Reading [1] 2.4 or [2] 2.4.3 in columns and performing simple + * rearrangements on adjacent pairs, output is: + * + * a = 3210 + 4545 + 6767 + 88aa + 99bb + dccd + effe + * = 3210 + 4567 + 6745 + 89ab + 98ba + dcfe + efcd + * b = 0101 + 2323 + 5476 + 8998 + baab + eecc + ffdd + * = 0123 + 2301 + 5476 + 89ab + ba98 + efcd + fedc + * c = 0022 + 1133 + 4554 + 7667 + ab89 + dcdc + fefe + * = 0123 + 1032 + 4567 + 7654 + ab89 + dcfe + fedc + * d = 1001 + 2332 + 6644 + 7755 + 9898 + baba + cdef + * = 1032 + 2301 + 6745 + 7654 + 98ba + ba98 + cdef + * + * Note: another presentation of the A transform can be found as the first + * half of App. B.1 in [1] in terms of 4-byte operators P1, P2, P3 and P4. + * The implementation below uses only P1 and P2 as they are sufficient. + */ +static inline void aria_a( uint32_t *a, uint32_t *b, + uint32_t *c, uint32_t *d ) +{ + uint32_t ta, tb, tc; + ta = *b; // 4567 + *b = *a; // 0123 + *a = ARIA_P2( ta ); // 6745 + tb = ARIA_P2( *d ); // efcd + *d = ARIA_P1( *c ); // 98ba + *c = ARIA_P1( tb ); // fedc + ta ^= *d; // 4567+98ba + tc = ARIA_P2( *b ); // 2301 + ta = ARIA_P1( ta ) ^ tc ^ *c; // 2301+5476+89ab+fedc + tb ^= ARIA_P2( *d ); // ba98+efcd + tc ^= ARIA_P1( *a ); // 2301+7654 + *b ^= ta ^ tb; // 0123+2301+5476+89ab+ba98+efcd+fedc OUT + tb = ARIA_P2( tb ) ^ ta; // 2301+5476+89ab+98ba+cdef+fedc + *a ^= ARIA_P1( tb ); // 3210+4567+6745+89ab+98ba+dcfe+efcd OUT + ta = ARIA_P2( ta ); // 0123+7654+ab89+dcfe + *d ^= ARIA_P1( ta ) ^ tc; // 1032+2301+6745+7654+98ba+ba98+cdef OUT + tc = ARIA_P2( tc ); // 0123+5476 + *c ^= ARIA_P1( tc ) ^ ta; // 0123+1032+4567+7654+ab89+dcfe+fedc OUT +} + +/* + * ARIA Substitution Layer SL1 / SL2 + * (a, b, c, d) = state in/out + * (sa, sb, sc, sd) = 256 8-bit S-Boxes (see below) + * + * By passing sb1, sb2, is1, is2 as S-Boxes you get SL1 + * By passing is1, is2, sb1, sb2 as S-Boxes you get SL2 + */ +static inline void aria_sl( uint32_t *a, uint32_t *b, + uint32_t *c, uint32_t *d, + const uint8_t sa[256], const uint8_t sb[256], + const uint8_t sc[256], const uint8_t sd[256] ) +{ + *a = ( (uint32_t) sa[ *a & 0xFF] ) ^ + (((uint32_t) sb[(*a >> 8) & 0xFF]) << 8) ^ + (((uint32_t) sc[(*a >> 16) & 0xFF]) << 16) ^ + (((uint32_t) sd[ *a >> 24 ]) << 24); + *b = ( (uint32_t) sa[ *b & 0xFF] ) ^ + (((uint32_t) sb[(*b >> 8) & 0xFF]) << 8) ^ + (((uint32_t) sc[(*b >> 16) & 0xFF]) << 16) ^ + (((uint32_t) sd[ *b >> 24 ]) << 24); + *c = ( (uint32_t) sa[ *c & 0xFF] ) ^ + (((uint32_t) sb[(*c >> 8) & 0xFF]) << 8) ^ + (((uint32_t) sc[(*c >> 16) & 0xFF]) << 16) ^ + (((uint32_t) sd[ *c >> 24 ]) << 24); + *d = ( (uint32_t) sa[ *d & 0xFF] ) ^ + (((uint32_t) sb[(*d >> 8) & 0xFF]) << 8) ^ + (((uint32_t) sc[(*d >> 16) & 0xFF]) << 16) ^ + (((uint32_t) sd[ *d >> 24 ]) << 24); +} + +/* + * S-Boxes + */ +static const uint8_t aria_sb1[256] = +{ + 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, + 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, + 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, + 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, + 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, + 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, + 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, + 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, + 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, + 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, + 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, + 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, + 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, + 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, + 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, + 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, + 0xB0, 0x54, 0xBB, 0x16 +}; + +static const uint8_t aria_sb2[256] = +{ + 0xE2, 0x4E, 0x54, 0xFC, 0x94, 0xC2, 0x4A, 0xCC, 0x62, 0x0D, 0x6A, 0x46, + 0x3C, 0x4D, 0x8B, 0xD1, 0x5E, 0xFA, 0x64, 0xCB, 0xB4, 0x97, 0xBE, 0x2B, + 0xBC, 0x77, 0x2E, 0x03, 0xD3, 0x19, 0x59, 0xC1, 0x1D, 0x06, 0x41, 0x6B, + 0x55, 0xF0, 0x99, 0x69, 0xEA, 0x9C, 0x18, 0xAE, 0x63, 0xDF, 0xE7, 0xBB, + 0x00, 0x73, 0x66, 0xFB, 0x96, 0x4C, 0x85, 0xE4, 0x3A, 0x09, 0x45, 0xAA, + 0x0F, 0xEE, 0x10, 0xEB, 0x2D, 0x7F, 0xF4, 0x29, 0xAC, 0xCF, 0xAD, 0x91, + 0x8D, 0x78, 0xC8, 0x95, 0xF9, 0x2F, 0xCE, 0xCD, 0x08, 0x7A, 0x88, 0x38, + 0x5C, 0x83, 0x2A, 0x28, 0x47, 0xDB, 0xB8, 0xC7, 0x93, 0xA4, 0x12, 0x53, + 0xFF, 0x87, 0x0E, 0x31, 0x36, 0x21, 0x58, 0x48, 0x01, 0x8E, 0x37, 0x74, + 0x32, 0xCA, 0xE9, 0xB1, 0xB7, 0xAB, 0x0C, 0xD7, 0xC4, 0x56, 0x42, 0x26, + 0x07, 0x98, 0x60, 0xD9, 0xB6, 0xB9, 0x11, 0x40, 0xEC, 0x20, 0x8C, 0xBD, + 0xA0, 0xC9, 0x84, 0x04, 0x49, 0x23, 0xF1, 0x4F, 0x50, 0x1F, 0x13, 0xDC, + 0xD8, 0xC0, 0x9E, 0x57, 0xE3, 0xC3, 0x7B, 0x65, 0x3B, 0x02, 0x8F, 0x3E, + 0xE8, 0x25, 0x92, 0xE5, 0x15, 0xDD, 0xFD, 0x17, 0xA9, 0xBF, 0xD4, 0x9A, + 0x7E, 0xC5, 0x39, 0x67, 0xFE, 0x76, 0x9D, 0x43, 0xA7, 0xE1, 0xD0, 0xF5, + 0x68, 0xF2, 0x1B, 0x34, 0x70, 0x05, 0xA3, 0x8A, 0xD5, 0x79, 0x86, 0xA8, + 0x30, 0xC6, 0x51, 0x4B, 0x1E, 0xA6, 0x27, 0xF6, 0x35, 0xD2, 0x6E, 0x24, + 0x16, 0x82, 0x5F, 0xDA, 0xE6, 0x75, 0xA2, 0xEF, 0x2C, 0xB2, 0x1C, 0x9F, + 0x5D, 0x6F, 0x80, 0x0A, 0x72, 0x44, 0x9B, 0x6C, 0x90, 0x0B, 0x5B, 0x33, + 0x7D, 0x5A, 0x52, 0xF3, 0x61, 0xA1, 0xF7, 0xB0, 0xD6, 0x3F, 0x7C, 0x6D, + 0xED, 0x14, 0xE0, 0xA5, 0x3D, 0x22, 0xB3, 0xF8, 0x89, 0xDE, 0x71, 0x1A, + 0xAF, 0xBA, 0xB5, 0x81 +}; + +static const uint8_t aria_is1[256] = +{ + 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, + 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, + 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, + 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, + 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, + 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, + 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, + 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, + 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, + 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, + 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, + 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, + 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, + 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, + 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, + 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, + 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, + 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, + 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, + 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, + 0x55, 0x21, 0x0C, 0x7D +}; + +static const uint8_t aria_is2[256] = +{ + 0x30, 0x68, 0x99, 0x1B, 0x87, 0xB9, 0x21, 0x78, 0x50, 0x39, 0xDB, 0xE1, + 0x72, 0x09, 0x62, 0x3C, 0x3E, 0x7E, 0x5E, 0x8E, 0xF1, 0xA0, 0xCC, 0xA3, + 0x2A, 0x1D, 0xFB, 0xB6, 0xD6, 0x20, 0xC4, 0x8D, 0x81, 0x65, 0xF5, 0x89, + 0xCB, 0x9D, 0x77, 0xC6, 0x57, 0x43, 0x56, 0x17, 0xD4, 0x40, 0x1A, 0x4D, + 0xC0, 0x63, 0x6C, 0xE3, 0xB7, 0xC8, 0x64, 0x6A, 0x53, 0xAA, 0x38, 0x98, + 0x0C, 0xF4, 0x9B, 0xED, 0x7F, 0x22, 0x76, 0xAF, 0xDD, 0x3A, 0x0B, 0x58, + 0x67, 0x88, 0x06, 0xC3, 0x35, 0x0D, 0x01, 0x8B, 0x8C, 0xC2, 0xE6, 0x5F, + 0x02, 0x24, 0x75, 0x93, 0x66, 0x1E, 0xE5, 0xE2, 0x54, 0xD8, 0x10, 0xCE, + 0x7A, 0xE8, 0x08, 0x2C, 0x12, 0x97, 0x32, 0xAB, 0xB4, 0x27, 0x0A, 0x23, + 0xDF, 0xEF, 0xCA, 0xD9, 0xB8, 0xFA, 0xDC, 0x31, 0x6B, 0xD1, 0xAD, 0x19, + 0x49, 0xBD, 0x51, 0x96, 0xEE, 0xE4, 0xA8, 0x41, 0xDA, 0xFF, 0xCD, 0x55, + 0x86, 0x36, 0xBE, 0x61, 0x52, 0xF8, 0xBB, 0x0E, 0x82, 0x48, 0x69, 0x9A, + 0xE0, 0x47, 0x9E, 0x5C, 0x04, 0x4B, 0x34, 0x15, 0x79, 0x26, 0xA7, 0xDE, + 0x29, 0xAE, 0x92, 0xD7, 0x84, 0xE9, 0xD2, 0xBA, 0x5D, 0xF3, 0xC5, 0xB0, + 0xBF, 0xA4, 0x3B, 0x71, 0x44, 0x46, 0x2B, 0xFC, 0xEB, 0x6F, 0xD5, 0xF6, + 0x14, 0xFE, 0x7C, 0x70, 0x5A, 0x7D, 0xFD, 0x2F, 0x18, 0x83, 0x16, 0xA5, + 0x91, 0x1F, 0x05, 0x95, 0x74, 0xA9, 0xC1, 0x5B, 0x4A, 0x85, 0x6D, 0x13, + 0x07, 0x4F, 0x4E, 0x45, 0xB2, 0x0F, 0xC9, 0x1C, 0xA6, 0xBC, 0xEC, 0x73, + 0x90, 0x7B, 0xCF, 0x59, 0x8F, 0xA1, 0xF9, 0x2D, 0xF2, 0xB1, 0x00, 0x94, + 0x37, 0x9F, 0xD0, 0x2E, 0x9C, 0x6E, 0x28, 0x3F, 0x80, 0xF0, 0x3D, 0xD3, + 0x25, 0x8A, 0xB5, 0xE7, 0x42, 0xB3, 0xC7, 0xEA, 0xF7, 0x4C, 0x11, 0x33, + 0x03, 0xA2, 0xAC, 0x60 +}; + +/* + * Helper for key schedule: r = FO( p, k ) ^ x + */ +static void aria_fo_xor( uint32_t r[4], const uint32_t p[4], + const uint32_t k[4], const uint32_t x[4] ) +{ + uint32_t a, b, c, d; + + a = p[0] ^ k[0]; + b = p[1] ^ k[1]; + c = p[2] ^ k[2]; + d = p[3] ^ k[3]; + + aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 ); + aria_a( &a, &b, &c, &d ); + + r[0] = a ^ x[0]; + r[1] = b ^ x[1]; + r[2] = c ^ x[2]; + r[3] = d ^ x[3]; +} + +/* + * Helper for key schedule: r = FE( p, k ) ^ x + */ +static void aria_fe_xor( uint32_t r[4], const uint32_t p[4], + const uint32_t k[4], const uint32_t x[4] ) +{ + uint32_t a, b, c, d; + + a = p[0] ^ k[0]; + b = p[1] ^ k[1]; + c = p[2] ^ k[2]; + d = p[3] ^ k[3]; + + aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 ); + aria_a( &a, &b, &c, &d ); + + r[0] = a ^ x[0]; + r[1] = b ^ x[1]; + r[2] = c ^ x[2]; + r[3] = d ^ x[3]; +} + +/* + * Big endian 128-bit rotation: r = a ^ (b <<< n), used only in key setup. + * + * We chose to store bytes into 32-bit words in little-endian format (see + * GET/PUT_UINT32_LE) so we need to reverse bytes here. + */ +static void aria_rot128( uint32_t r[4], const uint32_t a[4], + const uint32_t b[4], uint8_t n ) +{ + uint8_t i, j; + uint32_t t, u; + + const uint8_t n1 = n % 32; // bit offset + const uint8_t n2 = n1 ? 32 - n1 : 0; // reverse bit offset + + j = ( n / 32 ) % 4; // initial word offset + t = ARIA_P3( b[j] ); // big endian + for( i = 0; i < 4; i++ ) + { + j = ( j + 1 ) % 4; // get next word, big endian + u = ARIA_P3( b[j] ); + t <<= n1; // rotate + t |= u >> n2; + t = ARIA_P3( t ); // back to little endian + r[i] = a[i] ^ t; // store + t = u; // move to next word + } +} + +/* + * Set encryption key + */ +int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx, + const unsigned char *key, unsigned int keybits ) +{ + /* round constant masks */ + const uint32_t rc[3][4] = + { + { 0xB7C17C51, 0x940A2227, 0xE8AB13FE, 0xE06E9AFA }, + { 0xCC4AB16D, 0x20C8219E, 0xD5B128FF, 0xB0E25DEF }, + { 0x1D3792DB, 0x70E92621, 0x75972403, 0x0EC9E804 } + }; + + int i; + uint32_t w[4][4], *w2; + + if( keybits != 128 && keybits != 192 && keybits != 256 ) + return( MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH ); + + /* Copy key to W0 (and potential remainder to W1) */ + GET_UINT32_LE( w[0][0], key, 0 ); + GET_UINT32_LE( w[0][1], key, 4 ); + GET_UINT32_LE( w[0][2], key, 8 ); + GET_UINT32_LE( w[0][3], key, 12 ); + + memset( w[1], 0, 16 ); + if( keybits >= 192 ) + { + GET_UINT32_LE( w[1][0], key, 16 ); // 192 bit key + GET_UINT32_LE( w[1][1], key, 20 ); + } + if( keybits == 256 ) + { + GET_UINT32_LE( w[1][2], key, 24 ); // 256 bit key + GET_UINT32_LE( w[1][3], key, 28 ); + } + + i = ( keybits - 128 ) >> 6; // index: 0, 1, 2 + ctx->nr = 12 + 2 * i; // no. rounds: 12, 14, 16 + + aria_fo_xor( w[1], w[0], rc[i], w[1] ); // W1 = FO(W0, CK1) ^ KR + i = i < 2 ? i + 1 : 0; + aria_fe_xor( w[2], w[1], rc[i], w[0] ); // W2 = FE(W1, CK2) ^ W0 + i = i < 2 ? i + 1 : 0; + aria_fo_xor( w[3], w[2], rc[i], w[1] ); // W3 = FO(W2, CK3) ^ W1 + + for( i = 0; i < 4; i++ ) // create round keys + { + w2 = w[(i + 1) & 3]; + aria_rot128( ctx->rk[i ], w[i], w2, 128 - 19 ); + aria_rot128( ctx->rk[i + 4], w[i], w2, 128 - 31 ); + aria_rot128( ctx->rk[i + 8], w[i], w2, 61 ); + aria_rot128( ctx->rk[i + 12], w[i], w2, 31 ); + } + aria_rot128( ctx->rk[16], w[0], w[1], 19 ); + + /* w holds enough info to reconstruct the round keys */ + mbedtls_platform_zeroize( w, sizeof( w ) ); + + return( 0 ); +} + +/* + * Set decryption key + */ +int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx, + const unsigned char *key, unsigned int keybits ) +{ + int i, j, k, ret; + + ret = mbedtls_aria_setkey_enc( ctx, key, keybits ); + if( ret != 0 ) + return( ret ); + + /* flip the order of round keys */ + for( i = 0, j = ctx->nr; i < j; i++, j-- ) + { + for( k = 0; k < 4; k++ ) + { + uint32_t t = ctx->rk[i][k]; + ctx->rk[i][k] = ctx->rk[j][k]; + ctx->rk[j][k] = t; + } + } + + /* apply affine transform to middle keys */ + for( i = 1; i < ctx->nr; i++ ) + { + aria_a( &ctx->rk[i][0], &ctx->rk[i][1], + &ctx->rk[i][2], &ctx->rk[i][3] ); + } + + return( 0 ); +} + +/* + * Encrypt a block + */ +int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx, + const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] ) +{ + int i; + + uint32_t a, b, c, d; + + GET_UINT32_LE( a, input, 0 ); + GET_UINT32_LE( b, input, 4 ); + GET_UINT32_LE( c, input, 8 ); + GET_UINT32_LE( d, input, 12 ); + + i = 0; + while( 1 ) + { + a ^= ctx->rk[i][0]; + b ^= ctx->rk[i][1]; + c ^= ctx->rk[i][2]; + d ^= ctx->rk[i][3]; + i++; + + aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 ); + aria_a( &a, &b, &c, &d ); + + a ^= ctx->rk[i][0]; + b ^= ctx->rk[i][1]; + c ^= ctx->rk[i][2]; + d ^= ctx->rk[i][3]; + i++; + + aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 ); + if( i >= ctx->nr ) + break; + aria_a( &a, &b, &c, &d ); + } + + /* final key mixing */ + a ^= ctx->rk[i][0]; + b ^= ctx->rk[i][1]; + c ^= ctx->rk[i][2]; + d ^= ctx->rk[i][3]; + + PUT_UINT32_LE( a, output, 0 ); + PUT_UINT32_LE( b, output, 4 ); + PUT_UINT32_LE( c, output, 8 ); + PUT_UINT32_LE( d, output, 12 ); + + return( 0 ); +} + +/* Initialize context */ +void mbedtls_aria_init( mbedtls_aria_context *ctx ) +{ + memset( ctx, 0, sizeof( mbedtls_aria_context ) ); +} + +/* Clear context */ +void mbedtls_aria_free( mbedtls_aria_context *ctx ) +{ + if( ctx == NULL ) + return; + + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aria_context ) ); +} + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/* + * ARIA-CBC buffer encryption/decryption + */ +int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx, + int mode, + size_t length, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ) +{ + int i; + unsigned char temp[MBEDTLS_ARIA_BLOCKSIZE]; + + if( length % MBEDTLS_ARIA_BLOCKSIZE ) + return( MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH ); + + if( mode == MBEDTLS_ARIA_DECRYPT ) + { + while( length > 0 ) + { + memcpy( temp, input, MBEDTLS_ARIA_BLOCKSIZE ); + mbedtls_aria_crypt_ecb( ctx, input, output ); + + for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ ) + output[i] = (unsigned char)( output[i] ^ iv[i] ); + + memcpy( iv, temp, MBEDTLS_ARIA_BLOCKSIZE ); + + input += MBEDTLS_ARIA_BLOCKSIZE; + output += MBEDTLS_ARIA_BLOCKSIZE; + length -= MBEDTLS_ARIA_BLOCKSIZE; + } + } + else + { + while( length > 0 ) + { + for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ ) + output[i] = (unsigned char)( input[i] ^ iv[i] ); + + mbedtls_aria_crypt_ecb( ctx, output, output ); + memcpy( iv, output, MBEDTLS_ARIA_BLOCKSIZE ); + + input += MBEDTLS_ARIA_BLOCKSIZE; + output += MBEDTLS_ARIA_BLOCKSIZE; + length -= MBEDTLS_ARIA_BLOCKSIZE; + } + } + + return( 0 ); +} +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/* + * ARIA-CFB128 buffer encryption/decryption + */ +int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ) +{ + unsigned char c; + size_t n = *iv_off; + + if( mode == MBEDTLS_ARIA_DECRYPT ) + { + while( length-- ) + { + if( n == 0 ) + mbedtls_aria_crypt_ecb( ctx, iv, iv ); + + c = *input++; + *output++ = c ^ iv[n]; + iv[n] = c; + + n = ( n + 1 ) & 0x0F; + } + } + else + { + while( length-- ) + { + if( n == 0 ) + mbedtls_aria_crypt_ecb( ctx, iv, iv ); + + iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ ); + + n = ( n + 1 ) & 0x0F; + } + } + + *iv_off = n; + + return( 0 ); +} +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/* + * ARIA-CTR buffer encryption/decryption + */ +int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ) +{ + int c, i; + size_t n = *nc_off; + + while( length-- ) + { + if( n == 0 ) { + mbedtls_aria_crypt_ecb( ctx, nonce_counter, + stream_block ); + + for( i = MBEDTLS_ARIA_BLOCKSIZE; i > 0; i-- ) + if( ++nonce_counter[i - 1] != 0 ) + break; + } + c = *input++; + *output++ = (unsigned char)( c ^ stream_block[n] ); + + n = ( n + 1 ) & 0x0F; + } + + *nc_off = n; + + return( 0 ); +} +#endif /* MBEDTLS_CIPHER_MODE_CTR */ +#endif /* !MBEDTLS_ARIA_ALT */ + +#if defined(MBEDTLS_SELF_TEST) + +/* + * Basic ARIA ECB test vectors from RFC 5794 + */ +static const uint8_t aria_test1_ecb_key[32] = // test key +{ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 128 bit + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // 192 bit + 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F // 256 bit +}; + +static const uint8_t aria_test1_ecb_pt[MBEDTLS_ARIA_BLOCKSIZE] = // plaintext +{ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // same for all + 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF // key sizes +}; + +static const uint8_t aria_test1_ecb_ct[3][MBEDTLS_ARIA_BLOCKSIZE] = // ciphertext +{ + { 0xD7, 0x18, 0xFB, 0xD6, 0xAB, 0x64, 0x4C, 0x73, // 128 bit + 0x9D, 0xA9, 0x5F, 0x3B, 0xE6, 0x45, 0x17, 0x78 }, + { 0x26, 0x44, 0x9C, 0x18, 0x05, 0xDB, 0xE7, 0xAA, // 192 bit + 0x25, 0xA4, 0x68, 0xCE, 0x26, 0x3A, 0x9E, 0x79 }, + { 0xF9, 0x2B, 0xD7, 0xC7, 0x9F, 0xB7, 0x2E, 0x2F, // 256 bit + 0x2B, 0x8F, 0x80, 0xC1, 0x97, 0x2D, 0x24, 0xFC } +}; + +/* + * Mode tests from "Test Vectors for ARIA" Version 1.0 + * http://210.104.33.10/ARIA/doc/ARIA-testvector-e.pdf + */ +#if (defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB) || \ + defined(MBEDTLS_CIPHER_MODE_CTR)) +static const uint8_t aria_test2_key[32] = +{ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // 128 bit + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // 192 bit + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff // 256 bit +}; + +static const uint8_t aria_test2_pt[48] = +{ + 0x11, 0x11, 0x11, 0x11, 0xaa, 0xaa, 0xaa, 0xaa, // same for all + 0x11, 0x11, 0x11, 0x11, 0xbb, 0xbb, 0xbb, 0xbb, + 0x11, 0x11, 0x11, 0x11, 0xcc, 0xcc, 0xcc, 0xcc, + 0x11, 0x11, 0x11, 0x11, 0xdd, 0xdd, 0xdd, 0xdd, + 0x22, 0x22, 0x22, 0x22, 0xaa, 0xaa, 0xaa, 0xaa, + 0x22, 0x22, 0x22, 0x22, 0xbb, 0xbb, 0xbb, 0xbb, +}; +#endif + +#if (defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB)) +static const uint8_t aria_test2_iv[MBEDTLS_ARIA_BLOCKSIZE] = +{ + 0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78, // same for CBC, CFB + 0x87, 0x96, 0xa5, 0xb4, 0xc3, 0xd2, 0xe1, 0xf0 // CTR has zero IV +}; +#endif + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +static const uint8_t aria_test2_cbc_ct[3][48] = // CBC ciphertext +{ + { 0x49, 0xd6, 0x18, 0x60, 0xb1, 0x49, 0x09, 0x10, // 128-bit key + 0x9c, 0xef, 0x0d, 0x22, 0xa9, 0x26, 0x81, 0x34, + 0xfa, 0xdf, 0x9f, 0xb2, 0x31, 0x51, 0xe9, 0x64, + 0x5f, 0xba, 0x75, 0x01, 0x8b, 0xdb, 0x15, 0x38, + 0xb5, 0x33, 0x34, 0x63, 0x4b, 0xbf, 0x7d, 0x4c, + 0xd4, 0xb5, 0x37, 0x70, 0x33, 0x06, 0x0c, 0x15 }, + { 0xaf, 0xe6, 0xcf, 0x23, 0x97, 0x4b, 0x53, 0x3c, // 192-bit key + 0x67, 0x2a, 0x82, 0x62, 0x64, 0xea, 0x78, 0x5f, + 0x4e, 0x4f, 0x7f, 0x78, 0x0d, 0xc7, 0xf3, 0xf1, + 0xe0, 0x96, 0x2b, 0x80, 0x90, 0x23, 0x86, 0xd5, + 0x14, 0xe9, 0xc3, 0xe7, 0x72, 0x59, 0xde, 0x92, + 0xdd, 0x11, 0x02, 0xff, 0xab, 0x08, 0x6c, 0x1e }, + { 0x52, 0x3a, 0x8a, 0x80, 0x6a, 0xe6, 0x21, 0xf1, // 256-bit key + 0x55, 0xfd, 0xd2, 0x8d, 0xbc, 0x34, 0xe1, 0xab, + 0x7b, 0x9b, 0x42, 0x43, 0x2a, 0xd8, 0xb2, 0xef, + 0xb9, 0x6e, 0x23, 0xb1, 0x3f, 0x0a, 0x6e, 0x52, + 0xf3, 0x61, 0x85, 0xd5, 0x0a, 0xd0, 0x02, 0xc5, + 0xf6, 0x01, 0xbe, 0xe5, 0x49, 0x3f, 0x11, 0x8b } +}; +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +static const uint8_t aria_test2_cfb_ct[3][48] = // CFB ciphertext +{ + { 0x37, 0x20, 0xe5, 0x3b, 0xa7, 0xd6, 0x15, 0x38, // 128-bit key + 0x34, 0x06, 0xb0, 0x9f, 0x0a, 0x05, 0xa2, 0x00, + 0xc0, 0x7c, 0x21, 0xe6, 0x37, 0x0f, 0x41, 0x3a, + 0x5d, 0x13, 0x25, 0x00, 0xa6, 0x82, 0x85, 0x01, + 0x7c, 0x61, 0xb4, 0x34, 0xc7, 0xb7, 0xca, 0x96, + 0x85, 0xa5, 0x10, 0x71, 0x86, 0x1e, 0x4d, 0x4b }, + { 0x41, 0x71, 0xf7, 0x19, 0x2b, 0xf4, 0x49, 0x54, // 192-bit key + 0x94, 0xd2, 0x73, 0x61, 0x29, 0x64, 0x0f, 0x5c, + 0x4d, 0x87, 0xa9, 0xa2, 0x13, 0x66, 0x4c, 0x94, + 0x48, 0x47, 0x7c, 0x6e, 0xcc, 0x20, 0x13, 0x59, + 0x8d, 0x97, 0x66, 0x95, 0x2d, 0xd8, 0xc3, 0x86, + 0x8f, 0x17, 0xe3, 0x6e, 0xf6, 0x6f, 0xd8, 0x4b }, + { 0x26, 0x83, 0x47, 0x05, 0xb0, 0xf2, 0xc0, 0xe2, // 256-bit key + 0x58, 0x8d, 0x4a, 0x7f, 0x09, 0x00, 0x96, 0x35, + 0xf2, 0x8b, 0xb9, 0x3d, 0x8c, 0x31, 0xf8, 0x70, + 0xec, 0x1e, 0x0b, 0xdb, 0x08, 0x2b, 0x66, 0xfa, + 0x40, 0x2d, 0xd9, 0xc2, 0x02, 0xbe, 0x30, 0x0c, + 0x45, 0x17, 0xd1, 0x96, 0xb1, 0x4d, 0x4c, 0xe1 } +}; +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +static const uint8_t aria_test2_ctr_ct[3][48] = // CTR ciphertext +{ + { 0xac, 0x5d, 0x7d, 0xe8, 0x05, 0xa0, 0xbf, 0x1c, // 128-bit key + 0x57, 0xc8, 0x54, 0x50, 0x1a, 0xf6, 0x0f, 0xa1, + 0x14, 0x97, 0xe2, 0xa3, 0x45, 0x19, 0xde, 0xa1, + 0x56, 0x9e, 0x91, 0xe5, 0xb5, 0xcc, 0xae, 0x2f, + 0xf3, 0xbf, 0xa1, 0xbf, 0x97, 0x5f, 0x45, 0x71, + 0xf4, 0x8b, 0xe1, 0x91, 0x61, 0x35, 0x46, 0xc3 }, + { 0x08, 0x62, 0x5c, 0xa8, 0xfe, 0x56, 0x9c, 0x19, // 192-bit key + 0xba, 0x7a, 0xf3, 0x76, 0x0a, 0x6e, 0xd1, 0xce, + 0xf4, 0xd1, 0x99, 0x26, 0x3e, 0x99, 0x9d, 0xde, + 0x14, 0x08, 0x2d, 0xbb, 0xa7, 0x56, 0x0b, 0x79, + 0xa4, 0xc6, 0xb4, 0x56, 0xb8, 0x70, 0x7d, 0xce, + 0x75, 0x1f, 0x98, 0x54, 0xf1, 0x88, 0x93, 0xdf }, + { 0x30, 0x02, 0x6c, 0x32, 0x96, 0x66, 0x14, 0x17, // 256-bit key + 0x21, 0x17, 0x8b, 0x99, 0xc0, 0xa1, 0xf1, 0xb2, + 0xf0, 0x69, 0x40, 0x25, 0x3f, 0x7b, 0x30, 0x89, + 0xe2, 0xa3, 0x0e, 0xa8, 0x6a, 0xa3, 0xc8, 0x8f, + 0x59, 0x40, 0xf0, 0x5a, 0xd7, 0xee, 0x41, 0xd7, + 0x13, 0x47, 0xbb, 0x72, 0x61, 0xe3, 0x48, 0xf1 } +}; +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#define ARIA_SELF_TEST_IF_FAIL \ + { \ + if( verbose ) \ + printf( "failed\n" ); \ + return( 1 ); \ + } else { \ + if( verbose ) \ + printf( "passed\n" ); \ + } + +/* + * Checkup routine + */ +int mbedtls_aria_self_test( int verbose ) +{ + int i; + uint8_t blk[MBEDTLS_ARIA_BLOCKSIZE]; + mbedtls_aria_context ctx; + +#if (defined(MBEDTLS_CIPHER_MODE_CFB) || defined(MBEDTLS_CIPHER_MODE_CTR)) + size_t j; +#endif + +#if (defined(MBEDTLS_CIPHER_MODE_CBC) || \ + defined(MBEDTLS_CIPHER_MODE_CFB) || \ + defined(MBEDTLS_CIPHER_MODE_CTR)) + uint8_t buf[48], iv[MBEDTLS_ARIA_BLOCKSIZE]; +#endif + + /* + * Test set 1 + */ + for( i = 0; i < 3; i++ ) + { + /* test ECB encryption */ + if( verbose ) + printf( " ARIA-ECB-%d (enc): ", 128 + 64 * i ); + mbedtls_aria_setkey_enc( &ctx, aria_test1_ecb_key, 128 + 64 * i ); + mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_pt, blk ); + if( memcmp( blk, aria_test1_ecb_ct[i], MBEDTLS_ARIA_BLOCKSIZE ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + + /* test ECB decryption */ + if( verbose ) + printf( " ARIA-ECB-%d (dec): ", 128 + 64 * i ); + mbedtls_aria_setkey_dec( &ctx, aria_test1_ecb_key, 128 + 64 * i ); + mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_ct[i], blk ); + if( memcmp( blk, aria_test1_ecb_pt, MBEDTLS_ARIA_BLOCKSIZE ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + } + if( verbose ) + printf( "\n" ); + + /* + * Test set 2 + */ +#if defined(MBEDTLS_CIPHER_MODE_CBC) + for( i = 0; i < 3; i++ ) + { + /* Test CBC encryption */ + if( verbose ) + printf( " ARIA-CBC-%d (enc): ", 128 + 64 * i ); + mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i ); + memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE ); + memset( buf, 0x55, sizeof( buf ) ); + mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, iv, + aria_test2_pt, buf ); + if( memcmp( buf, aria_test2_cbc_ct[i], 48 ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + + /* Test CBC decryption */ + if( verbose ) + printf( " ARIA-CBC-%d (dec): ", 128 + 64 * i ); + mbedtls_aria_setkey_dec( &ctx, aria_test2_key, 128 + 64 * i ); + memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE ); + memset( buf, 0xAA, sizeof( buf ) ); + mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_DECRYPT, 48, iv, + aria_test2_cbc_ct[i], buf ); + if( memcmp( buf, aria_test2_pt, 48 ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + } + if( verbose ) + printf( "\n" ); + +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) + for( i = 0; i < 3; i++ ) + { + /* Test CFB encryption */ + if( verbose ) + printf( " ARIA-CFB-%d (enc): ", 128 + 64 * i ); + mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i ); + memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE ); + memset( buf, 0x55, sizeof( buf ) ); + j = 0; + mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, &j, iv, + aria_test2_pt, buf ); + if( memcmp( buf, aria_test2_cfb_ct[i], 48 ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + + /* Test CFB decryption */ + if( verbose ) + printf( " ARIA-CFB-%d (dec): ", 128 + 64 * i ); + mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i ); + memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE ); + memset( buf, 0xAA, sizeof( buf ) ); + j = 0; + mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_DECRYPT, 48, &j, + iv, aria_test2_cfb_ct[i], buf ); + if( memcmp( buf, aria_test2_pt, 48 ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + } + if( verbose ) + printf( "\n" ); +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) + for( i = 0; i < 3; i++ ) + { + /* Test CTR encryption */ + if( verbose ) + printf( " ARIA-CTR-%d (enc): ", 128 + 64 * i ); + mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i ); + memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE ); // IV = 0 + memset( buf, 0x55, sizeof( buf ) ); + j = 0; + mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk, + aria_test2_pt, buf ); + if( memcmp( buf, aria_test2_ctr_ct[i], 48 ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + + /* Test CTR decryption */ + if( verbose ) + printf( " ARIA-CTR-%d (dec): ", 128 + 64 * i ); + mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i ); + memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE ); // IV = 0 + memset( buf, 0xAA, sizeof( buf ) ); + j = 0; + mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk, + aria_test2_ctr_ct[i], buf ); + if( memcmp( buf, aria_test2_pt, 48 ) != 0 ) + ARIA_SELF_TEST_IF_FAIL; + } + if( verbose ) + printf( "\n" ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + + return( 0 ); +} + +#endif /* MBEDTLS_SELF_TEST */ + +#endif /* MBEDTLS_ARIA_C */ diff --git a/thirdparty/mbedtls/library/asn1parse.c b/thirdparty/mbedtls/library/asn1parse.c index 4dd65c03c0..171c340b8c 100644 --- a/thirdparty/mbedtls/library/asn1parse.c +++ b/thirdparty/mbedtls/library/asn1parse.c @@ -28,6 +28,7 @@ #if defined(MBEDTLS_ASN1_PARSE_C) #include "mbedtls/asn1.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -43,11 +44,6 @@ #define mbedtls_free free #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * ASN.1 DER decoding routines */ @@ -313,7 +309,7 @@ int mbedtls_asn1_get_alg( unsigned char **p, if( *p == end ) { - mbedtls_zeroize( params, sizeof(mbedtls_asn1_buf) ); + mbedtls_platform_zeroize( params, sizeof(mbedtls_asn1_buf) ); return( 0 ); } @@ -358,7 +354,7 @@ void mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *cur ) mbedtls_free( cur->oid.p ); mbedtls_free( cur->val.p ); - mbedtls_zeroize( cur, sizeof( mbedtls_asn1_named_data ) ); + mbedtls_platform_zeroize( cur, sizeof( mbedtls_asn1_named_data ) ); } void mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head ) diff --git a/thirdparty/mbedtls/library/asn1write.c b/thirdparty/mbedtls/library/asn1write.c index 69b61b205f..c01c836550 100644 --- a/thirdparty/mbedtls/library/asn1write.c +++ b/thirdparty/mbedtls/library/asn1write.c @@ -232,10 +232,6 @@ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val ) int ret; size_t len = 0; - // TODO negative values and values larger than 128 - // DER format assumes 2s complement for numbers, so the leftmost bit - // should be 0 for positive numbers and 1 for negative numbers. - // if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); diff --git a/thirdparty/mbedtls/library/bignum.c b/thirdparty/mbedtls/library/bignum.c index 9f13da4421..423e375fd1 100644 --- a/thirdparty/mbedtls/library/bignum.c +++ b/thirdparty/mbedtls/library/bignum.c @@ -45,6 +45,7 @@ #include "mbedtls/bignum.h" #include "mbedtls/bn_mul.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -58,16 +59,6 @@ #define mbedtls_free free #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n ) { - volatile mbedtls_mpi_uint *p = v; while( n-- ) *p++ = 0; -} - -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - #define ciL (sizeof(mbedtls_mpi_uint)) /* chars in limb */ #define biL (ciL << 3) /* bits in limb */ #define biH (ciL << 2) /* half limb size */ @@ -81,6 +72,12 @@ static void mbedtls_zeroize( void *v, size_t n ) { #define BITS_TO_LIMBS(i) ( (i) / biL + ( (i) % biL != 0 ) ) #define CHARS_TO_LIMBS(i) ( (i) / ciL + ( (i) % ciL != 0 ) ) +/* Implementation that should never be optimized out by the compiler */ +static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n ) +{ + mbedtls_platform_zeroize( v, ciL * n ); +} + /* * Initialize one MPI */ @@ -184,7 +181,7 @@ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs ) */ int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y ) { - int ret; + int ret = 0; size_t i; if( X == Y ) @@ -203,9 +200,15 @@ int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y ) X->s = Y->s; - MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) ); + if( X->n < i ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) ); + } + else + { + memset( X->p + i, 0, ( X->n - i ) * ciL ); + } - memset( X->p, 0, X->n * ciL ); memcpy( X->p, Y->p, i * ciL ); cleanup: @@ -963,7 +966,7 @@ static void mpi_sub_hlp( size_t n, mbedtls_mpi_uint *s, mbedtls_mpi_uint *d ) while( c != 0 ) { z = ( *d < c ); *d -= c; - c = z; i++; d++; + c = z; d++; } } @@ -1201,8 +1204,8 @@ int mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) ); - for( i++; j > 0; j-- ) - mpi_mul_hlp( i - 1, A->p, X->p + j - 1, B->p[j - 1] ); + for( ; j > 0; j-- ) + mpi_mul_hlp( i, A->p, X->p + j - 1, B->p[j - 1] ); X->s = A->s * B->s; @@ -1891,7 +1894,7 @@ int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size, MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( X, buf, size ) ); cleanup: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } @@ -2188,12 +2191,23 @@ int mbedtls_mpi_is_prime( const mbedtls_mpi *X, /* * Prime number generation + * + * If dh_flag is 0 and nbits is at least 1024, then the procedure + * follows the RSA probably-prime generation method of FIPS 186-4. + * NB. FIPS 186-4 only allows the specific bit lengths of 1024 and 1536. */ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { - int ret; +#ifdef MBEDTLS_HAVE_INT64 +// ceil(2^63.5) +#define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL +#else +// ceil(2^31.5) +#define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U +#endif + int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; size_t k, n; mbedtls_mpi_uint r; mbedtls_mpi Y; @@ -2205,69 +2219,66 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, n = BITS_TO_LIMBS( nbits ); - MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) ); - - k = mbedtls_mpi_bitlen( X ); - if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits + 1 ) ); - - mbedtls_mpi_set_bit( X, nbits-1, 1 ); + while( 1 ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) ); + /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */ + if( X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2 ) continue; - X->p[0] |= 1; + k = n * biL; + if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) ); + X->p[0] |= 1; - if( dh_flag == 0 ) - { - while( ( ret = mbedtls_mpi_is_prime( X, f_rng, p_rng ) ) != 0 ) + if( dh_flag == 0 ) { + ret = mbedtls_mpi_is_prime( X, f_rng, p_rng ); + if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) goto cleanup; - - MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 2 ) ); } - } - else - { - /* - * An necessary condition for Y and X = 2Y + 1 to be prime - * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3). - * Make sure it is satisfied, while keeping X = 3 mod 4 - */ + else + { + /* + * An necessary condition for Y and X = 2Y + 1 to be prime + * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3). + * Make sure it is satisfied, while keeping X = 3 mod 4 + */ - X->p[0] |= 2; + X->p[0] |= 2; - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) ); - if( r == 0 ) - MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) ); - else if( r == 1 ) - MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) ); + if( r == 0 ) + MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) ); + else if( r == 1 ) + MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) ); - /* Set Y = (X-1) / 2, which is X / 2 because X is odd */ - MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) ); + /* Set Y = (X-1) / 2, which is X / 2 because X is odd */ + MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) ); - while( 1 ) - { - /* - * First, check small factors for X and Y - * before doing Miller-Rabin on any of them - */ - if( ( ret = mpi_check_small_factors( X ) ) == 0 && - ( ret = mpi_check_small_factors( &Y ) ) == 0 && - ( ret = mpi_miller_rabin( X, f_rng, p_rng ) ) == 0 && - ( ret = mpi_miller_rabin( &Y, f_rng, p_rng ) ) == 0 ) + while( 1 ) { - break; + /* + * First, check small factors for X and Y + * before doing Miller-Rabin on any of them + */ + if( ( ret = mpi_check_small_factors( X ) ) == 0 && + ( ret = mpi_check_small_factors( &Y ) ) == 0 && + ( ret = mpi_miller_rabin( X, f_rng, p_rng ) ) == 0 && + ( ret = mpi_miller_rabin( &Y, f_rng, p_rng ) ) == 0 ) + goto cleanup; + + if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) + goto cleanup; + + /* + * Next candidates. We want to preserve Y = (X-1) / 2 and + * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3) + * so up Y by 6 and X by 12. + */ + MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 12 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6 ) ); } - - if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) - goto cleanup; - - /* - * Next candidates. We want to preserve Y = (X-1) / 2 and - * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3) - * so up Y by 6 and X by 12. - */ - MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 12 ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6 ) ); } } diff --git a/thirdparty/mbedtls/library/blowfish.c b/thirdparty/mbedtls/library/blowfish.c index 9003f0dfeb..5b6bb9885f 100644 --- a/thirdparty/mbedtls/library/blowfish.c +++ b/thirdparty/mbedtls/library/blowfish.c @@ -34,16 +34,12 @@ #if defined(MBEDTLS_BLOWFISH_C) #include "mbedtls/blowfish.h" +#include "mbedtls/platform_util.h" #include <string.h> #if !defined(MBEDTLS_BLOWFISH_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (big endian) */ @@ -165,7 +161,7 @@ void mbedtls_blowfish_free( mbedtls_blowfish_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_blowfish_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_blowfish_context ) ); } /* diff --git a/thirdparty/mbedtls/library/camellia.c b/thirdparty/mbedtls/library/camellia.c index ac6f96a83a..41b7da0fae 100644 --- a/thirdparty/mbedtls/library/camellia.c +++ b/thirdparty/mbedtls/library/camellia.c @@ -34,6 +34,7 @@ #if defined(MBEDTLS_CAMELLIA_C) #include "mbedtls/camellia.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -48,11 +49,6 @@ #if !defined(MBEDTLS_CAMELLIA_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (big endian) */ @@ -333,7 +329,7 @@ void mbedtls_camellia_free( mbedtls_camellia_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_camellia_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_camellia_context ) ); } /* diff --git a/thirdparty/mbedtls/library/ccm.c b/thirdparty/mbedtls/library/ccm.c index 9101e5f7c7..cf6520935e 100644 --- a/thirdparty/mbedtls/library/ccm.c +++ b/thirdparty/mbedtls/library/ccm.c @@ -37,6 +37,7 @@ #if defined(MBEDTLS_CCM_C) #include "mbedtls/ccm.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -51,11 +52,6 @@ #if !defined(MBEDTLS_CCM_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - #define CCM_ENCRYPT 0 #define CCM_DECRYPT 1 @@ -102,7 +98,7 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx, void mbedtls_ccm_free( mbedtls_ccm_context *ctx ) { mbedtls_cipher_free( &ctx->cipher_ctx ); - mbedtls_zeroize( ctx, sizeof( mbedtls_ccm_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) ); } /* @@ -343,7 +339,7 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, if( diff != 0 ) { - mbedtls_zeroize( output, length ); + mbedtls_platform_zeroize( output, length ); return( MBEDTLS_ERR_CCM_AUTH_FAILED ); } diff --git a/thirdparty/mbedtls/library/cipher.c b/thirdparty/mbedtls/library/cipher.c index ff0327380c..a5cd61cdf3 100644 --- a/thirdparty/mbedtls/library/cipher.c +++ b/thirdparty/mbedtls/library/cipher.c @@ -33,6 +33,7 @@ #include "mbedtls/cipher.h" #include "mbedtls/cipher_internal.h" +#include "mbedtls/platform_util.h" #include <stdlib.h> #include <string.h> @@ -60,11 +61,6 @@ #define MBEDTLS_CIPHER_MODE_STREAM #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - static int supported_init = 0; const int *mbedtls_cipher_list( void ) @@ -141,7 +137,8 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) #if defined(MBEDTLS_CMAC_C) if( ctx->cmac_ctx ) { - mbedtls_zeroize( ctx->cmac_ctx, sizeof( mbedtls_cmac_context_t ) ); + mbedtls_platform_zeroize( ctx->cmac_ctx, + sizeof( mbedtls_cmac_context_t ) ); mbedtls_free( ctx->cmac_ctx ); } #endif @@ -149,7 +146,7 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) if( ctx->cipher_ctx ) ctx->cipher_info->base->ctx_free_func( ctx->cipher_ctx ); - mbedtls_zeroize( ctx, sizeof(mbedtls_cipher_context_t) ); + mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) ); } int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ) @@ -325,8 +322,10 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i /* * If there is not enough data for a full block, cache it. */ - if( ( ctx->operation == MBEDTLS_DECRYPT && + if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding && ilen <= block_size - ctx->unprocessed_len ) || + ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding && + ilen < block_size - ctx->unprocessed_len ) || ( ctx->operation == MBEDTLS_ENCRYPT && ilen < block_size - ctx->unprocessed_len ) ) { @@ -372,9 +371,17 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT; } + /* Encryption: only cache partial blocks + * Decryption w/ padding: always keep at least one whole block + * Decryption w/o padding: only cache partial blocks + */ copy_len = ilen % block_size; - if( copy_len == 0 && ctx->operation == MBEDTLS_DECRYPT ) + if( copy_len == 0 && + ctx->operation == MBEDTLS_DECRYPT && + NULL != ctx->add_padding) + { copy_len = block_size; + } memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ), copy_len ); diff --git a/thirdparty/mbedtls/library/cipher_wrap.c b/thirdparty/mbedtls/library/cipher_wrap.c index dc76af8ff4..a9ef8195ca 100644 --- a/thirdparty/mbedtls/library/cipher_wrap.c +++ b/thirdparty/mbedtls/library/cipher_wrap.c @@ -45,6 +45,10 @@ #include "mbedtls/camellia.h" #endif +#if defined(MBEDTLS_ARIA_C) +#include "mbedtls/aria.h" +#endif + #if defined(MBEDTLS_DES_C) #include "mbedtls/des.h" #endif @@ -822,6 +826,364 @@ static const mbedtls_cipher_info_t camellia_256_ccm_info = { #endif /* MBEDTLS_CAMELLIA_C */ +#if defined(MBEDTLS_ARIA_C) + +static int aria_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation, + const unsigned char *input, unsigned char *output ) +{ + (void) operation; + return mbedtls_aria_crypt_ecb( (mbedtls_aria_context *) ctx, input, + output ); +} + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +static int aria_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, + size_t length, unsigned char *iv, + const unsigned char *input, unsigned char *output ) +{ + return mbedtls_aria_crypt_cbc( (mbedtls_aria_context *) ctx, operation, length, iv, + input, output ); +} +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +static int aria_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation, + size_t length, size_t *iv_off, unsigned char *iv, + const unsigned char *input, unsigned char *output ) +{ + return mbedtls_aria_crypt_cfb128( (mbedtls_aria_context *) ctx, operation, length, + iv_off, iv, input, output ); +} +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +static int aria_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off, + unsigned char *nonce_counter, unsigned char *stream_block, + const unsigned char *input, unsigned char *output ) +{ + return mbedtls_aria_crypt_ctr( (mbedtls_aria_context *) ctx, length, nc_off, + nonce_counter, stream_block, input, output ); +} +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +static int aria_setkey_dec_wrap( void *ctx, const unsigned char *key, + unsigned int key_bitlen ) +{ + return mbedtls_aria_setkey_dec( (mbedtls_aria_context *) ctx, key, key_bitlen ); +} + +static int aria_setkey_enc_wrap( void *ctx, const unsigned char *key, + unsigned int key_bitlen ) +{ + return mbedtls_aria_setkey_enc( (mbedtls_aria_context *) ctx, key, key_bitlen ); +} + +static void * aria_ctx_alloc( void ) +{ + mbedtls_aria_context *ctx; + ctx = mbedtls_calloc( 1, sizeof( mbedtls_aria_context ) ); + + if( ctx == NULL ) + return( NULL ); + + mbedtls_aria_init( ctx ); + + return( ctx ); +} + +static void aria_ctx_free( void *ctx ) +{ + mbedtls_aria_free( (mbedtls_aria_context *) ctx ); + mbedtls_free( ctx ); +} + +static const mbedtls_cipher_base_t aria_info = { + MBEDTLS_CIPHER_ID_ARIA, + aria_crypt_ecb_wrap, +#if defined(MBEDTLS_CIPHER_MODE_CBC) + aria_crypt_cbc_wrap, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CFB) + aria_crypt_cfb128_wrap, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CTR) + aria_crypt_ctr_wrap, +#endif +#if defined(MBEDTLS_CIPHER_MODE_STREAM) + NULL, +#endif + aria_setkey_enc_wrap, + aria_setkey_dec_wrap, + aria_ctx_alloc, + aria_ctx_free +}; + +static const mbedtls_cipher_info_t aria_128_ecb_info = { + MBEDTLS_CIPHER_ARIA_128_ECB, + MBEDTLS_MODE_ECB, + 128, + "ARIA-128-ECB", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_192_ecb_info = { + MBEDTLS_CIPHER_ARIA_192_ECB, + MBEDTLS_MODE_ECB, + 192, + "ARIA-192-ECB", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_256_ecb_info = { + MBEDTLS_CIPHER_ARIA_256_ECB, + MBEDTLS_MODE_ECB, + 256, + "ARIA-256-ECB", + 16, + 0, + 16, + &aria_info +}; + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +static const mbedtls_cipher_info_t aria_128_cbc_info = { + MBEDTLS_CIPHER_ARIA_128_CBC, + MBEDTLS_MODE_CBC, + 128, + "ARIA-128-CBC", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_192_cbc_info = { + MBEDTLS_CIPHER_ARIA_192_CBC, + MBEDTLS_MODE_CBC, + 192, + "ARIA-192-CBC", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_256_cbc_info = { + MBEDTLS_CIPHER_ARIA_256_CBC, + MBEDTLS_MODE_CBC, + 256, + "ARIA-256-CBC", + 16, + 0, + 16, + &aria_info +}; +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +static const mbedtls_cipher_info_t aria_128_cfb128_info = { + MBEDTLS_CIPHER_ARIA_128_CFB128, + MBEDTLS_MODE_CFB, + 128, + "ARIA-128-CFB128", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_192_cfb128_info = { + MBEDTLS_CIPHER_ARIA_192_CFB128, + MBEDTLS_MODE_CFB, + 192, + "ARIA-192-CFB128", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_256_cfb128_info = { + MBEDTLS_CIPHER_ARIA_256_CFB128, + MBEDTLS_MODE_CFB, + 256, + "ARIA-256-CFB128", + 16, + 0, + 16, + &aria_info +}; +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +static const mbedtls_cipher_info_t aria_128_ctr_info = { + MBEDTLS_CIPHER_ARIA_128_CTR, + MBEDTLS_MODE_CTR, + 128, + "ARIA-128-CTR", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_192_ctr_info = { + MBEDTLS_CIPHER_ARIA_192_CTR, + MBEDTLS_MODE_CTR, + 192, + "ARIA-192-CTR", + 16, + 0, + 16, + &aria_info +}; + +static const mbedtls_cipher_info_t aria_256_ctr_info = { + MBEDTLS_CIPHER_ARIA_256_CTR, + MBEDTLS_MODE_CTR, + 256, + "ARIA-256-CTR", + 16, + 0, + 16, + &aria_info +}; +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#if defined(MBEDTLS_GCM_C) +static int gcm_aria_setkey_wrap( void *ctx, const unsigned char *key, + unsigned int key_bitlen ) +{ + return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA, + key, key_bitlen ); +} + +static const mbedtls_cipher_base_t gcm_aria_info = { + MBEDTLS_CIPHER_ID_ARIA, + NULL, +#if defined(MBEDTLS_CIPHER_MODE_CBC) + NULL, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CFB) + NULL, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CTR) + NULL, +#endif +#if defined(MBEDTLS_CIPHER_MODE_STREAM) + NULL, +#endif + gcm_aria_setkey_wrap, + gcm_aria_setkey_wrap, + gcm_ctx_alloc, + gcm_ctx_free, +}; + +static const mbedtls_cipher_info_t aria_128_gcm_info = { + MBEDTLS_CIPHER_ARIA_128_GCM, + MBEDTLS_MODE_GCM, + 128, + "ARIA-128-GCM", + 12, + MBEDTLS_CIPHER_VARIABLE_IV_LEN, + 16, + &gcm_aria_info +}; + +static const mbedtls_cipher_info_t aria_192_gcm_info = { + MBEDTLS_CIPHER_ARIA_192_GCM, + MBEDTLS_MODE_GCM, + 192, + "ARIA-192-GCM", + 12, + MBEDTLS_CIPHER_VARIABLE_IV_LEN, + 16, + &gcm_aria_info +}; + +static const mbedtls_cipher_info_t aria_256_gcm_info = { + MBEDTLS_CIPHER_ARIA_256_GCM, + MBEDTLS_MODE_GCM, + 256, + "ARIA-256-GCM", + 12, + MBEDTLS_CIPHER_VARIABLE_IV_LEN, + 16, + &gcm_aria_info +}; +#endif /* MBEDTLS_GCM_C */ + +#if defined(MBEDTLS_CCM_C) +static int ccm_aria_setkey_wrap( void *ctx, const unsigned char *key, + unsigned int key_bitlen ) +{ + return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA, + key, key_bitlen ); +} + +static const mbedtls_cipher_base_t ccm_aria_info = { + MBEDTLS_CIPHER_ID_ARIA, + NULL, +#if defined(MBEDTLS_CIPHER_MODE_CBC) + NULL, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CFB) + NULL, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CTR) + NULL, +#endif +#if defined(MBEDTLS_CIPHER_MODE_STREAM) + NULL, +#endif + ccm_aria_setkey_wrap, + ccm_aria_setkey_wrap, + ccm_ctx_alloc, + ccm_ctx_free, +}; + +static const mbedtls_cipher_info_t aria_128_ccm_info = { + MBEDTLS_CIPHER_ARIA_128_CCM, + MBEDTLS_MODE_CCM, + 128, + "ARIA-128-CCM", + 12, + MBEDTLS_CIPHER_VARIABLE_IV_LEN, + 16, + &ccm_aria_info +}; + +static const mbedtls_cipher_info_t aria_192_ccm_info = { + MBEDTLS_CIPHER_ARIA_192_CCM, + MBEDTLS_MODE_CCM, + 192, + "ARIA-192-CCM", + 12, + MBEDTLS_CIPHER_VARIABLE_IV_LEN, + 16, + &ccm_aria_info +}; + +static const mbedtls_cipher_info_t aria_256_ccm_info = { + MBEDTLS_CIPHER_ARIA_256_CCM, + MBEDTLS_MODE_CCM, + 256, + "ARIA-256-CCM", + 12, + MBEDTLS_CIPHER_VARIABLE_IV_LEN, + 16, + &ccm_aria_info +}; +#endif /* MBEDTLS_CCM_C */ + +#endif /* MBEDTLS_ARIA_C */ + #if defined(MBEDTLS_DES_C) static int des_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation, @@ -1427,6 +1789,37 @@ const mbedtls_cipher_definition_t mbedtls_cipher_definitions[] = #endif #endif /* MBEDTLS_CAMELLIA_C */ +#if defined(MBEDTLS_ARIA_C) + { MBEDTLS_CIPHER_ARIA_128_ECB, &aria_128_ecb_info }, + { MBEDTLS_CIPHER_ARIA_192_ECB, &aria_192_ecb_info }, + { MBEDTLS_CIPHER_ARIA_256_ECB, &aria_256_ecb_info }, +#if defined(MBEDTLS_CIPHER_MODE_CBC) + { MBEDTLS_CIPHER_ARIA_128_CBC, &aria_128_cbc_info }, + { MBEDTLS_CIPHER_ARIA_192_CBC, &aria_192_cbc_info }, + { MBEDTLS_CIPHER_ARIA_256_CBC, &aria_256_cbc_info }, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CFB) + { MBEDTLS_CIPHER_ARIA_128_CFB128, &aria_128_cfb128_info }, + { MBEDTLS_CIPHER_ARIA_192_CFB128, &aria_192_cfb128_info }, + { MBEDTLS_CIPHER_ARIA_256_CFB128, &aria_256_cfb128_info }, +#endif +#if defined(MBEDTLS_CIPHER_MODE_CTR) + { MBEDTLS_CIPHER_ARIA_128_CTR, &aria_128_ctr_info }, + { MBEDTLS_CIPHER_ARIA_192_CTR, &aria_192_ctr_info }, + { MBEDTLS_CIPHER_ARIA_256_CTR, &aria_256_ctr_info }, +#endif +#if defined(MBEDTLS_GCM_C) + { MBEDTLS_CIPHER_ARIA_128_GCM, &aria_128_gcm_info }, + { MBEDTLS_CIPHER_ARIA_192_GCM, &aria_192_gcm_info }, + { MBEDTLS_CIPHER_ARIA_256_GCM, &aria_256_gcm_info }, +#endif +#if defined(MBEDTLS_CCM_C) + { MBEDTLS_CIPHER_ARIA_128_CCM, &aria_128_ccm_info }, + { MBEDTLS_CIPHER_ARIA_192_CCM, &aria_192_ccm_info }, + { MBEDTLS_CIPHER_ARIA_256_CCM, &aria_256_ccm_info }, +#endif +#endif /* MBEDTLS_ARIA_C */ + #if defined(MBEDTLS_DES_C) { MBEDTLS_CIPHER_DES_ECB, &des_ecb_info }, { MBEDTLS_CIPHER_DES_EDE_ECB, &des_ede_ecb_info }, diff --git a/thirdparty/mbedtls/library/cmac.c b/thirdparty/mbedtls/library/cmac.c index 9dbff90386..4d7a1f1693 100644 --- a/thirdparty/mbedtls/library/cmac.c +++ b/thirdparty/mbedtls/library/cmac.c @@ -49,6 +49,7 @@ #if defined(MBEDTLS_CMAC_C) #include "mbedtls/cmac.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -67,11 +68,6 @@ #if !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * Multiplication by u in the Galois field of GF(2^n) * @@ -144,7 +140,7 @@ static int cmac_generate_subkeys( mbedtls_cipher_context_t *ctx, unsigned char L[MBEDTLS_CIPHER_BLKSIZE_MAX]; size_t olen, block_size; - mbedtls_zeroize( L, sizeof( L ) ); + mbedtls_platform_zeroize( L, sizeof( L ) ); block_size = ctx->cipher_info->block_size; @@ -162,7 +158,7 @@ static int cmac_generate_subkeys( mbedtls_cipher_context_t *ctx, goto exit; exit: - mbedtls_zeroize( L, sizeof( L ) ); + mbedtls_platform_zeroize( L, sizeof( L ) ); return( ret ); } @@ -238,7 +234,7 @@ int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx, ctx->cmac_ctx = cmac_ctx; - mbedtls_zeroize( cmac_ctx->state, sizeof( cmac_ctx->state ) ); + mbedtls_platform_zeroize( cmac_ctx->state, sizeof( cmac_ctx->state ) ); return 0; } @@ -330,8 +326,8 @@ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, block_size = ctx->cipher_info->block_size; state = cmac_ctx->state; - mbedtls_zeroize( K1, sizeof( K1 ) ); - mbedtls_zeroize( K2, sizeof( K2 ) ); + mbedtls_platform_zeroize( K1, sizeof( K1 ) ); + mbedtls_platform_zeroize( K2, sizeof( K2 ) ); cmac_generate_subkeys( ctx, K1, K2 ); last_block = cmac_ctx->unprocessed_block; @@ -361,14 +357,14 @@ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, exit: /* Wipe the generated keys on the stack, and any other transients to avoid * side channel leakage */ - mbedtls_zeroize( K1, sizeof( K1 ) ); - mbedtls_zeroize( K2, sizeof( K2 ) ); + mbedtls_platform_zeroize( K1, sizeof( K1 ) ); + mbedtls_platform_zeroize( K2, sizeof( K2 ) ); cmac_ctx->unprocessed_len = 0; - mbedtls_zeroize( cmac_ctx->unprocessed_block, - sizeof( cmac_ctx->unprocessed_block ) ); + mbedtls_platform_zeroize( cmac_ctx->unprocessed_block, + sizeof( cmac_ctx->unprocessed_block ) ); - mbedtls_zeroize( state, MBEDTLS_CIPHER_BLKSIZE_MAX ); + mbedtls_platform_zeroize( state, MBEDTLS_CIPHER_BLKSIZE_MAX ); return( ret ); } @@ -383,10 +379,10 @@ int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx ) /* Reset the internal state */ cmac_ctx->unprocessed_len = 0; - mbedtls_zeroize( cmac_ctx->unprocessed_block, - sizeof( cmac_ctx->unprocessed_block ) ); - mbedtls_zeroize( cmac_ctx->state, - sizeof( cmac_ctx->state ) ); + mbedtls_platform_zeroize( cmac_ctx->unprocessed_block, + sizeof( cmac_ctx->unprocessed_block ) ); + mbedtls_platform_zeroize( cmac_ctx->state, + sizeof( cmac_ctx->state ) ); return( 0 ); } @@ -466,7 +462,7 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_length, output ); exit: - mbedtls_zeroize( int_key, sizeof( int_key ) ); + mbedtls_platform_zeroize( int_key, sizeof( int_key ) ); return( ret ); } @@ -771,7 +767,7 @@ static int cmac_test_subkeys( int verbose, int block_size, int num_tests ) { - int i, ret; + int i, ret = 0; mbedtls_cipher_context_t ctx; const mbedtls_cipher_info_t *cipher_info; unsigned char K1[MBEDTLS_CIPHER_BLKSIZE_MAX]; @@ -853,7 +849,7 @@ static int cmac_test_wth_cipher( int verbose, int num_tests ) { const mbedtls_cipher_info_t *cipher_info; - int i, ret; + int i, ret = 0; unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX]; cipher_info = mbedtls_cipher_info_from_type( cipher_type ); diff --git a/thirdparty/mbedtls/library/ctr_drbg.c b/thirdparty/mbedtls/library/ctr_drbg.c index ff532a0134..d0e5ba862d 100644 --- a/thirdparty/mbedtls/library/ctr_drbg.c +++ b/thirdparty/mbedtls/library/ctr_drbg.c @@ -33,6 +33,7 @@ #if defined(MBEDTLS_CTR_DRBG_C) #include "mbedtls/ctr_drbg.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -49,11 +50,6 @@ #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * CTR_DRBG context initialization */ @@ -125,7 +121,7 @@ void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx ) mbedtls_mutex_free( &ctx->mutex ); #endif mbedtls_aes_free( &ctx->aes_ctx ); - mbedtls_zeroize( ctx, sizeof( mbedtls_ctr_drbg_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ctr_drbg_context ) ); } void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx, int resistance ) @@ -245,16 +241,16 @@ exit: /* * tidy up the stack */ - mbedtls_zeroize( buf, sizeof( buf ) ); - mbedtls_zeroize( tmp, sizeof( tmp ) ); - mbedtls_zeroize( key, sizeof( key ) ); - mbedtls_zeroize( chain, sizeof( chain ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); + mbedtls_platform_zeroize( key, sizeof( key ) ); + mbedtls_platform_zeroize( chain, sizeof( chain ) ); if( 0 != ret ) { /* * wipe partial seed from memory */ - mbedtls_zeroize( output, MBEDTLS_CTR_DRBG_SEEDLEN ); + mbedtls_platform_zeroize( output, MBEDTLS_CTR_DRBG_SEEDLEN ); } return( ret ); @@ -493,7 +489,7 @@ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char ret = 0; exit: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); fclose( f ); return( ret ); @@ -526,7 +522,7 @@ int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char fclose( f ); - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); if( ret != 0 ) return( ret ); diff --git a/thirdparty/mbedtls/library/des.c b/thirdparty/mbedtls/library/des.c index 09f95cfc3b..ca9e071f32 100644 --- a/thirdparty/mbedtls/library/des.c +++ b/thirdparty/mbedtls/library/des.c @@ -34,6 +34,7 @@ #if defined(MBEDTLS_DES_C) #include "mbedtls/des.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -48,11 +49,6 @@ #if !defined(MBEDTLS_DES_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (big endian) */ @@ -316,7 +312,7 @@ void mbedtls_des_free( mbedtls_des_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_des_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des_context ) ); } void mbedtls_des3_init( mbedtls_des3_context *ctx ) @@ -329,7 +325,7 @@ void mbedtls_des3_free( mbedtls_des3_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_des3_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des3_context ) ); } static const unsigned char odd_parity_table[128] = { 1, 2, 4, 7, 8, @@ -553,7 +549,7 @@ int mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx, uint32_t sk[96]; des3_set2key( ctx->sk, sk, key ); - mbedtls_zeroize( sk, sizeof( sk ) ); + mbedtls_platform_zeroize( sk, sizeof( sk ) ); return( 0 ); } @@ -567,7 +563,7 @@ int mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx, uint32_t sk[96]; des3_set2key( sk, ctx->sk, key ); - mbedtls_zeroize( sk, sizeof( sk ) ); + mbedtls_platform_zeroize( sk, sizeof( sk ) ); return( 0 ); } @@ -604,7 +600,7 @@ int mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx, uint32_t sk[96]; des3_set3key( ctx->sk, sk, key ); - mbedtls_zeroize( sk, sizeof( sk ) ); + mbedtls_platform_zeroize( sk, sizeof( sk ) ); return( 0 ); } @@ -618,7 +614,7 @@ int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx, uint32_t sk[96]; des3_set3key( sk, ctx->sk, key ); - mbedtls_zeroize( sk, sizeof( sk ) ); + mbedtls_platform_zeroize( sk, sizeof( sk ) ); return( 0 ); } diff --git a/thirdparty/mbedtls/library/dhm.c b/thirdparty/mbedtls/library/dhm.c index 28ac31003c..82cbb0ce88 100644 --- a/thirdparty/mbedtls/library/dhm.c +++ b/thirdparty/mbedtls/library/dhm.c @@ -36,6 +36,7 @@ #if defined(MBEDTLS_DHM_C) #include "mbedtls/dhm.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -58,10 +59,6 @@ #endif #if !defined(MBEDTLS_DHM_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} /* * helper to validate the mbedtls_mpi size and import it @@ -437,7 +434,7 @@ void mbedtls_dhm_free( mbedtls_dhm_context *ctx ) mbedtls_mpi_free( &ctx->GX ); mbedtls_mpi_free( &ctx->X ); mbedtls_mpi_free( &ctx->G ); mbedtls_mpi_free( &ctx->P ); - mbedtls_zeroize( ctx, sizeof( mbedtls_dhm_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_dhm_context ) ); } #if defined(MBEDTLS_ASN1_PARSE_C) @@ -575,7 +572,7 @@ static int load_file( const char *path, unsigned char **buf, size_t *n ) { fclose( f ); - mbedtls_zeroize( *buf, *n + 1 ); + mbedtls_platform_zeroize( *buf, *n + 1 ); mbedtls_free( *buf ); return( MBEDTLS_ERR_DHM_FILE_IO_ERROR ); @@ -605,7 +602,7 @@ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path ) ret = mbedtls_dhm_parse_dhm( dhm, buf, n ); - mbedtls_zeroize( buf, n ); + mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); diff --git a/thirdparty/mbedtls/library/ecdsa.c b/thirdparty/mbedtls/library/ecdsa.c index 826fefe5c6..17a88bdd29 100644 --- a/thirdparty/mbedtls/library/ecdsa.c +++ b/thirdparty/mbedtls/library/ecdsa.c @@ -400,6 +400,9 @@ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, &ctx->Q, &r, &s ) ) != 0 ) goto cleanup; + /* At this point we know that the buffer starts with a valid signature. + * Return 0 if the buffer just contains the signature, and a specific + * error code if the valid signature is followed by more data. */ if( p != end ) ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH; diff --git a/thirdparty/mbedtls/library/ecjpake.c b/thirdparty/mbedtls/library/ecjpake.c index e8f40862be..ec5a4007db 100644 --- a/thirdparty/mbedtls/library/ecjpake.c +++ b/thirdparty/mbedtls/library/ecjpake.c @@ -301,7 +301,7 @@ cleanup: */ static int ecjpake_zkp_write( const mbedtls_md_info_t *md_info, const mbedtls_ecp_group *grp, - const int pf, + const int pf, const mbedtls_ecp_point *G, const mbedtls_mpi *x, const mbedtls_ecp_point *X, diff --git a/thirdparty/mbedtls/library/ecp.c b/thirdparty/mbedtls/library/ecp.c index b41baef27a..41db3fbe5b 100644 --- a/thirdparty/mbedtls/library/ecp.c +++ b/thirdparty/mbedtls/library/ecp.c @@ -26,6 +26,7 @@ * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf * RFC 4492 for the related TLS structures and constants + * RFC 7748 for the Curve448 and Curve25519 curve definitions * * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf * @@ -50,6 +51,7 @@ #include "mbedtls/ecp.h" #include "mbedtls/threading.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -72,11 +74,6 @@ #define inline __inline #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - #if defined(MBEDTLS_SELF_TEST) /* * Counts of point addition and doubling, and field multiplications. @@ -99,7 +96,8 @@ static unsigned long add_count, dbl_count, mul_count; #define ECP_SHORTWEIERSTRASS #endif -#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) +#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \ + defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #define ECP_MONTGOMERY #endif @@ -346,7 +344,7 @@ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ) mbedtls_free( grp->T ); } - mbedtls_zeroize( grp, sizeof( mbedtls_ecp_group ) ); + mbedtls_platform_zeroize( grp, sizeof( mbedtls_ecp_group ) ); } /* @@ -1852,6 +1850,8 @@ cleanup: static int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ) { /* [Curve25519 p. 5] Just check X is the correct number of bytes */ + /* Allow any public value, if it's too big then we'll just reduce it mod p + * (RFC 7748 sec. 5 para. 3). */ if( mbedtls_mpi_size( &pt->X ) > ( grp->nbits + 7 ) / 8 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); @@ -1887,14 +1887,18 @@ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi * #if defined(ECP_MONTGOMERY) if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY ) { - /* see [Curve25519] page 5 */ + /* see RFC 7748 sec. 5 para. 5 */ if( mbedtls_mpi_get_bit( d, 0 ) != 0 || mbedtls_mpi_get_bit( d, 1 ) != 0 || - mbedtls_mpi_get_bit( d, 2 ) != 0 || mbedtls_mpi_bitlen( d ) - 1 != grp->nbits ) /* mbedtls_mpi_bitlen is one-based! */ return( MBEDTLS_ERR_ECP_INVALID_KEY ); else - return( 0 ); + + /* see [Curve25519] page 5 */ + if( grp->nbits == 254 && mbedtls_mpi_get_bit( d, 2 ) != 0 ) + return( MBEDTLS_ERR_ECP_INVALID_KEY ); + + return( 0 ); } #endif /* ECP_MONTGOMERY */ #if defined(ECP_SHORTWEIERSTRASS) @@ -1941,10 +1945,14 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, else MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) ); - /* Make sure the last three bits are unset */ + /* Make sure the last two bits are unset for Curve448, three bits for + Curve25519 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) ); + if( grp->nbits == 254 ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) ); + } } else #endif /* ECP_MONTGOMERY */ diff --git a/thirdparty/mbedtls/library/ecp_curves.c b/thirdparty/mbedtls/library/ecp_curves.c index df5ac3eea5..68e2441ae8 100644 --- a/thirdparty/mbedtls/library/ecp_curves.c +++ b/thirdparty/mbedtls/library/ecp_curves.c @@ -627,6 +627,9 @@ static int ecp_mod_p521( mbedtls_mpi * ); #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) static int ecp_mod_p255( mbedtls_mpi * ); #endif +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) +static int ecp_mod_p448( mbedtls_mpi * ); +#endif #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) static int ecp_mod_p192k1( mbedtls_mpi * ); #endif @@ -670,7 +673,12 @@ static int ecp_use_curve25519( mbedtls_ecp_group *grp ) MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 19 ) ); grp->pbits = mbedtls_mpi_bitlen( &grp->P ); - /* Y intentionaly not set, since we use x/z coordinates. + /* N = 2^252 + 27742317777372353535851937790883648493 */ + MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->N, 16, + "14DEF9DEA2F79CD65812631A5CF5D3ED" ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &grp->N, 252, 1 ) ); + + /* Y intentionally not set, since we use x/z coordinates. * This is used as a marker to identify Montgomery curves! */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.X, 9 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.Z, 1 ) ); @@ -687,6 +695,52 @@ cleanup: } #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) +/* + * Specialized function for creating the Curve448 group + */ +static int ecp_use_curve448( mbedtls_ecp_group *grp ) +{ + mbedtls_mpi Ns; + int ret; + + mbedtls_mpi_init( &Ns ); + + /* Actually ( A + 2 ) / 4 */ + MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->A, 16, "98AA" ) ); + + /* P = 2^448 - 2^224 - 1 */ + MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->P, 1 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 224 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 1 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 224 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 1 ) ); + grp->pbits = mbedtls_mpi_bitlen( &grp->P ); + + /* Y intentionally not set, since we use x/z coordinates. + * This is used as a marker to identify Montgomery curves! */ + MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.X, 5 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.Z, 1 ) ); + mbedtls_mpi_free( &grp->G.Y ); + + /* N = 2^446 - 13818066809895115352007386748515426880336692474882178609894547503885 */ + MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &grp->N, 446, 1 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &Ns, 16, + "8335DC163BB124B65129C96FDE933D8D723A70AADC873D6D54A7BB0D" ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &grp->N, &grp->N, &Ns ) ); + + /* Actually, the required msb for private keys */ + grp->nbits = 447; + +cleanup: + mbedtls_mpi_free( &Ns ); + if( ret != 0 ) + mbedtls_ecp_group_free( grp ); + + return( ret ); +} +#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ + /* * Set a group using well-known domain parameters */ @@ -767,6 +821,12 @@ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id ) return( ecp_use_curve25519( grp ) ); #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) + case MBEDTLS_ECP_DP_CURVE448: + grp->modp = ecp_mod_p448; + return( ecp_use_curve448( grp ) ); +#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ + default: mbedtls_ecp_group_free( grp ); return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); @@ -1176,7 +1236,7 @@ static int ecp_mod_p255( mbedtls_mpi *N ) M.s = 1; M.n = N->n - ( P255_WIDTH - 1 ); if( M.n > P255_WIDTH + 1 ) - M.n = P255_WIDTH + 1; + return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); M.p = Mp; memset( Mp, 0, sizeof Mp ); memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) ); @@ -1197,6 +1257,77 @@ cleanup: } #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) + +/* Size of p448 in terms of mbedtls_mpi_uint */ +#define P448_WIDTH ( 448 / 8 / sizeof( mbedtls_mpi_uint ) ) + +/* Number of limbs fully occupied by 2^224 (max), and limbs used by it (min) */ +#define DIV_ROUND_UP( X, Y ) ( ( ( X ) + ( Y ) - 1 ) / ( Y ) ) +#define P224_WIDTH_MIN ( 28 / sizeof( mbedtls_mpi_uint ) ) +#define P224_WIDTH_MAX DIV_ROUND_UP( 28, sizeof( mbedtls_mpi_uint ) ) +#define P224_UNUSED_BITS ( ( P224_WIDTH_MAX * sizeof( mbedtls_mpi_uint ) * 8 ) - 224 ) + +/* + * Fast quasi-reduction modulo p448 = 2^448 - 2^224 - 1 + * Write N as A0 + 2^448 A1 and A1 as B0 + 2^224 B1, and return + * A0 + A1 + B1 + (B0 + B1) * 2^224. This is different to the reference + * implementation of Curve448, which uses its own special 56-bit limbs rather + * than a generic bignum library. We could squeeze some extra speed out on + * 32-bit machines by splitting N up into 32-bit limbs and doing the + * arithmetic using the limbs directly as we do for the NIST primes above, + * but for 64-bit targets it should use half the number of operations if we do + * the reduction with 224-bit limbs, since mpi_add_mpi will then use 64-bit adds. + */ +static int ecp_mod_p448( mbedtls_mpi *N ) +{ + int ret; + size_t i; + mbedtls_mpi M, Q; + mbedtls_mpi_uint Mp[P448_WIDTH + 1], Qp[P448_WIDTH]; + + if( N->n <= P448_WIDTH ) + return( 0 ); + + /* M = A1 */ + M.s = 1; + M.n = N->n - ( P448_WIDTH ); + if( M.n > P448_WIDTH ) + /* Shouldn't be called with N larger than 2^896! */ + return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); + M.p = Mp; + memset( Mp, 0, sizeof( Mp ) ); + memcpy( Mp, N->p + P448_WIDTH, M.n * sizeof( mbedtls_mpi_uint ) ); + + /* N = A0 */ + for( i = P448_WIDTH; i < N->n; i++ ) + N->p[i] = 0; + + /* N += A1 */ + MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &M ) ); + + /* Q = B1, N += B1 */ + Q = M; + Q.p = Qp; + memcpy( Qp, Mp, sizeof( Qp ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Q, 224 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &Q ) ); + + /* M = (B0 + B1) * 2^224, N += M */ + if( sizeof( mbedtls_mpi_uint ) > 4 ) + Mp[P224_WIDTH_MIN] &= ( (mbedtls_mpi_uint)-1 ) >> ( P224_UNUSED_BITS ); + for( i = P224_WIDTH_MAX; i < M.n; ++i ) + Mp[i] = 0; + MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &M, &M, &Q ) ); + M.n = P448_WIDTH + 1; /* Make room for shifted carry bit from the addition */ + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &M, 224 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &M ) ); + +cleanup: + return( ret ); +} +#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ + #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) diff --git a/thirdparty/mbedtls/library/entropy.c b/thirdparty/mbedtls/library/entropy.c index e17512e779..f8db1a5503 100644 --- a/thirdparty/mbedtls/library/entropy.c +++ b/thirdparty/mbedtls/library/entropy.c @@ -35,6 +35,7 @@ #include "mbedtls/entropy.h" #include "mbedtls/entropy_poll.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -59,11 +60,6 @@ #include "mbedtls/havege.h" #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - #define ENTROPY_MAX_LOOP 256 /**< Maximum amount to loop before error */ void mbedtls_entropy_init( mbedtls_entropy_context *ctx ) @@ -140,7 +136,7 @@ void mbedtls_entropy_free( mbedtls_entropy_context *ctx ) ctx->initial_entropy_run = 0; #endif ctx->source_count = 0; - mbedtls_zeroize( ctx->source, sizeof( ctx->source ) ); + mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) ); ctx->accumulator_started = 0; } @@ -232,7 +228,7 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id #endif cleanup: - mbedtls_zeroize( tmp, sizeof( tmp ) ); + mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); return( ret ); } @@ -300,7 +296,7 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx ) ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE; cleanup: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } @@ -433,7 +429,7 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len ) ret = 0; exit: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) @@ -486,7 +482,7 @@ int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *p ret = 0; exit: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); fclose( f ); return( ret ); @@ -516,7 +512,7 @@ int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char * fclose( f ); - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); if( ret != 0 ) return( ret ); diff --git a/thirdparty/mbedtls/library/entropy_poll.c b/thirdparty/mbedtls/library/entropy_poll.c index ed350735d0..cefe882d2a 100644 --- a/thirdparty/mbedtls/library/entropy_poll.c +++ b/thirdparty/mbedtls/library/entropy_poll.c @@ -44,7 +44,7 @@ #if !defined(MBEDTLS_NO_PLATFORM_ENTROPY) #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ - !defined(__APPLE__) && !defined(_WIN32) + !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) #error "Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in config.h" #endif diff --git a/thirdparty/mbedtls/library/error.c b/thirdparty/mbedtls/library/error.c index 0292480aee..8818054c56 100644 --- a/thirdparty/mbedtls/library/error.c +++ b/thirdparty/mbedtls/library/error.c @@ -49,6 +49,10 @@ #include "mbedtls/arc4.h" #endif +#if defined(MBEDTLS_ARIA_C) +#include "mbedtls/aria.h" +#endif + #if defined(MBEDTLS_BASE64_C) #include "mbedtls/base64.h" #endif @@ -256,19 +260,19 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) ) mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" ); if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "ECP - Requested curve not available" ); + mbedtls_snprintf( buf, buflen, "ECP - The requested feature is not available, for example, the requested curve is not supported" ); if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" ); if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) ) - mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" ); + mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as ephemeral key, failed" ); if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) ) mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" ); if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" ); + mbedtls_snprintf( buf, buflen, "ECP - The buffer contains a valid signature followed by more data" ); if( use_ret == -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "ECP - ECP hardware accelerator failed" ); + mbedtls_snprintf( buf, buflen, "ECP - The ECP hardware accelerator failed" ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) @@ -333,7 +337,7 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" ); + mbedtls_snprintf( buf, buflen, "PK - The buffer contains a valid signature followed by more data" ); if( use_ret == -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED) ) mbedtls_snprintf( buf, buflen, "PK - PK hardware accelerator failed" ); #endif /* MBEDTLS_PK_C */ @@ -478,7 +482,7 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) ) mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) ) - mbedtls_snprintf( buf, buflen, "SSL - Connection requires a read call" ); + mbedtls_snprintf( buf, buflen, "SSL - No data of requested type currently available on underlying transport" ); if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) ) mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" ); if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) ) @@ -491,6 +495,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" ); if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) ) mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" ); + if( use_ret == -(MBEDTLS_ERR_SSL_CONTINUE_PROCESSING) ) + mbedtls_snprintf( buf, buflen, "SSL - Internal-only message signaling that further message-processing should be done" ); #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) @@ -570,6 +576,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "AES - Invalid key length" ); if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) ) mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" ); + if( use_ret == -(MBEDTLS_ERR_AES_BAD_INPUT_DATA) ) + mbedtls_snprintf( buf, buflen, "AES - Invalid input data" ); if( use_ret == -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE) ) mbedtls_snprintf( buf, buflen, "AES - Feature not available. For example, an unsupported AES key size" ); if( use_ret == -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED) ) @@ -581,6 +589,17 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "ARC4 - ARC4 hardware accelerator failed" ); #endif /* MBEDTLS_ARC4_C */ +#if defined(MBEDTLS_ARIA_C) + if( use_ret == -(MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH) ) + mbedtls_snprintf( buf, buflen, "ARIA - Invalid key length" ); + if( use_ret == -(MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH) ) + mbedtls_snprintf( buf, buflen, "ARIA - Invalid data input length" ); + if( use_ret == -(MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE) ) + mbedtls_snprintf( buf, buflen, "ARIA - Feature not available. For example, an unsupported ARIA key size" ); + if( use_ret == -(MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED) ) + mbedtls_snprintf( buf, buflen, "ARIA - ARIA hardware accelerator failed" ); +#endif /* MBEDTLS_ARIA_C */ + #if defined(MBEDTLS_ASN1_PARSE_C) if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) ) mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" ); @@ -745,6 +764,10 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" ); if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) ) mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" ); + if( use_ret == -(MBEDTLS_ERR_NET_POLL_FAILED) ) + mbedtls_snprintf( buf, buflen, "NET - Polling the net context failed" ); + if( use_ret == -(MBEDTLS_ERR_NET_BAD_INPUT_DATA) ) + mbedtls_snprintf( buf, buflen, "NET - Input invalid" ); #endif /* MBEDTLS_NET_C */ #if defined(MBEDTLS_OID_C) diff --git a/thirdparty/mbedtls/library/gcm.c b/thirdparty/mbedtls/library/gcm.c index 294a86d3d4..57b027933d 100644 --- a/thirdparty/mbedtls/library/gcm.c +++ b/thirdparty/mbedtls/library/gcm.c @@ -38,6 +38,7 @@ #if defined(MBEDTLS_GCM_C) #include "mbedtls/gcm.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -80,11 +81,6 @@ } #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * Initialize a context */ @@ -498,7 +494,7 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, if( diff != 0 ) { - mbedtls_zeroize( output, length ); + mbedtls_platform_zeroize( output, length ); return( MBEDTLS_ERR_GCM_AUTH_FAILED ); } @@ -508,7 +504,7 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, void mbedtls_gcm_free( mbedtls_gcm_context *ctx ) { mbedtls_cipher_free( &ctx->cipher_ctx ); - mbedtls_zeroize( ctx, sizeof( mbedtls_gcm_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) ); } #endif /* !MBEDTLS_GCM_ALT */ diff --git a/thirdparty/mbedtls/library/havege.c b/thirdparty/mbedtls/library/havege.c index 2b75ef7bd8..4dcac02875 100644 --- a/thirdparty/mbedtls/library/havege.c +++ b/thirdparty/mbedtls/library/havege.c @@ -36,14 +36,10 @@ #include "mbedtls/havege.h" #include "mbedtls/timing.h" +#include "mbedtls/platform_util.h" #include <string.h> -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* ------------------------------------------------------------------------ * On average, one iteration accesses two 8-word blocks in the havege WALK * table, and generates 16 words in the RES array. @@ -208,7 +204,7 @@ void mbedtls_havege_free( mbedtls_havege_state *hs ) if( hs == NULL ) return; - mbedtls_zeroize( hs, sizeof( mbedtls_havege_state ) ); + mbedtls_platform_zeroize( hs, sizeof( mbedtls_havege_state ) ); } /* diff --git a/thirdparty/mbedtls/library/hmac_drbg.c b/thirdparty/mbedtls/library/hmac_drbg.c index 24c609e9ce..dad55ff861 100644 --- a/thirdparty/mbedtls/library/hmac_drbg.c +++ b/thirdparty/mbedtls/library/hmac_drbg.c @@ -34,6 +34,7 @@ #if defined(MBEDTLS_HMAC_DRBG_C) #include "mbedtls/hmac_drbg.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -50,11 +51,6 @@ #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_PLATFORM_C */ -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * HMAC_DRBG context initialization */ @@ -338,7 +334,7 @@ void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx ) mbedtls_mutex_free( &ctx->mutex ); #endif mbedtls_md_free( &ctx->md_ctx ); - mbedtls_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) ); } #if defined(MBEDTLS_FS_IO) @@ -364,7 +360,7 @@ int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const cha exit: fclose( f ); - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } @@ -396,7 +392,7 @@ int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const ch fclose( f ); - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); if( ret != 0 ) return( ret ); diff --git a/thirdparty/mbedtls/library/md.c b/thirdparty/mbedtls/library/md.c index 00249af78b..303cdcbeeb 100644 --- a/thirdparty/mbedtls/library/md.c +++ b/thirdparty/mbedtls/library/md.c @@ -33,6 +33,7 @@ #include "mbedtls/md.h" #include "mbedtls/md_internal.h" +#include "mbedtls/platform_util.h" #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" @@ -48,11 +49,6 @@ #include <stdio.h> #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * Reminder: update profiles in x509_crt.c when adding a new hash! */ @@ -193,11 +189,12 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx ) if( ctx->hmac_ctx != NULL ) { - mbedtls_zeroize( ctx->hmac_ctx, 2 * ctx->md_info->block_size ); + mbedtls_platform_zeroize( ctx->hmac_ctx, + 2 * ctx->md_info->block_size ); mbedtls_free( ctx->hmac_ctx ); } - mbedtls_zeroize( ctx, sizeof( mbedtls_md_context_t ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) ); } int mbedtls_md_clone( mbedtls_md_context_t *dst, @@ -311,7 +308,7 @@ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigne ret = md_info->finish_func( ctx.md_ctx, output ); cleanup: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); fclose( f ); mbedtls_md_free( &ctx ); @@ -361,7 +358,7 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, goto cleanup; cleanup: - mbedtls_zeroize( sum, sizeof( sum ) ); + mbedtls_platform_zeroize( sum, sizeof( sum ) ); return( ret ); } diff --git a/thirdparty/mbedtls/library/md2.c b/thirdparty/mbedtls/library/md2.c index b88aa406af..1c0b3df52d 100644 --- a/thirdparty/mbedtls/library/md2.c +++ b/thirdparty/mbedtls/library/md2.c @@ -34,6 +34,7 @@ #if defined(MBEDTLS_MD2_C) #include "mbedtls/md2.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -48,11 +49,6 @@ #if !defined(MBEDTLS_MD2_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - static const unsigned char PI_SUBST[256] = { 0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36, @@ -93,7 +89,7 @@ void mbedtls_md2_free( mbedtls_md2_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_md2_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md2_context ) ); } void mbedtls_md2_clone( mbedtls_md2_context *dst, diff --git a/thirdparty/mbedtls/library/md4.c b/thirdparty/mbedtls/library/md4.c index ba704f58e8..3f8ddff31d 100644 --- a/thirdparty/mbedtls/library/md4.c +++ b/thirdparty/mbedtls/library/md4.c @@ -34,6 +34,7 @@ #if defined(MBEDTLS_MD4_C) #include "mbedtls/md4.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -48,11 +49,6 @@ #if !defined(MBEDTLS_MD4_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (little endian) */ @@ -86,7 +82,7 @@ void mbedtls_md4_free( mbedtls_md4_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_md4_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md4_context ) ); } void mbedtls_md4_clone( mbedtls_md4_context *dst, diff --git a/thirdparty/mbedtls/library/md5.c b/thirdparty/mbedtls/library/md5.c index 8440ebffcf..8238c2b81a 100644 --- a/thirdparty/mbedtls/library/md5.c +++ b/thirdparty/mbedtls/library/md5.c @@ -33,6 +33,7 @@ #if defined(MBEDTLS_MD5_C) #include "mbedtls/md5.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -47,11 +48,6 @@ #if !defined(MBEDTLS_MD5_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (little endian) */ @@ -85,7 +81,7 @@ void mbedtls_md5_free( mbedtls_md5_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_md5_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) ); } void mbedtls_md5_clone( mbedtls_md5_context *dst, diff --git a/thirdparty/mbedtls/library/memory_buffer_alloc.c b/thirdparty/mbedtls/library/memory_buffer_alloc.c index 821ae2c708..ceaeda1e73 100644 --- a/thirdparty/mbedtls/library/memory_buffer_alloc.c +++ b/thirdparty/mbedtls/library/memory_buffer_alloc.c @@ -31,6 +31,7 @@ /* No need for the header guard as MBEDTLS_MEMORY_BUFFER_ALLOC_C is dependent upon MBEDTLS_PLATFORM_C */ #include "mbedtls/platform.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -42,11 +43,6 @@ #include "mbedtls/threading.h" #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - #define MAGIC1 0xFF00AA55 #define MAGIC2 0xEE119966 #define MAX_BT 20 @@ -612,7 +608,7 @@ void mbedtls_memory_buffer_alloc_free( void ) #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &heap.mutex ); #endif - mbedtls_zeroize( &heap, sizeof(buffer_alloc_ctx) ); + mbedtls_platform_zeroize( &heap, sizeof(buffer_alloc_ctx) ); } #if defined(MBEDTLS_SELF_TEST) diff --git a/thirdparty/mbedtls/library/net_sockets.c b/thirdparty/mbedtls/library/net_sockets.c index 2fb548caa9..9b0a375fb7 100644 --- a/thirdparty/mbedtls/library/net_sockets.c +++ b/thirdparty/mbedtls/library/net_sockets.c @@ -28,7 +28,7 @@ #if defined(MBEDTLS_NET_C) #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ - !defined(__APPLE__) && !defined(_WIN32) + !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) #error "This module only works on Unix and Windows, see MBEDTLS_NET_C in config.h" #endif @@ -45,6 +45,8 @@ #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ !defined(EFI32) +#define IS_EINTR( ret ) ( ( ret ) == WSAEINTR ) + /* GODOT ADDITION */ #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0501) #undef _WIN32_WINNT @@ -85,6 +87,8 @@ static int wsa_init_done = 0; #include <netdb.h> #include <errno.h> +#define IS_EINTR( ret ) ( ( ret ) == EINTR ) + #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */ /* Some MS functions want int and MSVC warns if we pass size_t, @@ -274,7 +278,7 @@ static int net_would_block( const mbedtls_net_context *ctx ) static int net_would_block( const mbedtls_net_context *ctx ) { int err = errno; - + /* * Never return 'WOULD BLOCK' on a non-blocking socket */ @@ -442,6 +446,72 @@ int mbedtls_net_set_nonblock( mbedtls_net_context *ctx ) } /* + * Check if data is available on the socket + */ + +int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout ) +{ + int ret; + struct timeval tv; + + fd_set read_fds; + fd_set write_fds; + + int fd = ctx->fd; + + if( fd < 0 ) + return( MBEDTLS_ERR_NET_INVALID_CONTEXT ); + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) + /* Ensure that memory sanitizers consider read_fds and write_fds as + * initialized even on platforms such as Glibc/x86_64 where FD_ZERO + * is implemented in assembly. */ + memset( &read_fds, 0, sizeof( read_fds ) ); + memset( &write_fds, 0, sizeof( write_fds ) ); +#endif +#endif + + FD_ZERO( &read_fds ); + if( rw & MBEDTLS_NET_POLL_READ ) + { + rw &= ~MBEDTLS_NET_POLL_READ; + FD_SET( fd, &read_fds ); + } + + FD_ZERO( &write_fds ); + if( rw & MBEDTLS_NET_POLL_WRITE ) + { + rw &= ~MBEDTLS_NET_POLL_WRITE; + FD_SET( fd, &write_fds ); + } + + if( rw != 0 ) + return( MBEDTLS_ERR_NET_BAD_INPUT_DATA ); + + tv.tv_sec = timeout / 1000; + tv.tv_usec = ( timeout % 1000 ) * 1000; + + do + { + ret = select( fd + 1, &read_fds, &write_fds, NULL, + timeout == (uint32_t) -1 ? NULL : &tv ); + } + while( IS_EINTR( ret ) ); + + if( ret < 0 ) + return( MBEDTLS_ERR_NET_POLL_FAILED ); + + ret = 0; + if( FD_ISSET( fd, &read_fds ) ) + ret |= MBEDTLS_NET_POLL_READ; + if( FD_ISSET( fd, &write_fds ) ) + ret |= MBEDTLS_NET_POLL_WRITE; + + return( ret ); +} + +/* * Portable usleep helper */ void mbedtls_net_usleep( unsigned long usec ) @@ -500,8 +570,8 @@ int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len ) /* * Read at most 'len' characters, blocking for at most 'timeout' ms */ -int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len, - uint32_t timeout ) +int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, + size_t len, uint32_t timeout ) { int ret; struct timeval tv; diff --git a/thirdparty/mbedtls/library/pem.c b/thirdparty/mbedtls/library/pem.c index ac86d7e479..6069a23dec 100644 --- a/thirdparty/mbedtls/library/pem.c +++ b/thirdparty/mbedtls/library/pem.c @@ -33,6 +33,7 @@ #include "mbedtls/aes.h" #include "mbedtls/md5.h" #include "mbedtls/cipher.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -45,11 +46,6 @@ #endif #if defined(MBEDTLS_PEM_PARSE_C) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - void mbedtls_pem_init( mbedtls_pem_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_pem_context ) ); @@ -135,7 +131,7 @@ static int pem_pbkdf1( unsigned char *key, size_t keylen, exit: mbedtls_md5_free( &md5_ctx ); - mbedtls_zeroize( md5sum, 16 ); + mbedtls_platform_zeroize( md5sum, 16 ); return( ret ); } @@ -164,7 +160,7 @@ static int pem_des_decrypt( unsigned char des_iv[8], exit: mbedtls_des_free( &des_ctx ); - mbedtls_zeroize( des_key, 8 ); + mbedtls_platform_zeroize( des_key, 8 ); return( ret ); } @@ -192,7 +188,7 @@ static int pem_des3_decrypt( unsigned char des3_iv[8], exit: mbedtls_des3_free( &des3_ctx ); - mbedtls_zeroize( des3_key, 24 ); + mbedtls_platform_zeroize( des3_key, 24 ); return( ret ); } @@ -222,7 +218,7 @@ static int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen, exit: mbedtls_aes_free( &aes_ctx ); - mbedtls_zeroize( aes_key, keylen ); + mbedtls_platform_zeroize( aes_key, keylen ); return( ret ); } @@ -359,7 +355,7 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const if( ( ret = mbedtls_base64_decode( buf, len, &len, s1, s2 - s1 ) ) != 0 ) { - mbedtls_zeroize( buf, len ); + mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_INVALID_DATA + ret ); } @@ -370,7 +366,7 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) ) if( pwd == NULL ) { - mbedtls_zeroize( buf, len ); + mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED ); } @@ -403,16 +399,16 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const * The result will be ASN.1 starting with a SEQUENCE tag, with 1 to 3 * length bytes (allow 4 to be sure) in all known use cases. * - * Use that as heurisitic to try detecting password mismatchs. + * Use that as a heuristic to try to detect password mismatches. */ if( len <= 2 || buf[0] != 0x30 || buf[1] > 0x83 ) { - mbedtls_zeroize( buf, len ); + mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_PASSWORD_MISMATCH ); } #else - mbedtls_zeroize( buf, len ); + mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC && @@ -428,11 +424,11 @@ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const void mbedtls_pem_free( mbedtls_pem_context *ctx ) { if( ctx->buf != NULL ) - mbedtls_zeroize( ctx->buf, ctx->buflen ); + mbedtls_platform_zeroize( ctx->buf, ctx->buflen ); mbedtls_free( ctx->buf ); mbedtls_free( ctx->info ); - mbedtls_zeroize( ctx, sizeof( mbedtls_pem_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) ); } #endif /* MBEDTLS_PEM_PARSE_C */ diff --git a/thirdparty/mbedtls/library/pk.c b/thirdparty/mbedtls/library/pk.c index b52c73fbc6..f05b139e3f 100644 --- a/thirdparty/mbedtls/library/pk.c +++ b/thirdparty/mbedtls/library/pk.c @@ -29,6 +29,8 @@ #include "mbedtls/pk.h" #include "mbedtls/pk_internal.h" +#include "mbedtls/platform_util.h" + #if defined(MBEDTLS_RSA_C) #include "mbedtls/rsa.h" #endif @@ -42,11 +44,6 @@ #include <limits.h> #include <stdint.h> -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * Initialise a mbedtls_pk_context */ @@ -69,7 +66,7 @@ void mbedtls_pk_free( mbedtls_pk_context *ctx ) ctx->pk_info->ctx_free_func( ctx->pk_ctx ); - mbedtls_zeroize( ctx, sizeof( mbedtls_pk_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pk_context ) ); } /* diff --git a/thirdparty/mbedtls/library/pk_wrap.c b/thirdparty/mbedtls/library/pk_wrap.c index a4bb35fc8f..2c7d2d79b8 100644 --- a/thirdparty/mbedtls/library/pk_wrap.c +++ b/thirdparty/mbedtls/library/pk_wrap.c @@ -41,6 +41,10 @@ #include "mbedtls/ecdsa.h" #endif +#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) +#include "mbedtls/platform_util.h" +#endif + #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else @@ -52,13 +56,6 @@ #include <limits.h> #include <stdint.h> -#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} -#endif - #if defined(MBEDTLS_RSA_C) static int rsa_can_do( mbedtls_pk_type_t type ) { @@ -93,6 +90,11 @@ static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, (unsigned int) hash_len, hash, sig ) ) != 0 ) return( ret ); + /* The buffer contains a valid signature followed by extra data. + * We have a special error code for that so that so that callers can + * use mbedtls_pk_verify() to check "Does the buffer start with a + * valid signature?" and not just "Does the buffer contain a valid + * signature?". */ if( sig_len > rsa_len ) return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); @@ -493,7 +495,7 @@ static void *rsa_alt_alloc_wrap( void ) static void rsa_alt_free_wrap( void *ctx ) { - mbedtls_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) ); mbedtls_free( ctx ); } diff --git a/thirdparty/mbedtls/library/pkcs12.c b/thirdparty/mbedtls/library/pkcs12.c index c603a13577..16a15cb63e 100644 --- a/thirdparty/mbedtls/library/pkcs12.c +++ b/thirdparty/mbedtls/library/pkcs12.c @@ -36,6 +36,7 @@ #include "mbedtls/pkcs12.h" #include "mbedtls/asn1.h" #include "mbedtls/cipher.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -47,11 +48,6 @@ #include "mbedtls/des.h" #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - static int pkcs12_parse_pbe_params( mbedtls_asn1_buf *params, mbedtls_asn1_buf *salt, int *iterations ) { @@ -166,7 +162,7 @@ int mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode, goto exit; exit: - mbedtls_zeroize( key, sizeof( key ) ); + mbedtls_platform_zeroize( key, sizeof( key ) ); mbedtls_arc4_free( &ctx ); return( ret ); @@ -223,8 +219,8 @@ int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode, ret = MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH; exit: - mbedtls_zeroize( key, sizeof( key ) ); - mbedtls_zeroize( iv, sizeof( iv ) ); + mbedtls_platform_zeroize( key, sizeof( key ) ); + mbedtls_platform_zeroize( iv, sizeof( iv ) ); mbedtls_cipher_free( &cipher_ctx ); return( ret ); @@ -352,10 +348,10 @@ int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen, ret = 0; exit: - mbedtls_zeroize( salt_block, sizeof( salt_block ) ); - mbedtls_zeroize( pwd_block, sizeof( pwd_block ) ); - mbedtls_zeroize( hash_block, sizeof( hash_block ) ); - mbedtls_zeroize( hash_output, sizeof( hash_output ) ); + mbedtls_platform_zeroize( salt_block, sizeof( salt_block ) ); + mbedtls_platform_zeroize( pwd_block, sizeof( pwd_block ) ); + mbedtls_platform_zeroize( hash_block, sizeof( hash_block ) ); + mbedtls_platform_zeroize( hash_output, sizeof( hash_output ) ); mbedtls_md_free( &md_ctx ); diff --git a/thirdparty/mbedtls/library/pkcs5.c b/thirdparty/mbedtls/library/pkcs5.c index 95f44fa98b..440a174b5b 100644 --- a/thirdparty/mbedtls/library/pkcs5.c +++ b/thirdparty/mbedtls/library/pkcs5.c @@ -38,9 +38,12 @@ #if defined(MBEDTLS_PKCS5_C) #include "mbedtls/pkcs5.h" + +#if defined(MBEDTLS_ASN1_PARSE_C) #include "mbedtls/asn1.h" #include "mbedtls/cipher.h" #include "mbedtls/oid.h" +#endif /* MBEDTLS_ASN1_PARSE_C */ #include <string.h> @@ -51,6 +54,22 @@ #define mbedtls_printf printf #endif +#if !defined(MBEDTLS_ASN1_PARSE_C) +int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *data, size_t datalen, + unsigned char *output ) +{ + ((void) pbe_params); + ((void) mode); + ((void) pwd); + ((void) pwdlen); + ((void) data); + ((void) datalen); + ((void) output); + return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE ); +} +#else static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params, mbedtls_asn1_buf *salt, int *iterations, int *keylen, mbedtls_md_type_t *md_type ) @@ -211,6 +230,7 @@ exit: return( ret ); } +#endif /* MBEDTLS_ASN1_PARSE_C */ int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *password, size_t plen, const unsigned char *salt, size_t slen, diff --git a/thirdparty/mbedtls/library/pkparse.c b/thirdparty/mbedtls/library/pkparse.c index 9022db2f93..ccb7f5409d 100644 --- a/thirdparty/mbedtls/library/pkparse.c +++ b/thirdparty/mbedtls/library/pkparse.c @@ -30,6 +30,7 @@ #include "mbedtls/pk.h" #include "mbedtls/asn1.h" #include "mbedtls/oid.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -60,14 +61,6 @@ #define mbedtls_free free #endif -#if defined(MBEDTLS_FS_IO) || \ - defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} -#endif - #if defined(MBEDTLS_FS_IO) /* * Load all data from a file into a given buffer. @@ -105,7 +98,7 @@ int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n ) { fclose( f ); - mbedtls_zeroize( *buf, *n ); + mbedtls_platform_zeroize( *buf, *n ); mbedtls_free( *buf ); return( MBEDTLS_ERR_PK_FILE_IO_ERROR ); @@ -140,7 +133,7 @@ int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx, ret = mbedtls_pk_parse_key( ctx, buf, n, (const unsigned char *) pwd, strlen( pwd ) ); - mbedtls_zeroize( buf, n ); + mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); @@ -160,7 +153,7 @@ int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path ) ret = mbedtls_pk_parse_public_key( ctx, buf, n ); - mbedtls_zeroize( buf, n ); + mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); @@ -861,7 +854,10 @@ static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck, mbedtls_ecp_keypair_free( eck ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } + } + if( p != end ) + { /* * Is 'publickey' present? If not, or if we can't read it (eg because it * is compressed), create it from the private key. @@ -1292,7 +1288,7 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk, ret = pk_parse_key_pkcs8_encrypted_der( pk, key_copy, keylen, pwd, pwdlen ); - mbedtls_zeroize( key_copy, keylen ); + mbedtls_platform_zeroize( key_copy, keylen ); mbedtls_free( key_copy ); } diff --git a/thirdparty/mbedtls/library/platform.c b/thirdparty/mbedtls/library/platform.c index a295f9b9af..9e992875d9 100644 --- a/thirdparty/mbedtls/library/platform.c +++ b/thirdparty/mbedtls/library/platform.c @@ -28,14 +28,7 @@ #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" - -#if defined(MBEDTLS_ENTROPY_NV_SEED) && \ - !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} -#endif +#include "mbedtls/platform_util.h" #if defined(MBEDTLS_PLATFORM_MEMORY) #if !defined(MBEDTLS_PLATFORM_STD_CALLOC) @@ -241,7 +234,7 @@ int mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len ) if( ( n = fread( buf, 1, buf_len, file ) ) != buf_len ) { fclose( file ); - mbedtls_zeroize( buf, buf_len ); + mbedtls_platform_zeroize( buf, buf_len ); return( -1 ); } diff --git a/thirdparty/mbedtls/library/platform_util.c b/thirdparty/mbedtls/library/platform_util.c new file mode 100644 index 0000000000..1a57de9393 --- /dev/null +++ b/thirdparty/mbedtls/library/platform_util.c @@ -0,0 +1,67 @@ +/* + * Common and shared functions used by multiple modules in the Mbed TLS + * library. + * + * Copyright (C) 2018, Arm Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * 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. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "mbedtls/platform_util.h" + +#include <stddef.h> +#include <string.h> + +#if !defined(MBEDTLS_PLATFORM_ZEROIZE_ALT) +/* + * This implementation should never be optimized out by the compiler + * + * This implementation for mbedtls_platform_zeroize() was inspired from Colin + * Percival's blog article at: + * + * http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html + * + * It uses a volatile function pointer to the standard memset(). Because the + * pointer is volatile the compiler expects it to change at + * any time and will not optimize out the call that could potentially perform + * other operations on the input buffer instead of just setting it to 0. + * Nevertheless, as pointed out by davidtgoldblatt on Hacker News + * (refer to http://www.daemonology.net/blog/2014-09-05-erratum.html for + * details), optimizations of the following form are still possible: + * + * if( memset_func != memset ) + * memset_func( buf, 0, len ); + * + * Note that it is extremely difficult to guarantee that + * mbedtls_platform_zeroize() will not be optimized out by aggressive compilers + * in a portable way. For this reason, Mbed TLS also provides the configuration + * option MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure + * mbedtls_platform_zeroize() to use a suitable implementation for their + * platform and needs. + */ +static void * (* const volatile memset_func)( void *, int, size_t ) = memset; + +void mbedtls_platform_zeroize( void *buf, size_t len ) +{ + memset_func( buf, 0, len ); +} +#endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */ diff --git a/thirdparty/mbedtls/library/ripemd160.c b/thirdparty/mbedtls/library/ripemd160.c index 2ba48b7fdb..bd25ada62c 100644 --- a/thirdparty/mbedtls/library/ripemd160.c +++ b/thirdparty/mbedtls/library/ripemd160.c @@ -34,6 +34,7 @@ #if defined(MBEDTLS_RIPEMD160_C) #include "mbedtls/ripemd160.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -71,11 +72,6 @@ } #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - void mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_ripemd160_context ) ); @@ -86,7 +82,7 @@ void mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_ripemd160_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ripemd160_context ) ); } void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst, diff --git a/thirdparty/mbedtls/library/rsa.c b/thirdparty/mbedtls/library/rsa.c index c9f7ba91b6..88c1cf1007 100644 --- a/thirdparty/mbedtls/library/rsa.c +++ b/thirdparty/mbedtls/library/rsa.c @@ -48,6 +48,7 @@ #include "mbedtls/rsa.h" #include "mbedtls/rsa_internal.h" #include "mbedtls/oid.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -70,11 +71,7 @@ #if !defined(MBEDTLS_RSA_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - +#if defined(MBEDTLS_PKCS1_V15) /* constant-time buffer comparison */ static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n ) { @@ -88,6 +85,7 @@ static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n ) return( diff ); } +#endif /* MBEDTLS_PKCS1_V15 */ int mbedtls_rsa_import( mbedtls_rsa_context *ctx, const mbedtls_mpi *N, @@ -493,6 +491,9 @@ size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ) /* * Generate an RSA keypair + * + * This generation method follows the RSA key pair generation procedure of + * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072. */ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), @@ -500,7 +501,7 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, unsigned int nbits, int exponent ) { int ret; - mbedtls_mpi H, G; + mbedtls_mpi H, G, L; if( f_rng == NULL || nbits < 128 || exponent < 3 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); @@ -510,10 +511,13 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G ); + mbedtls_mpi_init( &L ); /* * find primes P and Q with Q < P so that: - * GCD( E, (P-1)*(Q-1) ) == 1 + * 1. |P-Q| > 2^( nbits / 2 - 100 ) + * 2. GCD( E, (P-1)*(Q-1) ) == 1 + * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 ) */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) ); @@ -525,40 +529,51 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0, f_rng, p_rng ) ); - if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 ) + /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */ + MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) ); + if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) ) continue; - MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ); - if( mbedtls_mpi_bitlen( &ctx->N ) != nbits ) - continue; - - if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 ) + /* not required by any standards, but some users rely on the fact that P > Q */ + if( H.s < 0 ) mbedtls_mpi_swap( &ctx->P, &ctx->Q ); /* Temporarily replace P,Q by P-1, Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q, &ctx->Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P, &ctx->Q ) ); + + /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H ) ); + if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 ) + continue; + + /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */ + MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P, &ctx->Q ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &L ) ); + + if( mbedtls_mpi_bitlen( &ctx->D ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a)) + continue; + + break; } - while( mbedtls_mpi_cmp_int( &G, 1 ) != 0 ); + while( 1 ); /* Restore P,Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q, &ctx->Q, 1 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ); + ctx->len = mbedtls_mpi_size( &ctx->N ); +#if !defined(MBEDTLS_RSA_NO_CRT) /* - * D = E^-1 mod ((P-1)*(Q-1)) * DP = D mod (P - 1) * DQ = D mod (Q - 1) * QP = Q^-1 mod P */ - - MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &H ) ); - -#if !defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ) ); #endif /* MBEDTLS_RSA_NO_CRT */ @@ -570,6 +585,7 @@ cleanup: mbedtls_mpi_free( &H ); mbedtls_mpi_free( &G ); + mbedtls_mpi_free( &L ); if( ret != 0 ) { @@ -1040,7 +1056,7 @@ static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src, } exit: - mbedtls_zeroize( mask, sizeof( mask ) ); + mbedtls_platform_zeroize( mask, sizeof( mask ) ); return( ret ); } @@ -1354,8 +1370,8 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, ret = 0; cleanup: - mbedtls_zeroize( buf, sizeof( buf ) ); - mbedtls_zeroize( lhash, sizeof( lhash ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( lhash, sizeof( lhash ) ); return( ret ); } @@ -1452,7 +1468,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, ret = 0; cleanup: - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } @@ -1583,7 +1599,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, p += hlen; *p++ = 0xBC; - mbedtls_zeroize( salt, sizeof( salt ) ); + mbedtls_platform_zeroize( salt, sizeof( salt ) ); exit: mbedtls_md_free( &md_ctx ); @@ -1725,7 +1741,7 @@ static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg, * after the initial bounds check. */ if( p != dst + dst_len ) { - mbedtls_zeroize( dst, dst_len ); + mbedtls_platform_zeroize( dst, dst_len ); return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } @@ -2062,13 +2078,13 @@ cleanup: if( encoded != NULL ) { - mbedtls_zeroize( encoded, sig_len ); + mbedtls_platform_zeroize( encoded, sig_len ); mbedtls_free( encoded ); } if( encoded_expected != NULL ) { - mbedtls_zeroize( encoded_expected, sig_len ); + mbedtls_platform_zeroize( encoded_expected, sig_len ); mbedtls_free( encoded_expected ); } diff --git a/thirdparty/mbedtls/library/sha1.c b/thirdparty/mbedtls/library/sha1.c index 1f29a0fbf8..1587de4805 100644 --- a/thirdparty/mbedtls/library/sha1.c +++ b/thirdparty/mbedtls/library/sha1.c @@ -33,6 +33,7 @@ #if defined(MBEDTLS_SHA1_C) #include "mbedtls/sha1.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -47,11 +48,6 @@ #if !defined(MBEDTLS_SHA1_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (big endian) */ @@ -85,7 +81,7 @@ void mbedtls_sha1_free( mbedtls_sha1_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_sha1_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) ); } void mbedtls_sha1_clone( mbedtls_sha1_context *dst, diff --git a/thirdparty/mbedtls/library/sha256.c b/thirdparty/mbedtls/library/sha256.c index f39bcbab6c..695485d847 100644 --- a/thirdparty/mbedtls/library/sha256.c +++ b/thirdparty/mbedtls/library/sha256.c @@ -33,6 +33,7 @@ #if defined(MBEDTLS_SHA256_C) #include "mbedtls/sha256.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -50,11 +51,6 @@ #if !defined(MBEDTLS_SHA256_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (big endian) */ @@ -88,7 +84,7 @@ void mbedtls_sha256_free( mbedtls_sha256_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_sha256_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) ); } void mbedtls_sha256_clone( mbedtls_sha256_context *dst, diff --git a/thirdparty/mbedtls/library/sha512.c b/thirdparty/mbedtls/library/sha512.c index 97cee07c56..6de94e99b4 100644 --- a/thirdparty/mbedtls/library/sha512.c +++ b/thirdparty/mbedtls/library/sha512.c @@ -33,6 +33,7 @@ #if defined(MBEDTLS_SHA512_C) #include "mbedtls/sha512.h" +#include "mbedtls/platform_util.h" #if defined(_MSC_VER) || defined(__WATCOMC__) #define UL64(x) x##ui64 @@ -56,11 +57,6 @@ #if !defined(MBEDTLS_SHA512_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * 64-bit integer manipulation macros (big endian) */ @@ -102,7 +98,7 @@ void mbedtls_sha512_free( mbedtls_sha512_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_sha512_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) ); } void mbedtls_sha512_clone( mbedtls_sha512_context *dst, diff --git a/thirdparty/mbedtls/library/ssl_ciphersuites.c b/thirdparty/mbedtls/library/ssl_ciphersuites.c index 95e6163ccc..2e9a0fd792 100644 --- a/thirdparty/mbedtls/library/ssl_ciphersuites.c +++ b/thirdparty/mbedtls/library/ssl_ciphersuites.c @@ -47,7 +47,7 @@ * 1. By key exchange: * Forward-secure non-PSK > forward-secure PSK > ECJPAKE > other non-PSK > other PSK * 2. By key length and cipher: - * AES-256 > Camellia-256 > AES-128 > Camellia-128 > 3DES + * AES-256 > Camellia-256 > ARIA-256 > AES-128 > Camellia-128 > ARIA-128 > 3DES * 3. By cipher mode when relevant GCM > CCM > CBC > CCM_8 * 4. By hash function used when relevant * 5. By key exchange/auth again: EC > non-EC @@ -81,6 +81,14 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, + /* All ARIA-256 ephemeral suites */ + MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, + MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, + MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, + /* All AES-128 ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, @@ -105,6 +113,14 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, + /* All ARIA-128 ephemeral suites */ + MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, + /* All remaining >= 128-bit ephemeral suites */ MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, @@ -121,6 +137,9 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8, + MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, + MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM, @@ -132,6 +151,9 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8, + MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, + MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, @@ -161,6 +183,14 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, + /* All ARIA-256 suites */ + MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, + MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, + MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384, + /* All AES-128 suites */ MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CCM, @@ -183,6 +213,14 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, + /* All ARIA-128 suites */ + MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, + MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256, + /* All remaining >= 128-bit suites */ MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, @@ -194,12 +232,16 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, + MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, + MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, @@ -211,6 +253,8 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8, + MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384, + MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384, MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_PSK_WITH_AES_128_CCM, @@ -219,6 +263,8 @@ static const int ciphersuite_preference[] = MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8, + MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256, + MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256, MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA, @@ -1688,6 +1734,365 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] = #endif /* MBEDTLS_DES_C */ #endif /* MBEDTLS_ENABLE_WEAK_CIPHERSUITES */ +#if defined(MBEDTLS_ARIA_C) + +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384, + "TLS-RSA-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384, + "TLS-RSA-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256, + "TLS-RSA-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256, + "TLS-RSA-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, + "TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, + "TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, + "TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, + "TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384, + "TLS-PSK-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384,MBEDTLS_KEY_EXCHANGE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384, + "TLS-PSK-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256, + "TLS-PSK-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256, + "TLS-PSK-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, + "TLS-ECDH-RSA-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, + "TLS-ECDH-RSA-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, + "TLS-ECDH-RSA-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, + "TLS-ECDH-RSA-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384, + "TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, + "TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256, + "TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, + "TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) + +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, + "TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, + "TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384, + "TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, + "TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256, + "TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, + "TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, + "TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, + "TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, + "TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, + "TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384, + "TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, + "TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256, + "TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, + "TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) + +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384, + "TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384", + MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C)) + { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, + "TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384", + MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256, + "TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256", + MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif +#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C)) + { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, + "TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256", + MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3, + 0 }, +#endif + +#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ + +#endif /* MBEDTLS_ARIA_C */ + + { 0, "", MBEDTLS_CIPHER_NONE, MBEDTLS_MD_NONE, MBEDTLS_KEY_EXCHANGE_NONE, 0, 0, 0, 0, 0 } diff --git a/thirdparty/mbedtls/library/ssl_cli.c b/thirdparty/mbedtls/library/ssl_cli.c index 88864b8136..7455e99d2e 100644 --- a/thirdparty/mbedtls/library/ssl_cli.c +++ b/thirdparty/mbedtls/library/ssl_cli.c @@ -48,10 +48,7 @@ #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} +#include "mbedtls/platform_util.h" #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) @@ -355,7 +352,7 @@ static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, *olen = 6; } -#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || +#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) @@ -717,6 +714,49 @@ static int ssl_generate_random( mbedtls_ssl_context *ssl ) return( 0 ); } +/** + * \brief Validate cipher suite against config in SSL context. + * + * \param suite_info cipher suite to validate + * \param ssl SSL context + * \param min_minor_ver Minimal minor version to accept a cipher suite + * \param max_minor_ver Maximal minor version to accept a cipher suite + * + * \return 0 if valid, else 1 + */ +static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info, + const mbedtls_ssl_context * ssl, + int min_minor_ver, int max_minor_ver ) +{ + (void) ssl; + if( suite_info == NULL ) + return( 1 ); + + if( suite_info->min_minor_ver > max_minor_ver || + suite_info->max_minor_ver < min_minor_ver ) + return( 1 ); + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && + ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) + return( 1 ); +#endif + +#if defined(MBEDTLS_ARC4_C) + if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && + suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) + return( 1 ); +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && + mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) + return( 1 ); +#endif + + return( 0 ); +} + static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) { int ret; @@ -869,31 +909,11 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) { ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] ); - if( ciphersuite_info == NULL ) + if( ssl_validate_ciphersuite( ciphersuite_info, ssl, + ssl->conf->min_minor_ver, + ssl->conf->max_minor_ver ) != 0 ) continue; - if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver || - ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver ) - continue; - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) - continue; -#endif - -#if defined(MBEDTLS_ARC4_C) - if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && - ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) - continue; -#endif - -#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) - if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && - mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) - continue; -#endif - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x", ciphersuites[i] ) ); @@ -938,7 +958,7 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) #endif /* - * We don't support compression with DTLS right now: is many records come + * We don't support compression with DTLS right now: if many records come * in the same datagram, uncompressing one could overwrite the next one. * We don't want to add complexity for handling that case unless there is * an actual need for it. @@ -1261,7 +1281,7 @@ static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } -#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || +#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) @@ -1690,22 +1710,9 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) ); - suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ); - if( suite_info == NULL -#if defined(MBEDTLS_ARC4_C) - || ( ssl->conf->arc4_disabled && - suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) -#endif - ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); - return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); - } - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); - + /* + * Perform cipher suite validation in same way as in ssl_write_client_hello. + */ i = 0; while( 1 ) { @@ -1724,6 +1731,17 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) } } + suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ); + if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); + if( comp != MBEDTLS_SSL_COMPRESS_NULL #if defined(MBEDTLS_ZLIB_SUPPORT) && comp != MBEDTLS_SSL_COMPRESS_DEFLATE @@ -2673,10 +2691,27 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) buf = ssl->in_msg; /* certificate_types */ + if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); + } cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )]; n = cert_type_len; - if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n ) + /* + * In the subsequent code there are two paths that read from buf: + * * the length of the signature algorithms field (if minor version of + * SSL is 3), + * * distinguished name length otherwise. + * Both reach at most the index: + * ...hdr_len + 2 + n, + * therefore the buffer length at this point must be greater than that + * regardless of the actual code path. + */ + if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, @@ -2691,9 +2726,32 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); #if defined(MBEDTLS_DEBUG_C) - unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n; + unsigned char* sig_alg; size_t i; +#endif + + /* + * The furthest access in buf is in the loop few lines below: + * sig_alg[i + 1], + * where: + * sig_alg = buf + ...hdr_len + 3 + n, + * max(i) = sig_alg_len - 1. + * Therefore the furthest access is: + * buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1], + * which reduces to: + * buf[...hdr_len + 3 + n + sig_alg_len], + * which is one less than we need the buf to be. + */ + if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); + } +#if defined(MBEDTLS_DEBUG_C) + sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n; for( i = 0; i < sig_alg_len; i += 2 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d" @@ -2702,14 +2760,6 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) #endif n += 2 + sig_alg_len; - - if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); - } } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ @@ -3289,8 +3339,8 @@ static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl ) if( ticket_len == 0 ) return( 0 ); - mbedtls_zeroize( ssl->session_negotiate->ticket, - ssl->session_negotiate->ticket_len ); + mbedtls_platform_zeroize( ssl->session_negotiate->ticket, + ssl->session_negotiate->ticket_len ); mbedtls_free( ssl->session_negotiate->ticket ); ssl->session_negotiate->ticket = NULL; ssl->session_negotiate->ticket_len = 0; diff --git a/thirdparty/mbedtls/library/ssl_cookie.c b/thirdparty/mbedtls/library/ssl_cookie.c index caf119990d..56e9bdd2bf 100644 --- a/thirdparty/mbedtls/library/ssl_cookie.c +++ b/thirdparty/mbedtls/library/ssl_cookie.c @@ -40,14 +40,10 @@ #include "mbedtls/ssl_cookie.h" #include "mbedtls/ssl_internal.h" +#include "mbedtls/platform_util.h" #include <string.h> -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * If DTLS is in use, then at least one of SHA-1, SHA-256, SHA-512 is * available. Try SHA-256 first, 512 wastes resources since we need to stay @@ -101,7 +97,7 @@ void mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx ) mbedtls_mutex_free( &ctx->mutex ); #endif - mbedtls_zeroize( ctx, sizeof( mbedtls_ssl_cookie_ctx ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_cookie_ctx ) ); } int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx, @@ -122,7 +118,7 @@ int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx, if( ret != 0 ) return( ret ); - mbedtls_zeroize( key, sizeof( key ) ); + mbedtls_platform_zeroize( key, sizeof( key ) ); return( 0 ); } diff --git a/thirdparty/mbedtls/library/ssl_srv.c b/thirdparty/mbedtls/library/ssl_srv.c index aca4235e6e..09b7a3fed3 100644 --- a/thirdparty/mbedtls/library/ssl_srv.c +++ b/thirdparty/mbedtls/library/ssl_srv.c @@ -38,6 +38,7 @@ #include "mbedtls/debug.h" #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -49,13 +50,6 @@ #include "mbedtls/platform_time.h" #endif -#if defined(MBEDTLS_SSL_SESSION_TICKETS) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} -#endif - #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl, const unsigned char *info, @@ -553,7 +547,7 @@ static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) ); /* Zeroize instead of free as we copied the content */ - mbedtls_zeroize( &session, sizeof( mbedtls_ssl_session ) ); + mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) ); @@ -793,7 +787,7 @@ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id, const mbedtls_ssl_ciphersuite_t *suite_info; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ - defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) mbedtls_pk_type_t sig_type; #endif @@ -2961,7 +2955,7 @@ static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl ) return( ret ); } -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) +#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) dig_signed = p; dig_signed_len = len; #endif @@ -3050,7 +3044,7 @@ curve_matching_done: /* * 3.1: Choose hash algorithm: - * A: For TLS 1.2, obey signature-hash-algorithm extension + * A: For TLS 1.2, obey signature-hash-algorithm extension * to choose appropriate hash. * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1 * (RFC 4492, Sec. 5.4) @@ -3071,7 +3065,7 @@ curve_matching_done: sig_alg ) ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - /* (... because we choose a cipher suite + /* (... because we choose a cipher suite * only if there is a matching hash.) */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } @@ -3750,7 +3744,10 @@ static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) /* Read the message without adding it to the checksum */ do { - if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 ) + do ret = mbedtls_ssl_read_record_layer( ssl ); + while( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); + + if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret ); return( ret ); @@ -3758,7 +3755,8 @@ static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) ret = mbedtls_ssl_handle_message_type( ssl ); - } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ); + } while( MBEDTLS_ERR_SSL_NON_FATAL == ret || + MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret ); if( 0 != ret ) { diff --git a/thirdparty/mbedtls/library/ssl_ticket.c b/thirdparty/mbedtls/library/ssl_ticket.c index 4d9116d214..a2b304869e 100644 --- a/thirdparty/mbedtls/library/ssl_ticket.c +++ b/thirdparty/mbedtls/library/ssl_ticket.c @@ -36,14 +36,10 @@ #endif #include "mbedtls/ssl_ticket.h" +#include "mbedtls/platform_util.h" #include <string.h> -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * Initialze context */ @@ -83,7 +79,7 @@ static int ssl_ticket_gen_key( mbedtls_ssl_ticket_context *ctx, mbedtls_cipher_get_key_bitlen( &key->ctx ), MBEDTLS_ENCRYPT ); - mbedtls_zeroize( buf, sizeof( buf ) ); + mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } @@ -483,7 +479,7 @@ void mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx ) mbedtls_mutex_free( &ctx->mutex ); #endif - mbedtls_zeroize( ctx, sizeof( mbedtls_ssl_ticket_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_ticket_context ) ); } #endif /* MBEDTLS_SSL_TICKET_C */ diff --git a/thirdparty/mbedtls/library/ssl_tls.c b/thirdparty/mbedtls/library/ssl_tls.c index 236e52d767..e8e0cd854b 100644 --- a/thirdparty/mbedtls/library/ssl_tls.c +++ b/thirdparty/mbedtls/library/ssl_tls.c @@ -46,6 +46,7 @@ #include "mbedtls/debug.h" #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -53,11 +54,6 @@ #include "mbedtls/oid.h" #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* Length of the "epoch" field in the record header */ static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl ) { @@ -269,8 +265,8 @@ exit: mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); - mbedtls_zeroize( padding, sizeof( padding ) ); - mbedtls_zeroize( sha1sum, sizeof( sha1sum ) ); + mbedtls_platform_zeroize( padding, sizeof( padding ) ); + mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) ); return( ret ); } @@ -367,8 +363,8 @@ static int tls1_prf( const unsigned char *secret, size_t slen, mbedtls_md_free( &md_ctx ); - mbedtls_zeroize( tmp, sizeof( tmp ) ); - mbedtls_zeroize( h_i, sizeof( h_i ) ); + mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); + mbedtls_platform_zeroize( h_i, sizeof( h_i ) ); return( 0 ); } @@ -432,8 +428,8 @@ static int tls_prf_generic( mbedtls_md_type_t md_type, mbedtls_md_free( &md_ctx ); - mbedtls_zeroize( tmp, sizeof( tmp ) ); - mbedtls_zeroize( h_i, sizeof( h_i ) ); + mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); + mbedtls_platform_zeroize( h_i, sizeof( h_i ) ); return( 0 ); } @@ -642,7 +638,8 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) return( ret ); } - mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) ); + mbedtls_platform_zeroize( handshake->premaster, + sizeof(handshake->premaster) ); } else MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); @@ -653,7 +650,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) memcpy( tmp, handshake->randbytes, 64 ); memcpy( handshake->randbytes, tmp + 32, 32 ); memcpy( handshake->randbytes + 32, tmp, 32 ); - mbedtls_zeroize( tmp, sizeof( tmp ) ); + mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); /* * SSLv3: @@ -681,7 +678,8 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 ); MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 ); - mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) ); + mbedtls_platform_zeroize( handshake->randbytes, + sizeof( handshake->randbytes ) ); /* * Determine the appropriate key, IV and MAC length. @@ -855,8 +853,13 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { - mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len ); - mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len ); + /* For HMAC-based ciphersuites, initialize the HMAC transforms. + For AEAD-based ciphersuites, there is nothing to do here. */ + if( mac_key_len != 0 ) + { + mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len ); + mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len ); + } } else #endif @@ -943,7 +946,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) } #endif /* MBEDTLS_CIPHER_MODE_CBC */ - mbedtls_zeroize( keyblk, sizeof( keyblk ) ); + mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) ); #if defined(MBEDTLS_ZLIB_SUPPORT) // Initialize compression @@ -1269,7 +1272,7 @@ static void ssl_mac( mbedtls_md_context_t *md_ctx, #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ ( defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) ) + ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C)) ) #define SSL_SOME_MODES_USE_MAC #endif @@ -1470,7 +1473,7 @@ static int ssl_encrypt_buf( mbedtls_ssl_context *ssl ) else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) + ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) ) if( mode == MBEDTLS_MODE_CBC ) { int ret; @@ -1586,7 +1589,7 @@ static int ssl_encrypt_buf( mbedtls_ssl_context *ssl ) } else #endif /* MBEDTLS_CIPHER_MODE_CBC && - ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */ + ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); @@ -1730,7 +1733,7 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl ) else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) + ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) ) if( mode == MBEDTLS_MODE_CBC ) { /* @@ -1942,7 +1945,7 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl ) } else #endif /* MBEDTLS_CIPHER_MODE_CBC && - ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */ + ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); @@ -2103,6 +2106,7 @@ static int ssl_compress_buf( mbedtls_ssl_context *ssl ) { int ret; unsigned char *msg_post = ssl->out_msg; + ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf; size_t len_pre = ssl->out_msglen; unsigned char *msg_pre = ssl->compress_buf; @@ -2122,7 +2126,7 @@ static int ssl_compress_buf( mbedtls_ssl_context *ssl ) ssl->transform_out->ctx_deflate.next_in = msg_pre; ssl->transform_out->ctx_deflate.avail_in = len_pre; ssl->transform_out->ctx_deflate.next_out = msg_post; - ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN; + ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN - bytes_written; ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) @@ -2132,7 +2136,7 @@ static int ssl_compress_buf( mbedtls_ssl_context *ssl ) } ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN - - ssl->transform_out->ctx_deflate.avail_out; + ssl->transform_out->ctx_deflate.avail_out - bytes_written; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ", ssl->out_msglen ) ); @@ -2149,6 +2153,7 @@ static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) { int ret; unsigned char *msg_post = ssl->in_msg; + ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf; size_t len_pre = ssl->in_msglen; unsigned char *msg_pre = ssl->compress_buf; @@ -2168,7 +2173,8 @@ static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) ssl->transform_in->ctx_inflate.next_in = msg_pre; ssl->transform_in->ctx_inflate.avail_in = len_pre; ssl->transform_in->ctx_inflate.next_out = msg_post; - ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN; + ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_BUFFER_LEN - + header_bytes; ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) @@ -2177,8 +2183,8 @@ static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } - ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN - - ssl->transform_in->ctx_inflate.avail_out; + ssl->in_msglen = MBEDTLS_SSL_BUFFER_LEN - + ssl->transform_in->ctx_inflate.avail_out - header_bytes; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ", ssl->in_msglen ) ); @@ -2332,7 +2338,10 @@ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) * that will end up being dropped. */ if( ssl_check_timer( ssl ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) ); ret = MBEDTLS_ERR_SSL_TIMEOUT; + } else { len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf ); @@ -2434,6 +2443,14 @@ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) if( ret < 0 ) return( ret ); + if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "f_recv returned %d bytes but only %lu were requested", + ret, (unsigned long)len ) ); + return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); + } + ssl->in_left += ret; } } @@ -2481,6 +2498,14 @@ int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) if( ret <= 0 ) return( ret ); + if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "f_send returned %d bytes but only %lu bytes were sent", + ret, (unsigned long)ssl->out_left ) ); + return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); + } + ssl->out_left -= ret; } @@ -3064,7 +3089,7 @@ static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl ) if( ssl_bitmask_check( bitmask, msg_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) ); - return( MBEDTLS_ERR_SSL_WANT_READ ); + return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) ); @@ -3141,9 +3166,11 @@ int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) int ret; unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; - /* ssl->handshake is NULL when receiving ClientHello for renego */ if( ssl->handshake != NULL && - recv_msg_seq != ssl->handshake->in_msg_seq ) + ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && + recv_msg_seq != ssl->handshake->in_msg_seq ) || + ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && + ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) ) { /* Retransmit only on last message from previous flight, to avoid * too many retransmissions. @@ -3170,7 +3197,7 @@ int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) ssl->handshake->in_msg_seq ) ); } - return( MBEDTLS_ERR_SSL_WANT_READ ); + return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } /* Wait until message completion to increment in_msg_seq */ @@ -3573,81 +3600,23 @@ static int ssl_parse_record_header( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } - /* Check length against bounds of the current transform and version */ - if( ssl->transform_in == NULL ) - { - if( ssl->in_msglen < 1 || - ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - } - else - { - if( ssl->in_msglen < ssl->transform_in->minlen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && - ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - /* - * TLS encrypted messages can have up to 256 bytes of padding - */ - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 && - ssl->in_msglen > ssl->transform_in->minlen + - MBEDTLS_SSL_MAX_CONTENT_LEN + 256 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } -#endif - } - /* - * DTLS-related tests done last, because most of them may result in - * silently dropping the record (but not the whole datagram), and we only - * want to consider that after ensuring that the "basic" fields (type, - * version, length) are sane. + * DTLS-related tests. + * Check epoch before checking length constraint because + * the latter varies with the epoch. E.g., if a ChangeCipherSpec + * message gets duplicated before the corresponding Finished message, + * the second ChangeCipherSpec should be discarded because it belongs + * to an old epoch, but not because its length is shorter than + * the minimum record length for packets using the new record transform. + * Note that these two kinds of failures are handled differently, + * as an unexpected record is silently skipped but an invalid + * record leads to the entire datagram being dropped. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1]; - /* Drop unexpected ChangeCipherSpec messages */ - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && - ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && - ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); - } - - /* Drop unexpected ApplicationData records, - * except at the beginning of renegotiations */ - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && - ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER -#if defined(MBEDTLS_SSL_RENEGOTIATION) - && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && - ssl->state == MBEDTLS_SSL_SERVER_HELLO ) -#endif - ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); - } - /* Check epoch (and sequence number) with DTLS */ if( rec_epoch != ssl->in_epoch ) { @@ -3687,9 +3656,74 @@ static int ssl_parse_record_header( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #endif + + /* Drop unexpected ChangeCipherSpec messages */ + if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && + ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && + ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) ); + return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); + } + + /* Drop unexpected ApplicationData records, + * except at the beginning of renegotiations */ + if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && + ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER +#if defined(MBEDTLS_SSL_RENEGOTIATION) + && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->state == MBEDTLS_SSL_SERVER_HELLO ) +#endif + ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); + return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); + } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ + + /* Check length against bounds of the current transform and version */ + if( ssl->transform_in == NULL ) + { + if( ssl->in_msglen < 1 || + ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); + return( MBEDTLS_ERR_SSL_INVALID_RECORD ); + } + } + else + { + if( ssl->in_msglen < ssl->transform_in->minlen ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); + return( MBEDTLS_ERR_SSL_INVALID_RECORD ); + } + +#if defined(MBEDTLS_SSL_PROTO_SSL3) + if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && + ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); + return( MBEDTLS_ERR_SSL_INVALID_RECORD ); + } +#endif +#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) + /* + * TLS encrypted messages can have up to 256 bytes of padding + */ + if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 && + ssl->in_msglen > ssl->transform_in->minlen + + MBEDTLS_SSL_MAX_CONTENT_LEN + 256 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); + return( MBEDTLS_ERR_SSL_INVALID_RECORD ); + } +#endif + } + return( 0 ); } @@ -3778,7 +3812,10 @@ int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl ) { do { - if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 ) + do ret = mbedtls_ssl_read_record_layer( ssl ); + while( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); + + if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret ); return( ret ); @@ -3786,11 +3823,12 @@ int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl ) ret = mbedtls_ssl_handle_message_type( ssl ); - } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ); + } while( MBEDTLS_ERR_SSL_NON_FATAL == ret || + MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret ); if( 0 != ret ) { - MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret ); + MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret ); return( ret ); } @@ -3828,11 +3866,6 @@ int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl ) * (2) Alert messages: * Consume whole record content, in_msglen = 0. * - * NOTE: This needs to be fixed, since like for - * handshake messages it is allowed to have - * multiple alerts witin a single record. - * Internal reference IOTSSL-1321. - * * (3) Change cipher spec: * Consume whole record content, in_msglen = 0. * @@ -3860,12 +3893,12 @@ int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl ) */ /* Notes: - * (1) in_hslen is *NOT* necessarily the size of the + * (1) in_hslen is not necessarily the size of the * current handshake content: If DTLS handshake * fragmentation is used, that's the fragment * size instead. Using the total handshake message - * size here is FAULTY and should be changed at - * some point. Internal reference IOTSSL-1414. + * size here is faulty and should be changed at + * some point. * (2) While it doesn't seem to cause problems, one * has to be very careful not to assume that in_hslen * is always <= in_msglen in a sensible communication. @@ -3916,12 +3949,6 @@ int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl ) return( 0 ); } - /* Need to fetch a new record */ - -#if defined(MBEDTLS_SSL_PROTO_DTLS) -read_record_header: -#endif - /* Current record either fully processed or to be discarded. */ if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 ) @@ -3956,7 +3983,7 @@ read_record_header: } /* Get next record */ - goto read_record_header; + return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } #endif return( ret ); @@ -3975,7 +4002,13 @@ read_record_header: /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + { ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl ); + if( ssl->next_record_offset < ssl->in_left ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) ); + } + } else #endif ssl->in_left = 0; @@ -4022,7 +4055,7 @@ read_record_header: ssl->in_left = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) ); - goto read_record_header; + return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } return( ret ); @@ -4043,46 +4076,6 @@ read_record_header: } } - /* - * When we sent the last flight of the handshake, we MUST respond to a - * retransmit of the peer's previous flight with a retransmit. (In - * practice, only the Finished message will make it, other messages - * including CCS use the old transform so they're dropped as invalid.) - * - * If the record we received is not a handshake message, however, it - * means the peer received our last flight so we can clean up - * handshake info. - * - * This check needs to be done before prepare_handshake() due to an edge - * case: if the client immediately requests renegotiation, this - * finishes the current handshake first, avoiding the new ClientHello - * being mistaken for an ancient message in the current handshake. - */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->handshake != NULL && - ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) - { - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "received retransmit of last flight" ) ); - - if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); - return( ret ); - } - - return( MBEDTLS_ERR_SSL_WANT_READ ); - } - else - { - ssl_handshake_wrapup_free_hs_transform( ssl ); - } - } -#endif - return( 0 ); } @@ -4127,7 +4120,7 @@ int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); + MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) ); /* Will be handled when trying to parse ServerHello */ return( 0 ); } @@ -4149,6 +4142,15 @@ int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) return MBEDTLS_ERR_SSL_NON_FATAL; } +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && + ssl->handshake != NULL && + ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) + { + ssl_handshake_wrapup_free_hs_transform( ssl ); + } +#endif + return( 0 ); } @@ -5026,9 +5028,9 @@ static void ssl_calc_finished_ssl( mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); - mbedtls_zeroize( md5sum, sizeof( md5sum ) ); - mbedtls_zeroize( sha1sum, sizeof( sha1sum ) ); + mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); + mbedtls_platform_zeroize( md5sum, sizeof( md5sum ) ); + mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } @@ -5087,7 +5089,7 @@ static void ssl_calc_finished_tls( mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); + mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } @@ -5137,7 +5139,7 @@ static void ssl_calc_finished_tls_sha256( mbedtls_sha256_free( &sha256 ); - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); + mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } @@ -5186,7 +5188,7 @@ static void ssl_calc_finished_tls_sha384( mbedtls_sha512_free( &sha512 ); - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); + mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } @@ -6105,7 +6107,7 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, if( conf->psk != NULL ) { - mbedtls_zeroize( conf->psk, conf->psk_len ); + mbedtls_platform_zeroize( conf->psk, conf->psk_len ); mbedtls_free( conf->psk ); conf->psk = NULL; @@ -6148,7 +6150,8 @@ int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, if( ssl->handshake->psk != NULL ) { - mbedtls_zeroize( ssl->handshake->psk, ssl->handshake->psk_len ); + mbedtls_platform_zeroize( ssl->handshake->psk, + ssl->handshake->psk_len ); mbedtls_free( ssl->handshake->psk ); ssl->handshake->psk_len = 0; } @@ -6278,7 +6281,7 @@ int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ) if( ssl->hostname != NULL ) { - mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) ); + mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } @@ -6485,6 +6488,61 @@ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ) return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); } +int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ) +{ + /* + * Case A: We're currently holding back + * a message for further processing. + */ + + if( ssl->keep_current_message == 1 ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) ); + return( 1 ); + } + + /* + * Case B: Further records are pending in the current datagram. + */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && + ssl->in_left > ssl->next_record_offset ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) ); + return( 1 ); + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + /* + * Case C: A handshake message is being processed. + */ + + if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) ); + return( 1 ); + } + + /* + * Case D: An application data message is being processed + */ + if( ssl->in_offt != NULL ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) ); + return( 1 ); + } + + /* + * In all other cases, the rest of the message can be dropped. + * As in ssl_read_record_layer, this needs to be adapted if + * we implement support for multiple alerts in single records. + */ + + MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) ); + return( 0 ); +} + uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ) { if( ssl->session != NULL ) @@ -6892,42 +6950,8 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) } } - /* - * TODO - * - * The logic should be streamlined here: - * - * Instead of - * - * - Manually checking whether ssl->in_offt is NULL - * - Fetching a new record if yes - * - Setting ssl->in_offt if one finds an application record - * - Resetting keep_current_message after handling the application data - * - * one should - * - * - Adapt read_record to set ssl->in_offt automatically - * when a new application data record is processed. - * - Always call mbedtls_ssl_read_record here. - * - * This way, the logic of ssl_read would be much clearer: - * - * (1) Always call record layer and see what kind of record is on - * and have it ready for consumption (in particular, in_offt - * properly set for application data records). - * (2) If it's application data (either freshly fetched - * or something already being partially processed), - * serve the read request from it. - * (3) If it's something different from application data, - * handle it accordingly, e.g. potentially start a - * renegotiation. - * - * This will also remove the need to manually reset - * ssl->keep_current_message = 0 below. - * - */ - - if( ssl->in_offt == NULL ) + /* Loop as long as no application data record is available */ + while( ssl->in_offt == NULL ) { /* Start timer if not already running */ if( ssl->f_get_timer != NULL && @@ -6981,7 +7005,9 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - return( MBEDTLS_ERR_SSL_WANT_READ ); + { + continue; + } #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } @@ -6996,7 +7022,9 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - return( MBEDTLS_ERR_SSL_WANT_READ ); + { + continue; + } #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } @@ -7069,7 +7097,25 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) } } - return( MBEDTLS_ERR_SSL_WANT_READ ); + /* At this point, we don't know whether the renegotiation has been + * completed or not. The cases to consider are the following: + * 1) The renegotiation is complete. In this case, no new record + * has been read yet. + * 2) The renegotiation is incomplete because the client received + * an application data record while awaiting the ServerHello. + * 3) The renegotiation is incomplete because the client received + * a non-handshake, non-application data message while awaiting + * the ServerHello. + * In each of these case, looping will be the proper action: + * - For 1), the next iteration will read a new record and check + * if it's application data. + * - For 2), the loop condition isn't satisfied as application data + * is present, hence continue is the same as break + * - For 3), the loop condition is satisfied and read_record + * will re-deliver the message that was held back by the client + * when expecting the ServerHello. + */ + continue; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) @@ -7324,7 +7370,7 @@ void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ) mbedtls_md_free( &transform->md_ctx_enc ); mbedtls_md_free( &transform->md_ctx_dec ); - mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); + mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) @@ -7384,7 +7430,7 @@ void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake ) #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( handshake->psk != NULL ) { - mbedtls_zeroize( handshake->psk, handshake->psk_len ); + mbedtls_platform_zeroize( handshake->psk, handshake->psk_len ); mbedtls_free( handshake->psk ); } #endif @@ -7414,7 +7460,8 @@ void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake ) ssl_flight_free( handshake->flight ); #endif - mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) ); + mbedtls_platform_zeroize( handshake, + sizeof( mbedtls_ssl_handshake_params ) ); } void mbedtls_ssl_session_free( mbedtls_ssl_session *session ) @@ -7434,7 +7481,7 @@ void mbedtls_ssl_session_free( mbedtls_ssl_session *session ) mbedtls_free( session->ticket ); #endif - mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) ); + mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) ); } /* @@ -7449,20 +7496,20 @@ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) if( ssl->out_buf != NULL ) { - mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN ); + mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN ); mbedtls_free( ssl->out_buf ); } if( ssl->in_buf != NULL ) { - mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN ); + mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN ); mbedtls_free( ssl->in_buf ); } #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->compress_buf != NULL ) { - mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN ); + mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN ); mbedtls_free( ssl->compress_buf ); } #endif @@ -7493,7 +7540,7 @@ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_X509_CRT_PARSE_C) if( ssl->hostname != NULL ) { - mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) ); + mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } #endif @@ -7513,7 +7560,7 @@ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) ); /* Actually clear after last debug message */ - mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); + mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); } /* @@ -7740,11 +7787,17 @@ void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ) #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( conf->psk != NULL ) { - mbedtls_zeroize( conf->psk, conf->psk_len ); - mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len ); + mbedtls_platform_zeroize( conf->psk, conf->psk_len ); mbedtls_free( conf->psk ); - mbedtls_free( conf->psk_identity ); + conf->psk = NULL; conf->psk_len = 0; + } + + if( conf->psk_identity != NULL ) + { + mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len ); + mbedtls_free( conf->psk_identity ); + conf->psk_identity = NULL; conf->psk_identity_len = 0; } #endif @@ -7753,7 +7806,7 @@ void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ) ssl_key_cert_free( conf->key_cert ); #endif - mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) ); + mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) ); } #if defined(MBEDTLS_PK_C) && \ diff --git a/thirdparty/mbedtls/library/threading.c b/thirdparty/mbedtls/library/threading.c index 07586756f2..f1c37245c7 100644 --- a/thirdparty/mbedtls/library/threading.c +++ b/thirdparty/mbedtls/library/threading.c @@ -111,8 +111,12 @@ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * mbedtls_mutex_lock = mutex_lock; mbedtls_mutex_unlock = mutex_unlock; +#if defined(MBEDTLS_FS_IO) mbedtls_mutex_init( &mbedtls_threading_readdir_mutex ); +#endif +#if defined(MBEDTLS_HAVE_TIME_DATE) mbedtls_mutex_init( &mbedtls_threading_gmtime_mutex ); +#endif } /* @@ -120,8 +124,12 @@ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * */ void mbedtls_threading_free_alt( void ) { +#if defined(MBEDTLS_FS_IO) mbedtls_mutex_free( &mbedtls_threading_readdir_mutex ); +#endif +#if defined(MBEDTLS_HAVE_TIME_DATE) mbedtls_mutex_free( &mbedtls_threading_gmtime_mutex ); +#endif } #endif /* MBEDTLS_THREADING_ALT */ @@ -131,7 +139,11 @@ void mbedtls_threading_free_alt( void ) #ifndef MUTEX_INIT #define MUTEX_INIT #endif +#if defined(MBEDTLS_FS_IO) mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex MUTEX_INIT; +#endif +#if defined(MBEDTLS_HAVE_TIME_DATE) mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT; +#endif #endif /* MBEDTLS_THREADING_C */ diff --git a/thirdparty/mbedtls/library/timing.c b/thirdparty/mbedtls/library/timing.c index 35d6d89e2b..6a30e51259 100644 --- a/thirdparty/mbedtls/library/timing.c +++ b/thirdparty/mbedtls/library/timing.c @@ -39,7 +39,7 @@ #if !defined(MBEDTLS_TIMING_ALT) #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ - !defined(__APPLE__) && !defined(_WIN32) + !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) #error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h" #endif diff --git a/thirdparty/mbedtls/library/version_features.c b/thirdparty/mbedtls/library/version_features.c index da47e3d753..e8e448f6f8 100644 --- a/thirdparty/mbedtls/library/version_features.c +++ b/thirdparty/mbedtls/library/version_features.c @@ -90,6 +90,9 @@ static const char *features[] = { #if defined(MBEDTLS_ARC4_ALT) "MBEDTLS_ARC4_ALT", #endif /* MBEDTLS_ARC4_ALT */ +#if defined(MBEDTLS_ARIA_ALT) + "MBEDTLS_ARIA_ALT", +#endif /* MBEDTLS_ARIA_ALT */ #if defined(MBEDTLS_BLOWFISH_ALT) "MBEDTLS_BLOWFISH_ALT", #endif /* MBEDTLS_BLOWFISH_ALT */ @@ -237,6 +240,9 @@ static const char *features[] = { #if defined(MBEDTLS_AES_ROM_TABLES) "MBEDTLS_AES_ROM_TABLES", #endif /* MBEDTLS_AES_ROM_TABLES */ +#if defined(MBEDTLS_AES_FEWER_TABLES) + "MBEDTLS_AES_FEWER_TABLES", +#endif /* MBEDTLS_AES_FEWER_TABLES */ #if defined(MBEDTLS_CAMELLIA_SMALL_MEMORY) "MBEDTLS_CAMELLIA_SMALL_MEMORY", #endif /* MBEDTLS_CAMELLIA_SMALL_MEMORY */ @@ -306,6 +312,9 @@ static const char *features[] = { #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) "MBEDTLS_ECP_DP_CURVE25519_ENABLED", #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) + "MBEDTLS_ECP_DP_CURVE448_ENABLED", +#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ #if defined(MBEDTLS_ECP_NIST_OPTIM) "MBEDTLS_ECP_NIST_OPTIM", #endif /* MBEDTLS_ECP_NIST_OPTIM */ @@ -525,6 +534,9 @@ static const char *features[] = { #if defined(MBEDTLS_CAMELLIA_C) "MBEDTLS_CAMELLIA_C", #endif /* MBEDTLS_CAMELLIA_C */ +#if defined(MBEDTLS_ARIA_C) + "MBEDTLS_ARIA_C", +#endif /* MBEDTLS_ARIA_C */ #if defined(MBEDTLS_CCM_C) "MBEDTLS_CCM_C", #endif /* MBEDTLS_CCM_C */ diff --git a/thirdparty/mbedtls/library/x509_crl.c b/thirdparty/mbedtls/library/x509_crl.c index b0f39d428b..8450f87e03 100644 --- a/thirdparty/mbedtls/library/x509_crl.c +++ b/thirdparty/mbedtls/library/x509_crl.c @@ -39,6 +39,7 @@ #include "mbedtls/x509_crl.h" #include "mbedtls/oid.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -66,11 +67,6 @@ #include <stdio.h> #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * Version ::= INTEGER { v1(0), v2(1) } */ @@ -616,7 +612,7 @@ int mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path ) ret = mbedtls_x509_crl_parse( chain, buf, n ); - mbedtls_zeroize( buf, n ); + mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); @@ -737,7 +733,7 @@ void mbedtls_x509_crl_free( mbedtls_x509_crl *crl ) { name_prv = name_cur; name_cur = name_cur->next; - mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); + mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } @@ -746,13 +742,14 @@ void mbedtls_x509_crl_free( mbedtls_x509_crl *crl ) { entry_prv = entry_cur; entry_cur = entry_cur->next; - mbedtls_zeroize( entry_prv, sizeof( mbedtls_x509_crl_entry ) ); + mbedtls_platform_zeroize( entry_prv, + sizeof( mbedtls_x509_crl_entry ) ); mbedtls_free( entry_prv ); } if( crl_cur->raw.p != NULL ) { - mbedtls_zeroize( crl_cur->raw.p, crl_cur->raw.len ); + mbedtls_platform_zeroize( crl_cur->raw.p, crl_cur->raw.len ); mbedtls_free( crl_cur->raw.p ); } @@ -766,7 +763,7 @@ void mbedtls_x509_crl_free( mbedtls_x509_crl *crl ) crl_prv = crl_cur; crl_cur = crl_cur->next; - mbedtls_zeroize( crl_prv, sizeof( mbedtls_x509_crl ) ); + mbedtls_platform_zeroize( crl_prv, sizeof( mbedtls_x509_crl ) ); if( crl_prv != crl ) mbedtls_free( crl_prv ); } diff --git a/thirdparty/mbedtls/library/x509_crt.c b/thirdparty/mbedtls/library/x509_crt.c index 2a5dbb8783..038eae0257 100644 --- a/thirdparty/mbedtls/library/x509_crt.c +++ b/thirdparty/mbedtls/library/x509_crt.c @@ -27,6 +27,8 @@ * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf + * + * [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf */ #if !defined(MBEDTLS_CONFIG_FILE) @@ -39,6 +41,7 @@ #include "mbedtls/x509_crt.h" #include "mbedtls/oid.h" +#include "mbedtls/platform_util.h" #include <stdio.h> #include <string.h> @@ -88,10 +91,18 @@ #endif /* !_WIN32 || EFIX64 || EFI32 */ #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} +/* + * Item in a verification chain: cert and flags for it + */ +typedef struct { + mbedtls_x509_crt *crt; + uint32_t flags; +} x509_crt_verify_chain_item; + +/* + * Max size of verification chain: end-entity + intermediates + trusted root + */ +#define X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 ) /* * Default profile @@ -160,7 +171,7 @@ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb = /* * Check md_alg against profile - * Return 0 if md_alg acceptable for this profile, -1 otherwise + * Return 0 if md_alg is acceptable for this profile, -1 otherwise */ static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile, mbedtls_md_type_t md_alg ) @@ -173,7 +184,7 @@ static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile, /* * Check pk_alg against profile - * Return 0 if pk_alg acceptable for this profile, -1 otherwise + * Return 0 if pk_alg is acceptable for this profile, -1 otherwise */ static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile, mbedtls_pk_type_t pk_alg ) @@ -186,12 +197,13 @@ static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile, /* * Check key against profile - * Return 0 if pk_alg acceptable for this profile, -1 otherwise + * Return 0 if pk is acceptable for this profile, -1 otherwise */ static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile, - mbedtls_pk_type_t pk_alg, const mbedtls_pk_context *pk ) { + const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk ); + #if defined(MBEDTLS_RSA_C) if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS ) { @@ -207,7 +219,7 @@ static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile, pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH ) { - mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id; + const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id; if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 ) return( 0 ); @@ -730,7 +742,7 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char * memcpy( p, buf, crt->raw.len ); - // Direct pointers to the new buffer + // Direct pointers to the new buffer p += crt->raw.len - len; end = crt_end = p + len; @@ -1112,7 +1124,7 @@ int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path ) ret = mbedtls_x509_crt_parse( chain, buf, n ); - mbedtls_zeroize( buf, n ); + mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); @@ -1662,7 +1674,7 @@ int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509 /* * Check that the given certificate is not revoked according to the CRL. - * Skip validation is no CRL for the given CA is present. + * Skip validation if no CRL for the given CA is present. */ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, mbedtls_x509_crl *crl_list, @@ -1707,18 +1719,14 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, flags |= MBEDTLS_X509_BADCRL_BAD_PK; md_info = mbedtls_md_info_from_type( crl_list->sig_md ); - if( md_info == NULL ) + if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 ) { - /* - * Cannot check 'unknown' hash - */ + /* Note: this can't happen except after an internal error */ flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } - mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ); - - if( x509_profile_check_key( profile, crl_list->sig_pk, &ca->pk ) != 0 ) + if( x509_profile_check_key( profile, &ca->pk ) != 0 ) flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk, @@ -1786,13 +1794,14 @@ static int x509_memcasecmp( const void *s1, const void *s2, size_t len ) /* * Return 0 if name matches wildcard, -1 otherwise */ -static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name ) +static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name ) { size_t i; size_t cn_idx = 0, cn_len = strlen( cn ); + /* We can't have a match if there is no wildcard to match */ if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' ) - return( 0 ); + return( -1 ); for( i = 0; i < cn_len; ++i ) { @@ -1884,15 +1893,40 @@ static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b } /* + * Check the signature of a certificate by its parent + */ +static int x509_crt_check_signature( const mbedtls_x509_crt *child, + mbedtls_x509_crt *parent ) +{ + const mbedtls_md_info_t *md_info; + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + + md_info = mbedtls_md_info_from_type( child->sig_md ); + if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 ) + { + /* Note: this can't happen except after an internal error */ + return( -1 ); + } + + if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, + child->sig_md, hash, mbedtls_md_get_size( md_info ), + child->sig.p, child->sig.len ) != 0 ) + { + return( -1 ); + } + + return( 0 ); +} + +/* * Check if 'parent' is a suitable parent (signing CA) for 'child'. * Return 0 if yes, -1 if not. * * top means parent is a locally-trusted certificate - * bottom means child is the end entity cert */ static int x509_crt_check_parent( const mbedtls_x509_crt *child, const mbedtls_x509_crt *parent, - int top, int bottom ) + int top ) { int need_ca_bit; @@ -1907,14 +1941,6 @@ static int x509_crt_check_parent( const mbedtls_x509_crt *child, if( top && parent->version < 3 ) need_ca_bit = 0; - /* Exception: self-signed end-entity certs that are locally trusted. */ - if( top && bottom && - child->raw.len == parent->raw.len && - memcmp( child->raw.p, parent->raw.p, child->raw.len ) == 0 ) - { - need_ca_bit = 0; - } - if( need_ca_bit && ! parent->ca_istrue ) return( -1 ); @@ -1929,86 +1955,78 @@ static int x509_crt_check_parent( const mbedtls_x509_crt *child, return( 0 ); } -static int x509_crt_verify_top( - mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca, - mbedtls_x509_crl *ca_crl, - const mbedtls_x509_crt_profile *profile, - int path_cnt, int self_cnt, uint32_t *flags, - int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), - void *p_vrfy ) +/* + * Find a suitable parent for child in candidates, or return NULL. + * + * Here suitable is defined as: + * 1. subject name matches child's issuer + * 2. if necessary, the CA bit is set and key usage allows signing certs + * 3. for trusted roots, the signature is correct + * 4. pathlen constraints are satisfied + * + * If there's a suitable candidate which is also time-valid, return the first + * such. Otherwise, return the first suitable candidate (or NULL if there is + * none). + * + * The rationale for this rule is that someone could have a list of trusted + * roots with two versions on the same root with different validity periods. + * (At least one user reported having such a list and wanted it to just work.) + * The reason we don't just require time-validity is that generally there is + * only one version, and if it's expired we want the flags to state that + * rather than NOT_TRUSTED, as would be the case if we required it here. + * + * The rationale for rule 3 (signature for trusted roots) is that users might + * have two versions of the same CA with different keys in their list, and the + * way we select the correct one is by checking the signature (as we don't + * rely on key identifier extensions). (This is one way users might choose to + * handle key rollover, another relies on self-issued certs, see [SIRO].) + * + * Arguments: + * - [in] child: certificate for which we're looking for a parent + * - [in] candidates: chained list of potential parents + * - [in] top: 1 if candidates consists of trusted roots, ie we're at the top + * of the chain, 0 otherwise + * - [in] path_cnt: number of intermediates seen so far + * - [in] self_cnt: number of self-signed intermediates seen so far + * (will never be greater than path_cnt) + * + * Return value: + * - the first suitable parent found (see above regarding time-validity) + * - NULL if no suitable parent was found + */ +static mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child, + mbedtls_x509_crt *candidates, + int top, + size_t path_cnt, + size_t self_cnt ) { - int ret; - uint32_t ca_flags = 0; - int check_path_cnt; - unsigned char hash[MBEDTLS_MD_MAX_SIZE]; - const mbedtls_md_info_t *md_info; - mbedtls_x509_crt *future_past_ca = NULL; + mbedtls_x509_crt *parent, *badtime_parent = NULL; - if( mbedtls_x509_time_is_past( &child->valid_to ) ) - *flags |= MBEDTLS_X509_BADCERT_EXPIRED; - - if( mbedtls_x509_time_is_future( &child->valid_from ) ) - *flags |= MBEDTLS_X509_BADCERT_FUTURE; - - if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_MD; - - if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_PK; - - /* - * Child is the top of the chain. Check against the trust_ca list. - */ - *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; - - md_info = mbedtls_md_info_from_type( child->sig_md ); - if( md_info == NULL ) + for( parent = candidates; parent != NULL; parent = parent->next ) { - /* - * Cannot check 'unknown', no need to try any CA - */ - trust_ca = NULL; - } - else - mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); - - for( /* trust_ca */ ; trust_ca != NULL; trust_ca = trust_ca->next ) - { - if( x509_crt_check_parent( child, trust_ca, 1, path_cnt == 0 ) != 0 ) + /* basic parenting skills (name, CA bit, key usage) */ + if( x509_crt_check_parent( child, parent, top ) != 0 ) continue; - check_path_cnt = path_cnt + 1; - - /* - * Reduce check_path_cnt to check against if top of the chain is - * the same as the trusted CA - */ - if( child->subject_raw.len == trust_ca->subject_raw.len && - memcmp( child->subject_raw.p, trust_ca->subject_raw.p, - child->issuer_raw.len ) == 0 ) - { - check_path_cnt--; - } - - /* Self signed certificates do not count towards the limit */ - if( trust_ca->max_pathlen > 0 && - trust_ca->max_pathlen < check_path_cnt - self_cnt ) + /* +1 because stored max_pathlen is 1 higher that the actual value */ + if( parent->max_pathlen > 0 && + (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt ) { continue; } - if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &trust_ca->pk, - child->sig_md, hash, mbedtls_md_get_size( md_info ), - child->sig.p, child->sig.len ) != 0 ) + /* Signature */ + if( top && x509_crt_check_signature( child, parent ) != 0 ) { continue; } - if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) || - mbedtls_x509_time_is_future( &trust_ca->valid_from ) ) + /* optional time check */ + if( mbedtls_x509_time_is_past( &parent->valid_to ) || + mbedtls_x509_time_is_future( &parent->valid_from ) ) { - if ( future_past_ca == NULL ) - future_past_ca = trust_ca; + if( badtime_parent == NULL ) + badtime_parent = parent; continue; } @@ -2016,190 +2034,292 @@ static int x509_crt_verify_top( break; } - if( trust_ca != NULL || ( trust_ca = future_past_ca ) != NULL ) - { - /* - * Top of chain is signed by a trusted CA - */ - *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED; + if( parent == NULL ) + parent = badtime_parent; - if( x509_profile_check_key( profile, child->sig_pk, &trust_ca->pk ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; - } + return( parent ); +} - /* - * If top of chain is not the same as the trusted CA send a verify request - * to the callback for any issues with validity and CRL presence for the - * trusted CA certificate. - */ - if( trust_ca != NULL && - ( child->subject_raw.len != trust_ca->subject_raw.len || - memcmp( child->subject_raw.p, trust_ca->subject_raw.p, - child->issuer_raw.len ) != 0 ) ) - { -#if defined(MBEDTLS_X509_CRL_PARSE_C) - /* Check trusted CA's CRL for the chain's top crt */ - *flags |= x509_crt_verifycrl( child, trust_ca, ca_crl, profile ); -#else - ((void) ca_crl); -#endif +/* + * Find a parent in trusted CAs or the provided chain, or return NULL. + * + * Searches in trusted CAs first, and return the first suitable parent found + * (see find_parent_in() for definition of suitable). + * + * Arguments: + * - [in] child: certificate for which we're looking for a parent, followed + * by a chain of possible intermediates + * - [in] trust_ca: locally trusted CAs + * - [out] 1 if parent was found in trust_ca, 0 if found in provided chain + * - [in] path_cnt: number of intermediates seen so far + * - [in] self_cnt: number of self-signed intermediates seen so far + * (will always be no greater than path_cnt) + * + * Return value: + * - the first suitable parent found (see find_parent_in() for "suitable") + * - NULL if no suitable parent was found + */ +static mbedtls_x509_crt *x509_crt_find_parent( mbedtls_x509_crt *child, + mbedtls_x509_crt *trust_ca, + int *parent_is_trusted, + size_t path_cnt, + size_t self_cnt ) +{ + mbedtls_x509_crt *parent; - if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) ) - ca_flags |= MBEDTLS_X509_BADCERT_EXPIRED; + /* Look for a parent in trusted CAs */ + *parent_is_trusted = 1; + parent = x509_crt_find_parent_in( child, trust_ca, 1, path_cnt, self_cnt ); - if( mbedtls_x509_time_is_future( &trust_ca->valid_from ) ) - ca_flags |= MBEDTLS_X509_BADCERT_FUTURE; + if( parent != NULL ) + return( parent ); - if( NULL != f_vrfy ) - { - if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1, - &ca_flags ) ) != 0 ) - { - return( ret ); - } - } - } + /* Look for a parent upwards the chain */ + *parent_is_trusted = 0; + return( x509_crt_find_parent_in( child, child->next, 0, path_cnt, self_cnt ) ); +} - /* Call callback on top cert */ - if( NULL != f_vrfy ) +/* + * Check if an end-entity certificate is locally trusted + * + * Currently we require such certificates to be self-signed (actually only + * check for self-issued as self-signatures are not checked) + */ +static int x509_crt_check_ee_locally_trusted( + mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca ) +{ + mbedtls_x509_crt *cur; + + /* must be self-issued */ + if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 ) + return( -1 ); + + /* look for an exact match with trusted cert */ + for( cur = trust_ca; cur != NULL; cur = cur->next ) { - if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) - return( ret ); + if( crt->raw.len == cur->raw.len && + memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 ) + { + return( 0 ); + } } - *flags |= ca_flags; - - return( 0 ); + /* too bad */ + return( -1 ); } -static int x509_crt_verify_child( - mbedtls_x509_crt *child, mbedtls_x509_crt *parent, - mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, +/* + * Build and verify a certificate chain + * + * Given a peer-provided list of certificates EE, C1, ..., Cn and + * a list of trusted certs R1, ... Rp, try to build and verify a chain + * EE, Ci1, ... Ciq [, Rj] + * such that every cert in the chain is a child of the next one, + * jumping to a trusted root as early as possible. + * + * Verify that chain and return it with flags for all issues found. + * + * Special cases: + * - EE == Rj -> return a one-element list containing it + * - EE, Ci1, ..., Ciq cannot be continued with a trusted root + * -> return that chain with NOT_TRUSTED set on Ciq + * + * Arguments: + * - [in] crt: the cert list EE, C1, ..., Cn + * - [in] trust_ca: the trusted list R1, ..., Rp + * - [in] ca_crl, profile: as in verify_with_profile() + * - [out] ver_chain, chain_len: the built and verified chain + * + * Return value: + * - non-zero if the chain could not be fully built and examined + * - 0 is the chain was successfully built and examined, + * even if it was found to be invalid + */ +static int x509_crt_verify_chain( + mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, - int path_cnt, int self_cnt, uint32_t *flags, - int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), - void *p_vrfy ) + x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE], + size_t *chain_len ) { - int ret; - uint32_t parent_flags = 0; - unsigned char hash[MBEDTLS_MD_MAX_SIZE]; - mbedtls_x509_crt *grandparent; - const mbedtls_md_info_t *md_info; + uint32_t *flags; + mbedtls_x509_crt *child; + mbedtls_x509_crt *parent; + int parent_is_trusted = 0; + int child_is_trusted = 0; + size_t self_cnt = 0; - /* Counting intermediate self signed certificates */ - if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) - self_cnt++; + child = crt; + *chain_len = 0; - /* path_cnt is 0 for the first intermediate CA */ - if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) - { - /* return immediately as the goal is to avoid unbounded recursion */ - return( MBEDTLS_ERR_X509_FATAL_ERROR ); - } + while( 1 ) { + /* Add certificate to the verification chain */ + ver_chain[*chain_len].crt = child; + flags = &ver_chain[*chain_len].flags; + ++*chain_len; - if( mbedtls_x509_time_is_past( &child->valid_to ) ) - *flags |= MBEDTLS_X509_BADCERT_EXPIRED; + /* Check time-validity (all certificates) */ + if( mbedtls_x509_time_is_past( &child->valid_to ) ) + *flags |= MBEDTLS_X509_BADCERT_EXPIRED; - if( mbedtls_x509_time_is_future( &child->valid_from ) ) - *flags |= MBEDTLS_X509_BADCERT_FUTURE; + if( mbedtls_x509_time_is_future( &child->valid_from ) ) + *flags |= MBEDTLS_X509_BADCERT_FUTURE; - if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_MD; + /* Stop here for trusted roots (but not for trusted EE certs) */ + if( child_is_trusted ) + return( 0 ); - if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_PK; + /* Check signature algorithm: MD & PK algs */ + if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_MD; - md_info = mbedtls_md_info_from_type( child->sig_md ); - if( md_info == NULL ) - { - /* - * Cannot check 'unknown' hash - */ - *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; - } - else - { - mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); + if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_PK; - if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; + /* Special case: EE certs that are locally trusted */ + if( *chain_len == 1 && + x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 ) + { + return( 0 ); + } - if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, - child->sig_md, hash, mbedtls_md_get_size( md_info ), - child->sig.p, child->sig.len ) != 0 ) + /* Look for a parent in trusted CAs or up the chain */ + parent = x509_crt_find_parent( child, trust_ca, &parent_is_trusted, + *chain_len - 1, self_cnt ); + + /* No parent? We're done here */ + if( parent == NULL ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + return( 0 ); + } + + /* Count intermediate self-issued (not necessarily self-signed) certs. + * These can occur with some strategies for key rollover, see [SIRO], + * and should be excluded from max_pathlen checks. */ + if( *chain_len != 1 && + x509_name_cmp( &child->issuer, &child->subject ) == 0 ) + { + self_cnt++; } - } + + /* path_cnt is 0 for the first intermediate CA, + * and if parent is trusted it's not an intermediate CA */ + if( ! parent_is_trusted && + *chain_len > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) + { + /* return immediately to avoid overflow the chain array */ + return( MBEDTLS_ERR_X509_FATAL_ERROR ); + } + + /* if parent is trusted, the signature was checked by find_parent() */ + if( ! parent_is_trusted && x509_crt_check_signature( child, parent ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + + /* check size of signing key */ + if( x509_profile_check_key( profile, &parent->pk ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; #if defined(MBEDTLS_X509_CRL_PARSE_C) - /* Check trusted CA's CRL for the given crt */ - *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); + /* Check trusted CA's CRL for the given crt */ + *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile ); +#else + (void) ca_crl; #endif - /* Look for a grandparent in trusted CAs */ - for( grandparent = trust_ca; - grandparent != NULL; - grandparent = grandparent->next ) + /* prepare for next iteration */ + child = parent; + parent = NULL; + child_is_trusted = parent_is_trusted; + } +} + +/* + * Check for CN match + */ +static int x509_crt_check_cn( const mbedtls_x509_buf *name, + const char *cn, size_t cn_len ) +{ + /* try exact match */ + if( name->len == cn_len && + x509_memcasecmp( cn, name->p, cn_len ) == 0 ) { - if( x509_crt_check_parent( parent, grandparent, - 0, path_cnt == 0 ) == 0 ) - break; + return( 0 ); } - if( grandparent != NULL ) + /* try wildcard match */ + if( x509_check_wildcard( cn, name ) == 0 ) { - ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, - path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); - if( ret != 0 ) - return( ret ); + return( 0 ); } - else + + return( -1 ); +} + +/* + * Verify the requested CN - only call this if cn is not NULL! + */ +static void x509_crt_verify_name( const mbedtls_x509_crt *crt, + const char *cn, + uint32_t *flags ) +{ + const mbedtls_x509_name *name; + const mbedtls_x509_sequence *cur; + size_t cn_len = strlen( cn ); + + if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { - /* Look for a grandparent upwards the chain */ - for( grandparent = parent->next; - grandparent != NULL; - grandparent = grandparent->next ) + for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next ) { - /* +2 because the current step is not yet accounted for - * and because max_pathlen is one higher than it should be. - * Also self signed certificates do not count to the limit. */ - if( grandparent->max_pathlen > 0 && - grandparent->max_pathlen < 2 + path_cnt - self_cnt ) - { - continue; - } - - if( x509_crt_check_parent( parent, grandparent, - 0, path_cnt == 0 ) == 0 ) + if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 ) break; } - /* Is our parent part of the chain or at the top? */ - if( grandparent != NULL ) - { - ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, - profile, path_cnt + 1, self_cnt, &parent_flags, - f_vrfy, p_vrfy ); - if( ret != 0 ) - return( ret ); - } - else + if( cur == NULL ) + *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; + } + else + { + for( name = &crt->subject; name != NULL; name = name->next ) { - ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, - path_cnt + 1, self_cnt, &parent_flags, - f_vrfy, p_vrfy ); - if( ret != 0 ) - return( ret ); + if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 && + x509_crt_check_cn( &name->val, cn, cn_len ) == 0 ) + { + break; + } } + + if( name == NULL ) + *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } +} - /* child is verified to be a child of the parent, call verify callback */ - if( NULL != f_vrfy ) - if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) - return( ret ); +/* + * Merge the flags for all certs in the chain, after calling callback + */ +static int x509_crt_merge_flags_with_cb( + uint32_t *flags, + x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE], + size_t chain_len, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ) +{ + int ret; + size_t i; + uint32_t cur_flags; + + for( i = chain_len; i != 0; --i ) + { + cur_flags = ver_chain[i-1].flags; + + if( NULL != f_vrfy ) + if( ( ret = f_vrfy( p_vrfy, ver_chain[i-1].crt, (int) i-1, &cur_flags ) ) != 0 ) + return( ret ); - *flags |= parent_flags; + *flags |= cur_flags; + } return( 0 ); } @@ -2218,9 +2338,15 @@ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, &mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) ); } - /* * Verify the certificate validity, with profile + * + * This function: + * - checks the requested CN (if any) + * - checks the type and size of the EE cert's key, + * as that isn't done as part of chain building/verification currently + * - builds and verifies the chain + * - then calls the callback and merges the flags */ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, @@ -2230,15 +2356,15 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { - size_t cn_len; int ret; - int pathlen = 0, selfsigned = 0; - mbedtls_x509_crt *parent; - mbedtls_x509_name *name; - mbedtls_x509_sequence *cur = NULL; mbedtls_pk_type_t pk_type; + x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE]; + size_t chain_len; + uint32_t *ee_flags = &ver_chain[0].flags; *flags = 0; + memset( ver_chain, 0, sizeof( ver_chain ) ); + chain_len = 0; if( profile == NULL ) { @@ -2246,104 +2372,28 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, goto exit; } + /* check name if requested */ if( cn != NULL ) - { - name = &crt->subject; - cn_len = strlen( cn ); - - if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) - { - cur = &crt->subject_alt_names; - - while( cur != NULL ) - { - if( cur->buf.len == cn_len && - x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 ) - break; - - if( cur->buf.len > 2 && - memcmp( cur->buf.p, "*.", 2 ) == 0 && - x509_check_wildcard( cn, &cur->buf ) == 0 ) - { - break; - } - - cur = cur->next; - } - - if( cur == NULL ) - *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; - } - else - { - while( name != NULL ) - { - if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 ) - { - if( name->val.len == cn_len && - x509_memcasecmp( name->val.p, cn, cn_len ) == 0 ) - break; - - if( name->val.len > 2 && - memcmp( name->val.p, "*.", 2 ) == 0 && - x509_check_wildcard( cn, &name->val ) == 0 ) - break; - } - - name = name->next; - } - - if( name == NULL ) - *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; - } - } + x509_crt_verify_name( crt, cn, ee_flags ); /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_PK; + *ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK; - if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 ) - *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; + if( x509_profile_check_key( profile, &crt->pk ) != 0 ) + *ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY; - /* Look for a parent in trusted CAs */ - for( parent = trust_ca; parent != NULL; parent = parent->next ) - { - if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) - break; - } - - if( parent != NULL ) - { - ret = x509_crt_verify_top( crt, parent, ca_crl, profile, - pathlen, selfsigned, flags, f_vrfy, p_vrfy ); - if( ret != 0 ) - goto exit; - } - else - { - /* Look for a parent upwards the chain */ - for( parent = crt->next; parent != NULL; parent = parent->next ) - if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) - break; + /* Check the chain */ + ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile, + ver_chain, &chain_len ); + if( ret != 0 ) + goto exit; - /* Are we part of the chain or at the top? */ - if( parent != NULL ) - { - ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile, - pathlen, selfsigned, flags, f_vrfy, p_vrfy ); - if( ret != 0 ) - goto exit; - } - else - { - ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile, - pathlen, selfsigned, flags, f_vrfy, p_vrfy ); - if( ret != 0 ) - goto exit; - } - } + /* Build final flags, calling callback on the way if any */ + ret = x509_crt_merge_flags_with_cb( flags, + ver_chain, chain_len, f_vrfy, p_vrfy ); exit: /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by @@ -2400,7 +2450,7 @@ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) { name_prv = name_cur; name_cur = name_cur->next; - mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); + mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } @@ -2409,7 +2459,7 @@ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) { name_prv = name_cur; name_cur = name_cur->next; - mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); + mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } @@ -2418,7 +2468,8 @@ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) { seq_prv = seq_cur; seq_cur = seq_cur->next; - mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); + mbedtls_platform_zeroize( seq_prv, + sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } @@ -2427,13 +2478,14 @@ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) { seq_prv = seq_cur; seq_cur = seq_cur->next; - mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); + mbedtls_platform_zeroize( seq_prv, + sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } if( cert_cur->raw.p != NULL ) { - mbedtls_zeroize( cert_cur->raw.p, cert_cur->raw.len ); + mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len ); mbedtls_free( cert_cur->raw.p ); } @@ -2447,7 +2499,7 @@ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) cert_prv = cert_cur; cert_cur = cert_cur->next; - mbedtls_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) ); + mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) ); if( cert_prv != crt ) mbedtls_free( cert_prv ); } diff --git a/thirdparty/mbedtls/library/x509_csr.c b/thirdparty/mbedtls/library/x509_csr.c index 26a06db4f6..3e8e8fbc6a 100644 --- a/thirdparty/mbedtls/library/x509_csr.c +++ b/thirdparty/mbedtls/library/x509_csr.c @@ -39,6 +39,7 @@ #include "mbedtls/x509_csr.h" #include "mbedtls/oid.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -60,11 +61,6 @@ #include <stdio.h> #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * Version ::= INTEGER { v1(0) } */ @@ -325,7 +321,7 @@ int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path ) ret = mbedtls_x509_csr_parse( csr, buf, n ); - mbedtls_zeroize( buf, n ); + mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); @@ -407,17 +403,17 @@ void mbedtls_x509_csr_free( mbedtls_x509_csr *csr ) { name_prv = name_cur; name_cur = name_cur->next; - mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); + mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } if( csr->raw.p != NULL ) { - mbedtls_zeroize( csr->raw.p, csr->raw.len ); + mbedtls_platform_zeroize( csr->raw.p, csr->raw.len ); mbedtls_free( csr->raw.p ); } - mbedtls_zeroize( csr, sizeof( mbedtls_x509_csr ) ); + mbedtls_platform_zeroize( csr, sizeof( mbedtls_x509_csr ) ); } #endif /* MBEDTLS_X509_CSR_PARSE_C */ diff --git a/thirdparty/mbedtls/library/x509write_crt.c b/thirdparty/mbedtls/library/x509write_crt.c index 41dfe87b75..b1ef216c95 100644 --- a/thirdparty/mbedtls/library/x509write_crt.c +++ b/thirdparty/mbedtls/library/x509write_crt.c @@ -37,6 +37,7 @@ #include "mbedtls/oid.h" #include "mbedtls/asn1write.h" #include "mbedtls/sha1.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -44,11 +45,6 @@ #include "mbedtls/pem.h" #endif /* MBEDTLS_PEM_WRITE_C */ -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx ) { memset( ctx, 0, sizeof( mbedtls_x509write_cert ) ); @@ -65,7 +61,7 @@ void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx ) mbedtls_asn1_free_named_data_list( &ctx->issuer ); mbedtls_asn1_free_named_data_list( &ctx->extensions ); - mbedtls_zeroize( ctx, sizeof( mbedtls_x509write_cert ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_cert ) ); } void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version ) diff --git a/thirdparty/mbedtls/library/x509write_csr.c b/thirdparty/mbedtls/library/x509write_csr.c index e80053828f..66cee56014 100644 --- a/thirdparty/mbedtls/library/x509write_csr.c +++ b/thirdparty/mbedtls/library/x509write_csr.c @@ -35,6 +35,7 @@ #include "mbedtls/x509_csr.h" #include "mbedtls/oid.h" #include "mbedtls/asn1write.h" +#include "mbedtls/platform_util.h" #include <string.h> #include <stdlib.h> @@ -43,11 +44,6 @@ #include "mbedtls/pem.h" #endif -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx ) { memset( ctx, 0, sizeof( mbedtls_x509write_csr ) ); @@ -58,7 +54,7 @@ void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx ) mbedtls_asn1_free_named_data_list( &ctx->subject ); mbedtls_asn1_free_named_data_list( &ctx->extensions ); - mbedtls_zeroize( ctx, sizeof( mbedtls_x509write_csr ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_csr ) ); } void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg ) diff --git a/thirdparty/mbedtls/library/xtea.c b/thirdparty/mbedtls/library/xtea.c index fe0a3509f6..a33707bc17 100644 --- a/thirdparty/mbedtls/library/xtea.c +++ b/thirdparty/mbedtls/library/xtea.c @@ -28,6 +28,7 @@ #if defined(MBEDTLS_XTEA_C) #include "mbedtls/xtea.h" +#include "mbedtls/platform_util.h" #include <string.h> @@ -42,11 +43,6 @@ #if !defined(MBEDTLS_XTEA_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - /* * 32-bit integer manipulation macros (big endian) */ @@ -80,7 +76,7 @@ void mbedtls_xtea_free( mbedtls_xtea_context *ctx ) if( ctx == NULL ) return; - mbedtls_zeroize( ctx, sizeof( mbedtls_xtea_context ) ); + mbedtls_platform_zeroize( ctx, sizeof( mbedtls_xtea_context ) ); } /* |