commit 735ca85a536d1bc0a92887d0b9eae608729eacd2 Author: Maurice O'Neal Date: Sat Sep 14 13:03:34 2019 -0400 Initial commit for the Cmdr project. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..15361cf --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# C++ objects and libs +*.slo +*.lo +*.o +*.a +*.la +*.lai +*.so +*.dll +*.dylib + +# Qt-es +object_script.*.Release +object_script.*.Debug +*_plugin_import.cpp +/.qmake.cache +/.qmake.stash +*.pro.user +*.pro.user.* +*.qbs.user +*.qbs.user.* +*.moc +moc_*.cpp +moc_*.h +qrc_*.cpp +ui_*.h +*.qmlc +*.jsc +Makefile* +*build-* + +# Qt unit tests +target_wrapper.* + +# QtCreator +*.autosave + +# QtCreator Qml +*.qmlproject.user +*.qmlproject.user.* + +# QtCreator CMake +CMakeLists.txt.user* + +# QtCreator 4.8< compilation database +compile_commands.json + +# QtCreator local machine specific files for imported projects +*creator.user* diff --git a/Cmdr.pro b/Cmdr.pro new file mode 100644 index 0000000..826f232 --- /dev/null +++ b/Cmdr.pro @@ -0,0 +1,69 @@ +# This file is part of Cmdr. +# +# Cmdr is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Cmdr is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Cmdr under the LICENSE.md file. If not, see +# . + +QT += core gui +QT += network + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TEMPLATE = app + +CONFIG -= console +CONFIG -= app_bundle + +# The following define makes your compiler emit warnings if you use +# any feature of Qt which as been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. + +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if you use deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +TARGET = cmdr + +LIBS += -lcrypto -lssl + +SOURCES += src/main.cpp \ + src/cmd_line.cpp \ + src/common.cpp \ + src/main_ui.cpp \ + src/session.cpp \ + src/gen_file.cpp \ + src/text_body.cpp \ + src/cmd_objs/command.cpp \ + src/cmd_objs/info.cpp \ + src/cmd_objs/exec.cpp \ + src/cmd_objs/bookmarks.cpp \ + src/cmd_objs/status.cpp \ + src/cmd_objs/style.cpp + +HEADERS += src/session.h \ + src/cmd_line.h \ + src/common.h \ + src/gen_file.h \ + src/main_ui.h \ + src/text_body.h \ + src/cmd_objs/command.h \ + src/cmd_objs/info.h \ + src/cmd_objs/exec.h \ + src/cmd_objs/bookmarks.h \ + src/cmd_objs/long_txt.h \ + src/cmd_objs/status.h \ + src/cmd_objs/style.h diff --git a/docs/Async.md b/docs/Async.md new file mode 100644 index 0000000..e9decbc --- /dev/null +++ b/docs/Async.md @@ -0,0 +1,184 @@ +### Async Commands ### + +An async command is a virtual command that the host can use to send data to the client at any time while connected to the host. As the name implies, the occurance of a client receiving data from an async command is not always the result of running a regular command in the current session. This can occur for example when information in your account is changed by another client connected to the host; your client would not know about this change until an async command is sent notify it of the change. These commands cannot be called directly by a client or even a module command object. + +Async commands are not only used send data to the client but also used internally within the host to help session objects operating in different processes to communicate with each other. Some async commands in fact are considered internal only because the client should never see any data come from them at anytime. + +These are considered "virtual" commands because there is no defined command objects attached to them. Instead, async commands are best identified by command id values 1-255. Here is a list of currently "defined" async commands: + +``` +#define ASYNC_RDY 1 +#define ASYNC_SYS_MSG 2 +#define ASYNC_EXE_CRASH 3 +#define ASYNC_EXIT 4 // internal only +#define ASYNC_CAST 5 // internal only +#define ASYNC_MAXSES 6 // internal only +#define ASYNC_LOGOUT 7 // internal only +#define ASYNC_USER_DELETED 8 +#define ASYNC_GROUP_RENAMED 9 // internal only +#define ASYNC_DISP_RENAMED 10 // internal only +#define ASYNC_GRP_TRANS 11 // internal only +#define ASYNC_USER_GROUP_CHANGED 12 // internal only +#define ASYNC_CMD_RANKS_CHANGED 13 // internal only +#define ASYNC_RESTART 14 // internal only +#define ASYNC_ENABLE_MOD 15 // internal only +#define ASYNC_DISABLE_MOD 16 // internal only +#define ASYNC_GROUP_UPDATED 17 // internal only +#define ASYNC_END_SESSION 18 // internal only +#define ASYNC_USER_LOGIN 19 // internal only +#define ASYNC_RESTORE_AUTH 20 // internal only +#define ASYNC_TO_PEER 21 +#define ASYNC_LIMITED_CAST 22 +#define ASYNC_RW_MY_INFO 23 // internal only +#define ASYNC_P2P 24 +#define ASYNC_CLOSE_P2P 25 // internal only +#define ASYNC_NEW_CH_MEMBER 26 +#define ASYNC_DEL_CH 27 +#define ASYNC_RENAME_CH 28 +#define ASYNC_CH_ACT_FLAG 29 +#define ASYNC_NEW_SUB_CH 30 +#define ASYNC_RM_SUB_CH 31 +#define ASYNC_RENAME_SUB_CH 32 +#define ASYNC_INVITED_TO_CH 33 +#define ASYNC_RM_CH_MEMBER 34 +#define ASYNC_INVITE_ACCEPTED 35 +#define ASYNC_MEM_LEVEL_CHANGED 36 +#define ASYNC_SUB_CH_LEVEL_CHG 37 +#define ASYNC_ADD_RDONLY 38 +#define ASYNC_RM_RDONLY 39 +#define ASYNC_ADD_CMD 40 +#define ASYNC_RM_CMD 41 +#define ASYNC_USER_RENAMED 42 +#define ASYNC_PUBLIC_AUTH 43 // internal only +``` + +### Async Data ### + +```ASYNC_RDY (1)``` +This command signals to the client that your current session is now ready to start running commands. This is usually sent after successfully setting up the tcp connection or after successfully recovering from a session crash. It can carry ```TEXT``` data that can be displayed directly to the user if needed. + +```ASYNC_SYS_MSG (2)``` +This command carry ```TEXT``` or ```ERR``` data that are system messages that can be directly displayed to the user of needed. It is also used to carry ```HOST_CERT``` data during the tcp connection setup and ```MY_INFO``` when local user account information has changed. + +```ASYNC_EXE_CRASH (3)``` +This is used to send ```ERR``` messages to the client if your session crashes or fails to setup a command executor at the host side for any reason. + +```ASYNC_EXIT (4)``` +This is an internal async command that doesn't carry any data. This will cause the host to stop listing for clients, close all sessions and then close the main process. + +```ASYNC_CAST (5)``` +This is an internal only command that carries a 54byte open sub-channels list and an embedded mrci frame that can then be sent to clients that have any of the matching open sub-channels. It drops that sub-channel list before arriving at the client so it will apppear like a regular mrci frame of any data type. + +```ASYNC_MAXSES (6)``` +Internal only async command that is used by internal commands to send a ```BYTES``` frame to the main process to update the maximum amount the concurrent sessions for the host. The data itself is actually a 32bit unsigned int. + +```ASYNC_LOGOUT (7)``` +This internal only async command doesn't carry any data. This is just used to notify the main process that the user has logged out and should not attempt to restore authentication in case of a session crash. This doesn't actually do the logout. + +```ASYNC_USER_DELETED (8)``` +This async command carry ```TEXT``` data that is the user name of the user account that was deleted from the host database. All sessions that get this command must read and match this to the user name that is currently logged in. If the user name matches, the session must logout and forward this to the client since the user account no longer exists. + +```ASYNC_GROUP_RENAMED (9)``` +Internal only async command that carry ```TEXT``` command line arguments to notify all sessions that the a host group name has changed. Example: ```-src "old_group_name" -dst "new_group_name"```. All sessions that have matching current group names to ```old_group_name``` must update that group name to ```new_group_name``` and also send a ```ASYNC_SYS_MSG``` to the client containing an updated ```MY_INFO```. + +```ASYNC_DISP_RENAMED (10)``` +Internal only async command that carry ```TEXT``` command line arguments to notify all sessions that a user has changed the display name. Example: ```-name "new_display_name" -user "user_name"```. All sessions that have matching current user names to ```user_name``` must update the display name to ```new_display_name``` and also send a ```ASYNC_SYS_MSG``` to the client containing an updated ```MY_INFO```. + +```ASYNC_GRP_TRANS (11)``` +Internal only async command that carry the same ```TEXT``` command line arguments as ```ASYNC_GROUP_RENAMED``` to notify all sessions that the all users currently in the group given in ```-src``` must be updated to the group given in ```-dst```. This triggers a ```ASYNC_SYS_MSG``` to send an updated ```MY_INFO``` and the session will load all the commands that the user now have access to and remove any commands that lost access due to the group change. + +```ASYNC_USER_GROUP_CHANGED (12)``` +This is an internal only async command that carry ```TEXT``` command line arguments to notify all sessions that a user's group was changed to another group. example: ```-user "user_name" -group "new_group"```. All sessions the have the matching user name need to update it's group to ```new_group```, send a ```ASYNC_SYS_MSG``` with an updated ```MY_INFO``` and load all the commands that the user now have access to and remove any commands that lost access due to the group change. + +```ASYNC_CMD_RANKS_CHANGED (13)``` +This internal only async commmand doesn't carry any data. Instead, it notifies all sessions that the assigned command ranks have changed. This will cause all sessions to re-check the currently loaded commands and determine if it needs to remove any commands that the user no longer have access to and add any commands that the user may have gained access to. + +```ASYNC_RESTART (14)``` +This internal only async commmand doesn't carry any data. This will cause the host to stop listing for clients, close all sessions, reload the host settings and start listening for clients again. + +```ASYNC_ENABLE_MOD (15)``` +This internal only async commmand carry ```TEXT``` of a module name. All sessions that receive this will then load the requested module. + +```ASYNC_DISABLE_MOD (16)``` +This internal only async commmand carry ```TEXT``` of a module name. All sessions that receive this will delete all commands associated with this module and then unload it. + +```ASYNC_GROUP_UPDATED (17)``` +This is an internal only command that carry ```TEXT``` command line arguments to notify all sessions that a group's host rank has changed. Example: ```-name "group_name" -rank 2```. All sessions that have matching group names to ```group_name``` will need to update the host rank to ```2```. When the session's host rank is adjusted this way, the session will need to re-check the currently loaded commands and determine if it needs to remove any commands that the user no longer have access to and add any commands that the user may have gained access to. + +```ASYNC_END_SESSION (18)``` +This internal only async commmand doesn't carry any data. It will signal the session to close at the host side. + +```ASYNC_USER_LOGIN (19)``` +This is an internal only command that carry ```PRIV_IPC``` data containing the 256bit Keccak hash user id of the user that has successfully logged in. This is used by the command executor to notify the main process of the current user associated with the current session. The main process will use this information to restore the user authorization in case of a session crash. + +```ASYNC_RESTORE_AUTH (20)``` +This is an internal only command that carry ```PRIV_IPC``` data containing the 256bit Keccak hash user id of a user that has successfully logged in with the current session. It is used by the main process to tell the command executor in the slave process to authorize the user without a password. This is only used when attempting to restore the session from a crash and a user was logged in at the time. + +```ASYNC_TO_PEER (21)``` +This is an async command that carry an embedded mrci frame directly to/from peer sessions without any restrictions. It is prepended with the 224bit sha3 hash of the target session id; however, it drops that session id before arriving at the client so it will apppear as a regular mrci frame of any data type. Users should not be given direct access to this for security reasons. + +```ASYNC_LIMITED_CAST (22)``` +This operate exactly like ```ASYNC_CAST``` except only sessions with active update sub-channels will respond to it. + +```ASYNC_RW_MY_INFO (23)``` +This internal only async command carry ```TEXT``` data of the user name to tell all sessions that have the matching user name to send an update ```MY_INFO``` to the client. This is useful for when a host admin force updates user information of other lesser privileged users to make their clients aware of the changes. + +```ASYNC_P2P (24)``` +This async command carry an embedded mrci frame directly to/from peer sessions following the p2p negotiation process as described in [Type_IDs](Type_IDs.md), at the P2P specific data types. It prepends the 224bit sha3 hash of the destination session id and source session id; however, it drops the destination id and source id for just the P2P specific data types before arriving at the client. For all other data types (if a p2p connection is estabished), the source id is prepend-moved to the payload of the mrci frame before arriving at the client. + +```ASYNC_CLOSE_P2P (25)``` +This internal only async command carry a 224bit sha3 hash session id of a session that is about to close. This notifies all sessions that have matching hashes in p2p accepted and p2p pending list to remove them now. It also triggers a ```ASYNC_P2P``` to send a ```P2P_CLOSE``` for the session id in question so the clients can also be made aware of this. + +```ASYNC_NEW_CH_MEMBER (26)``` +```TEXT``` command line arguments when a new channel is created and the user that created it is added as the channel owner. Example: ```-user "user_name" -ch_name "new_channel" -ch_id 334 -level 1```. + +```ASYNC_DEL_CH (27)``` +```TEXT``` command line arguments when a channel is deleted. Example: ```-ch_name "channel_name" -ch_id 426```. The host will automatically close all sub-channels related to this channel for all sessions that have them open. + +```ASYNC_RENAME_CH (28)``` +```TEXT``` command line arguments when a channel is renamed. Example: ```-ch_name "old_name" -new_name "new_name"```. + +```ASYNC_CH_ACT_FLAG (29)``` +```TEXT``` command line arguments when sub-channel's active update flag has been updated. Example: ```-ch_name "channel_name" -sub_name "sub_channel" -state 1```. (```-state``` 1 is true or ```-state``` 0 is false). + +```ASYNC_NEW_SUB_CH (30)``` +```TEXT``` command line arguments when a new sub-channel is created. Example: ```-ch_name "channel_name" -sub_name "new_sub_channel" -ch_id 987 -sub_id 5 -level 2```. + +```ASYNC_RM_SUB_CH (31)``` +```TEXT``` command line arguments when a sub-channel is deleted. Example: ```-ch_name "channel_name" -sub_name "sub_channel" -ch_id 987 -sub_id 5```. The host will automatically close this sub-channel for sessions that currently have it open. + +```ASYNC_RENAME_SUB_CH (32)``` +```TEXT``` command line arguments when a sub-channel is renamed. Example: ```-ch_name "channel_name" -sub_name "sub_channel" -new_name "new_sub_name"```. + +```ASYNC_INVITED_TO_CH (33)``` +```TEXT``` command line arguments when a new user is invited to join a channel. Example: ```-ch_name "channel_name" -user "user_name"```. + +```ASYNC_RM_CH_MEMBER (34)``` +```TEXT``` command line arguments when a user is kicked from a channel, uninvited or has left the channel. Example: ```-ch_name "channel_name" -user "user_name" -ch_id 746```. + +```ASYNC_INVITE_ACCEPTED (35)``` +```TEXT``` command line arguments when a user that was previously invite to join the channel has accepted the invite and should now be considered full member of the channel starting off at level ```REGULAR```. Example: ```-ch_name "channel_name" -user "user_name"```. + +```ASYNC_MEM_LEVEL_CHANGED (36)``` +```TEXT``` command line arguments when a channel member's privilege level is changed. Example: ```-ch_name "channel_name" -user "user_name" -ch_id 774 -level 2```. The host automatically closes all sub-channels related to the channel for the affected user. It will be will up to the client to re-open the sub-channel(s) if the user still have access to it/them. + +```ASYNC_SUB_CH_LEVEL_CHG (37)``` +```TEXT``` command line arguments when a sub-channel's lowest level of access is changed. Example: ```-ch_name "channel_name" -sub_name "sub_channel" -level 3 -ch_id 645 -sub_id 5```. The host will automatically close this sub-channel for sessions that currently have it open. It will be up to the client to reopen it if the current user still have access to it. + +```ASYNC_ADD_RDONLY (38)``` +```TEXT``` command line arguments when a read only flag is added to a sub-channel's access level. Example: ```-ch_name "channel_name" -sub_id 5 -level 4```. The host will automatically close this sub-channel for sessions that currently have it open. It will be up to the client to reopen it if the current user still have access to it. + +```ASYNC_RM_RDONLY (39)``` +```TEXT``` command line arguments when a read only flag is removed from a sub-channel's access level. Example: ```-ch_name "channel_name" -sub_id 5 -level 4```. The host will automatically close this sub-channel for sessions that currently have it open. It will be up to the client to reopen it if the current user still have access to it. + +```ASYNC_ADD_CMD (40)``` +This async command carry ```NEW_CMD``` when the session's command executor loads a new command object and wants to notify the client of it. + +```ASYNC_RM_CMD (41)``` +This async command carry ```CMD_ID``` when the session's command executor deletes a command object and wants to notify the client of it. + +```ASYNC_USER_RENAMED (42)``` +```TEXT``` command line arguments when a user changes it's user name. Example: ```-old "old_user_name" -new_name "new_user_name"```. + +```ASYNC_PUBLIC_AUTH (43)``` +This internal only async commmand doesn't carry any data. It just tells the command executor to load or reload commands without an authorized user so only public commands will be available until the client authorizes into a user account. This is used by the host when starting a session for the first time or if restoring the session after a crash and no user was logged in at the time. \ No newline at end of file diff --git a/docs/LICENSE.md b/docs/LICENSE.md new file mode 100644 index 0000000..f718b3e --- /dev/null +++ b/docs/LICENSE.md @@ -0,0 +1,621 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..ccd9ddb --- /dev/null +++ b/docs/README.md @@ -0,0 +1,121 @@ +# Cmdr # + +Cmdr is a command line terminal emulator client for MRCI host using text input/output. This helps administer MRCI host via local or remote TCP connections encrypted with TLS/SSL using the MRCI protocol. It also supports file transfers to/from the client using the GEN_FILE sub-protocol that MRCI understands. + +### Usage ### + +Cmdr has it's own user interface and terminal display so there is no command line switches to pass on start up. Instead, all commands are parsed and processed within it's own terminal interface. Any commands not seen as an internal command for the client itself is passed through to the MRCI host if connected. Users have the option to start the command line with a '#' to bypass any of the client's internal commands in cases when there is overlap with a host command. + +### Versioning System ### + +This application uses the typical 3 number versioning system: [major].[minor].[patch] + +* Major - this indicates any major changes to the code of the application that renders versions of different majors incompatible with each other. +* Minor - this indicates only minor changes to the code that may require a few conditional blocks to maintain compatibility. +* Patch - this indicates changes that won't require any behaviour changes at all to maintain compatibility. + +Any increments to major resets minor and patch to 0. The MRCI host/protocol also uses the 3 number version system seperate from this client's own version number. + +### The Protocol ### + +This application being a MRCI client uses the MRCI protocol to transport data to and from the host using TCP in a binary data format called MRCI frames. In general, local connections with the host are not encrypted but all connects outside of the host must be encrypted using TLS/SSL. + +Before any MRCI frames can be transported, the host need to be made aware of the version of the host that this application supports and this application also needs to be made aware of the host current version. This is done by sending a fixed length header containing information about this application to the host when it successfully connects. the host will then reply with it's own fixed length host header. + +### MRCI Frame Format ### + +``` +Format: + +[type_id][cmd_id][data_len][payload] + +type_id - 1byte - 8bit little endian integer type id of the payload. +cmd_id - 2bytes - 16bit little endian integer command object id. +data_len - 3bytes - 24bit little endian integer size of the payload. +payload - variable - the actual data to be processed. +``` + +A full description of the type id's can be found in the [Type_IDs.md](Type_IDs.md) document. + +### Client Header (This Application) ### + +``` +Format: + +[tag][major][minor][patch][appName][coName] + +tag - 4bytes - 0x4D, 0x52, 0x43, 0x49 (MRCI) +major - 2bytes - 16bit little endian unsigned int +minor - 2bytes - 16bit little endian unsigned int +patch - 2bytes - 16bit little endian unsigned int +appName - 128bytes - UTF16LE string (padded with spaces) +coName - 272bytes - UTF16LE string (padded with spaces) +``` + +notes: + +* The **tag** is just a fixed ascii string "MRCI" that indicates to the host that the client is indeed attempting to use the MRCI protocol. + +* **major**, **minor**, **patch** is the version number of the MRCI protocol that the client understands. Do not send the client's own version number. + +* The **appName** is the name of the client application that is connected to the host. It can also contain the client's app version if needed because it doesn't follow any particular standard. + +* The **coName** is the common name of a SSL certificate that is currently installed in the host. Depending on how the host is configured, it can contain more than one installed SSL cert so coName can be used by clients as a way to request which one of the certs to use during the SSL handshake. + +### Host Header ### + +``` +Format: + +[reply][major][minor][patch][sesId] + +reply - 1byte - 8bit little endian unsigned int +major - 2bytes - 16bit little endian unsigned int +minor - 2bytes - 16bit little endian unsigned int +patch - 2bytes - 16bit little endian unsigned int +sesId - 28bytes - 224bit sha3 hash +``` + +notes: + +* **reply** is a numeric value that the host returns in it's header to communicate to the client the result of it's evaluation of the client's header. + + * reply = 1, means the client version is acceptable and it does not need to take any further action. + * reply = 2, means the client version is acceptable but the host will now send it's Pem formatted SSL cert data in a ```HOST_CERT``` mrci frame just after sending it's header. After receiving the cert, the client will then need to send a STARTTLS signal using this cert. + * reply = 3, means the client version is not supported by the host and the session will end shortly. + * reply = 4, means the host was unable to load the SSL cert associated with the common name sent by the client. The session will auto close at this point. + +* **sesId** is the session id. It is a unique 224bit sha3 hash generated against the current date of session creation (down to the msec) and the machine id. This can be used to uniquely identify the current session and past sessions. + +### ASync Commands ### + +Async commands are host only 'virtual commands' that this application can encounter at any time while connected to the host. More information about this can be found in the [Async.md](Async.md) document. This application does act on some of the data carried by the async commands but not all of them. + +### Development Setup ### + +Linux Required Packages: +``` +qtbase5-dev +libssl-dev +gcc +make +makeself +``` + +### Build From Source (Linux) ### + +Linux_build.sh is a custom script designed to build this project from the source code using qmake, make and makeself. You can pass 2 optional arguments: + +1. The path to the QT bin folder in case you want to compile with a QT install not defined in PATH. +2. Path of the output makeself file (usually has a .run extension). If not given, the outfile will be named cmdr-1.0.0.run in the source code folder. + +Build: +``` +cd /path/to/source/code +sh ./linux_build.sh +``` +Install: +``` +chmod +x ./cmdr-1.0.0.run +./cmdr-1.0.0.run +``` diff --git a/docs/Type_IDs.md b/docs/Type_IDs.md new file mode 100644 index 0000000..850319c --- /dev/null +++ b/docs/Type_IDs.md @@ -0,0 +1,219 @@ +### Type IDs ### + +``` +enum TypeID +{ + GEN_FILE = 30, + TEXT = 31, + ERR = 32, + PRIV_TEXT = 33, + IDLE = 34, + HOST_CERT = 35, + FILE_INFO = 36, + PEER_INFO = 37, + MY_INFO = 38, + PEER_STAT = 39, + P2P_REQUEST = 40, + P2P_CLOSE = 41, + P2P_OPEN = 42, + BYTES = 43, + SESSION_ID = 44, + NEW_CMD = 45, + CMD_ID = 46, + BIG_TEXT = 47 +}; +``` + +### Type Descriptions ### + +```TEXT``` +This is text that can be displayed directly to the user or pass arguments for command objects to process. + +format: ```[UTF-16LE_string] (no BOM)``` + +```GEN_FILE``` +This is a file transfer type id that can be used to transfer any type of file type (music, photos, documents, etc...). It operates in its own protocol of sorts. The 1st GEN_FILE frame received by the host or client is TEXT parameters similar to what you see in terminal command lines with at least one of the arguments listed below. The next set of GEN_FILE frames received by the host or client is then the binary data that needs to be written to an open file or streamed until the limit defined in **-len** is meet. + +The host or the client can be set as the sender or receiver of the GEN_FILE binary data. Which ever is designated as the receiver by the TEXT parameters need to send an empty GEN_FILE frame to start the process. An example if this can be found at the buttom of this document. + +arguments: + +* **-len (int)** | this is the integer value of the file size or amount of bytes to read/write. + +* **-offset (int)** | this integer position tells where in the source or destination file to start reading/writing. + +* **-client_file** (string) | this is the file path to the source/destination file in the client's file system. + +* **-remote_file** (string) | this is the file path to the source/destination file in the host file system. + +* **-single_step** | the presents of this argument tells both the client and host to operate in single step mode. single step mode causes the receiver of the binary data whether host or client to send an empty GEN_FILE frame after successfully receiving the data. this then tells the sender to send the next GEN_FILE frame containing binary data for the file and the cycle continues until len is meet. if this argument is not found, the sender can simply send all GEN_FILE data without waiting for an empty GEN_FILE from the receiver. + +* **-to_host** | this argument should only come from host and it will define the client as the sender and the host as the receiver. + +* **-from_host** | opposite affect to *-to_host*. it defines the host as the sender and the client as the receiver. + +* **-truncate** | this indicates to whoever is the receiver to truncate the file being written to. + +* **-force** | in some cases, the receiver might need to overwrite the target file. the presents of this argument tells it to overwrite without asking the user. the host should never send this argument and the client should ignore it if it is received from the host. + +```ERR``` +This type id is similar to TEXT except it indicates that this is an error message that can be displayed directly to the user if needed. + +```PRIV_TEXT``` +This id can be treated exactly like TEXT except this should tell the client to hide or do not echo the next TEXT data that the host is expecting, like a password or other sensitive text data. + +```BIG_TEXT``` +Also formatted exactly like TEXT but this indicates to the client that this is a large body of text that is recommended to be word wrapped when displaying to the user. It can contain line breaks so clients are also recommended to honor those line breaks. + +```IDLE``` +This doesn't carry any actual data, instead this indicates that the command id that sent it has finished it's task. + +```HOST_CERT``` +Just as the name implies, this data type is used by the host to send the host SSL certificate while setting up an SSL connection. + +```FILE_INFO``` +This is a data structure that carries information about a file system object (file,dir,link). + +``` + format: + 1. bytes[0] - flags (8bit little endian uint) + 2. bytes[1-8] - creation time in msec since Epoch UTC (64bit little endian uint) + 3. bytes[9-16] - modification time in msec since Epoch UTC (64bit little endian uint) + 4. bytes[17-24] - file size (64bit little endian uint) + 5. bytes[25-variable] - file name (UTF16-LE string, 16bit terminated) + 6. bytes[variable] - symmlink target if it is a symmlink (UTF16-LE string, 16bit terminated) + + notes: + 1. 16bit terminated UTF-16LE strings are basically + terminated by 2 bytes of 0x00. + 2. the symmlink target is empty if not a symmlink but + the terminator should still be present. + + flags: + 1. bit 0 - true if the object is a file + 2. bit 1 - true if the object is a directory + 3. bit 2 - true if the object is a symmlink + 4. bit 3 - true if the current user have read permissions + 5. bit 4 - true if the current user have write permissions + 6. bit 5 - true if the current user have execute permissions + 7. bit 6 - true if the object exist in the file system. if symmlink, + this determines if the symm target exists or not. +``` + +```PEER_INFO``` +This carry some user account and session information about a peer client connected to the host. + +``` + format: + 1. bytes[0-27] 28bytes - session id (224bit hash) + 2. bytes[28-59] 32bytes - user id (256bit hash) + 3. bytes[60-107] 48bytes - user name (TEXT - padded with empty spaces) + 4. bytes[108-235] 128bytes - app name (TEXT - padded with empty spaces) + 5. bytes[236-299] 64bytes - disp name (TEXT - padded with empty spaces) + + notes: + 1. the session id is unique to the peer's session connection only. it + can change upon reconnection. + 2. the user id is unique to the peer's user account. is stays constant + even when the user name changes and across all clients logged into + the same account. + 3. the display name is the preffered display name of the peer. clients + are encouraged to use this rather than the user name when displaying + peer info to the user. if empty, it's ok to just fall back to the user + name. +``` + +```MY_INFO``` +This contains all of the information found in ```PEER_INFO``` for the local session but also includes the following: + +``` + format: + 1. bytes[300-427] 128bytes - email (TEXT - padded with empty spaces) + 2. bytes[428-451] 24bytes - group name (TEXT - padded with empty spaces) + 3. bytes[452] 1byte - is email confirmed? (0x00 false, 0x01 true) +``` + +```NEW_CMD``` +This contains information about a new command that was added to the current session. + +``` + format: + 1. bytes[0-1] 2bytes - 16bit LE unsigned int (command id) + 2. bytes[2] 1byte - bool (0x01 or 0x00) (handles gen file) + 3. bytes[3-130] 128bytes - command name (TEXT - padded with empty spaces) + 4. bytes[131-258] 128bytes - library name (TEXT - padded with empty spaces) + + notes: + 1. the handles gen file flag is a single byte 0x01 to indicate true and + 0x00 to indicate false. clients need to be aware of which command + handles the GEN_FILE mini protocol because it requires user input at + both ends (host and client). + 2. the library name is the lirbary that the new command belongs to. this + can be used by any client that may expect or depend on certain commands + that do certain task. +``` + +```CMD_ID``` +This type id carries a 16bit unsigned LE int representing a command id. + +format: ```2bytes - 16bit LE unsigned int (command id)``` + +```PEER_STAT``` +This contain status information of a peer client when the peer changes sub-channels or disconnects from the host. + +``` + format: + 1. bytes[0-27] 28bytes - session id (224bit hash) + 2. bytes[28-81] 54bytes - channel-sub ids + 3. bytes[82] 1byte - is disconnected? (0x00 false, 0x01 true) + + notes: + 1. if (is disconnected) is set true (0x01) the session id will no longer + be valid for that peer client so you should not make anymore attempts + to send data to it. + 2. channel-sub ids is a string of 9byte channel-sub id combinations at + a fixed length of 54bytes (padded with 0x00). this indicates what + channels-subs the peer currently have open if the peer's channel ids + no longer match with your session, it can be considered inactive or + disconnected since you will no longer send/receive data with this peer. +``` + +```SESSION_ID``` +This is a fixed length 28byte(224bit) sha3 hash of a client's session id connected to the host. This is unique to just the client's tcp connection with the host. This can change upon re-connection. + +format: ```28bytes - session id (224bit sha3 hash)``` + +```P2P_REQUEST``` +This is formatted extactly like ```PEER_INFO``` except this is allowed to be sent directly to the target peer without restriction using the **to_peer** host cmd. It will be up to the target peer to respond with a ```P2P_OPEN``` for the host to then unrestrict **to_peer** so it will then be able to send/received other TypeIDs with this peer until ```P2P_CLOSE``` is sent/received. ```P2P_CLOSE``` can also be sent to decline the request. + +```P2P_OPEN``` +This contains a 28byte session id hash of the peer session that you or the peer will allow direct communication with when using the **to_peer** host cmd. + +format: ```28bytes - session id (224bit sha3 hash)``` + +```P2P_CLOSE``` +This contains a 28byte session id hash of the peer session that you or the peer want to close direct communication with when using the **to_peer** host cmd. + +format: ```28bytes - session id (224bit sha3 hash)``` + +```BYTES``` +This contains arbitrary binary data of any format that is not specialized for any internal objects in the host. + +### GEN_FILE Example ### + +Setup: + +* The host has a command called *upload_file* with a command id of *768* and handles the ```GEN_FILE``` data type. +* The client has a file called */home/foo/bar.mp3* and wants to upload it to the host file */home/host/music/bar.mp3* and the client knows the file size is 512bytes. + +To upload the file, the client calls command id *768* with the following TEXT arguments (must still be sent as a GEN_FILE): +```-client_file "/home/foo/bar.mp3" -remote_file "/home/host/music/bar.mp3" -len 512``` + +The host will then return the following the text arguments to the client (also sent as a GEN_FILE): +```-to_host``` + +This argument from the host designates it as the receiver so it will be up to the host to send an empty ```GEN_FILE``` to indicate to the client that it was ready to start receiving binary data from the client to write to */home/host/music/bar.mp3*. If that file already exists, the host will need to ask the user to overwrite or not. + +If the host indicates that it's ready for the upload, the client can then simply read 512 bytes from */home/foo/bar.mp3* and send the read bytes to the host command id *768* as a ```GEN_FILE```. + +The host will then write the bytes received from the client to */home/host/music/bar.mp3* and then auto terminate the command since 512 bytes has been meet. \ No newline at end of file diff --git a/icons/128x128.png b/icons/128x128.png new file mode 100644 index 0000000..488bcd8 Binary files /dev/null and b/icons/128x128.png differ diff --git a/icons/16x16.png b/icons/16x16.png new file mode 100644 index 0000000..2dfdb7f Binary files /dev/null and b/icons/16x16.png differ diff --git a/icons/192x192.png b/icons/192x192.png new file mode 100644 index 0000000..8029ff2 Binary files /dev/null and b/icons/192x192.png differ diff --git a/icons/22x22.png b/icons/22x22.png new file mode 100644 index 0000000..dd70f7d Binary files /dev/null and b/icons/22x22.png differ diff --git a/icons/24x24.png b/icons/24x24.png new file mode 100644 index 0000000..61dce03 Binary files /dev/null and b/icons/24x24.png differ diff --git a/icons/256x256.png b/icons/256x256.png new file mode 100644 index 0000000..450efa2 Binary files /dev/null and b/icons/256x256.png differ diff --git a/icons/32x32.png b/icons/32x32.png new file mode 100644 index 0000000..10a8a64 Binary files /dev/null and b/icons/32x32.png differ diff --git a/icons/36x36.png b/icons/36x36.png new file mode 100644 index 0000000..38e9c57 Binary files /dev/null and b/icons/36x36.png differ diff --git a/icons/42x42.png b/icons/42x42.png new file mode 100644 index 0000000..2c07153 Binary files /dev/null and b/icons/42x42.png differ diff --git a/icons/48x48.png b/icons/48x48.png new file mode 100644 index 0000000..e10af4b Binary files /dev/null and b/icons/48x48.png differ diff --git a/icons/512x512.png b/icons/512x512.png new file mode 100644 index 0000000..55632b2 Binary files /dev/null and b/icons/512x512.png differ diff --git a/icons/64x64.png b/icons/64x64.png new file mode 100644 index 0000000..f8d7c74 Binary files /dev/null and b/icons/64x64.png differ diff --git a/icons/72x72.png b/icons/72x72.png new file mode 100644 index 0000000..44f64bf Binary files /dev/null and b/icons/72x72.png differ diff --git a/icons/8x8.png b/icons/8x8.png new file mode 100644 index 0000000..e744d3e Binary files /dev/null and b/icons/8x8.png differ diff --git a/icons/96x96.png b/icons/96x96.png new file mode 100644 index 0000000..b5bbd3e Binary files /dev/null and b/icons/96x96.png differ diff --git a/icons/scalable.svg b/icons/scalable.svg new file mode 100644 index 0000000..7eb5e27 --- /dev/null +++ b/icons/scalable.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/linux_build.sh b/linux_build.sh new file mode 100644 index 0000000..be226ac --- /dev/null +++ b/linux_build.sh @@ -0,0 +1,188 @@ +#!/bin/sh + +qt_dir="$1" +installer_file="$2" + +src_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +bin_name="cmdr" +app_version="1.0.0" +app_name="Cmdr" +install_dir="/opt/$bin_name" +bin_dir="/usr/bin" +tmp_dir="$HOME/.cache/cmdr_build" + +if [ "$qt_dir" != "" ]; then + + PATH=$qt_dir:$PATH + +fi + +if [ "$installer_file" = "" ]; then + + installer_file="$src_dir/$bin_name-$app_version.run" + +fi + +if [ -d "$tmp_dir" ]; then + + rm -rfv $tmp_dir + +fi + +mkdir -vp $tmp_dir +cp -rv $src_dir/. $tmp_dir + +if [ $? -eq 0 ]; then + + cd $tmp_dir + + qmake -config release + + if [ $? -eq 0 ]; then + + make + + if [ $? -eq 0 ]; then + + mkdir -v ./build + mkdir -v ./build/lib + cp -rfv ./icons ./build + ldd ./$bin_name | grep "libQt" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libicu" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libssl" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libcrypto" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + mv -v ./$bin_name ./build/$bin_name + + startup_script="./build/$bin_name.sh" + setup_script="./build/setup.sh" + uninstall_script="./build/uninstall.sh" + desktop_file="./build/$bin_name.desktop" + + echo "#!/bin/sh" > $startup_script + echo "export LD_LIBRARY_PATH=$install_dir/lib" >> $startup_script + echo "$install_dir/$bin_name \$1 \$2 \$3 \$4" >> $startup_script + + echo "[Desktop Entry]" > $desktop_file + echo "Type=Application" >> $desktop_file + echo "Exec=$bin_dir/$bin_name" >> $desktop_file + echo "Name=$app_name" >> $desktop_file + echo "GenericName=Terminal emulator for MRCI host." >> $desktop_file + echo "Icon=$bin_name" >> $desktop_file + echo "StartupWMClass=$bin_name" >> $desktop_file + echo "Terminal=false" >> $desktop_file + echo "Categories=Network;Terminal;MRCI;" >> $desktop_file + + echo "#!/bin/sh" > $setup_script + echo "if [ -f \"$install_dir/uninstall.sh\" ]; then" >> $setup_script + echo " sh $install_dir/uninstall.sh" >> $setup_script + echo "fi" >> $setup_script + echo "if [ ! -d \"$install_dir\" ]; then" >> $setup_script + echo " sudo mkdir -p $install_dir" >> $setup_script + echo "fi" >> $setup_script + echo "sudo cp -rv ./lib $install_dir" >> $setup_script + echo "sudo cp -v ./$bin_name $install_dir" >> $setup_script + echo "sudo cp -v ./$bin_name.sh $install_dir" >> $setup_script + echo "sudo cp -v ./uninstall.sh $install_dir" >> $setup_script + echo "sudo chmod 755 $install_dir/$bin_name" >> $setup_script + echo "sudo chmod 755 $install_dir/$bin_name.sh" >> $setup_script + echo "sudo chmod 755 $install_dir/uninstall.sh" >> $setup_script + echo "sudo chmod 755 $install_dir" >> $setup_script + echo "sudo chmod -R 755 $install_dir/lib" >> $setup_script + + echo "sudo mkdir -p /usr/share/icons/hicolor/8x8/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/16x16/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/22x22/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/24x24/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/32x32/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/36x36/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/42x42/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/48x48/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/64x64/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/72x72/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/96x96/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/128x128/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/192x192/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/256x256/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/512x512/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/icons/hicolor/scalable/apps" >> $setup_script + echo "sudo mkdir -p /usr/share/applications" >> $setup_script + + echo "sudo cp -v ./icons/8x8.png /usr/share/icons/hicolor/8x8/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/16x16.png /usr/share/icons/hicolor/16x16/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/22x22.png /usr/share/icons/hicolor/22x22/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/24x24.png /usr/share/icons/hicolor/24x24/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/32x32.png /usr/share/icons/hicolor/32x32/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/36x36.png /usr/share/icons/hicolor/36x36/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/42x42.png /usr/share/icons/hicolor/42x42/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/48x48.png /usr/share/icons/hicolor/48x48/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/64x64.png /usr/share/icons/hicolor/64x64/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/72x72.png /usr/share/icons/hicolor/72x72/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/96x96.png /usr/share/icons/hicolor/96x96/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/128x128.png /usr/share/icons/hicolor/128x128/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/192x192.png /usr/share/icons/hicolor/192x192/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/256x256.png /usr/share/icons/hicolor/256x256/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/512x512.png /usr/share/icons/hicolor/512x512/apps/$bin_name.png" >> $setup_script + echo "sudo cp -v ./icons/scalable.svg /usr/share/icons/hicolor/scalable/apps/$bin_name.svg" >> $setup_script + echo "sudo cp -v ./$bin_name.desktop /usr/share/applications/$bin_name.desktop" >> $setup_script + + echo "sudo chmod 644 /usr/share/icons/hicolor/8x8/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/16x16/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/22x22/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/24x24/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/32x32/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/36x36/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/42x42/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/48x48/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/64x64/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/72x72/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/96x96/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/128x128/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/192x192/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/256x256/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/512x512/apps/$bin_name.png" >> $setup_script + echo "sudo chmod 644 /usr/share/icons/hicolor/scalable/apps/$bin_name.svg" >> $setup_script + echo "sudo chmod 644 /usr/share/applications/$bin_name.desktop" >> $setup_script + + echo "sudo ln -sfv $install_dir/$bin_name.sh $bin_dir/$bin_name" >> $setup_script + echo "echo \"\nInstallation finished. If you ever need to uninstall this application, run this command:\n\"" >> $setup_script + echo "echo \" sh $install_dir/uninstall.sh\n\"" >> $setup_script + + echo "#!/bin/sh" > $uninstall_script + echo "sudo rm -v $bin_dir/$bin_name" >> $uninstall_script + echo "sudo rm -rv $install_dir" >> $uninstall_script + + echo "sudo rm -v /usr/share/icons/hicolor/8x8/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/16x16/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/22x22/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/24x24/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/32x32/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/36x36/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/42x42/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/48x48/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/64x64/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/72x72/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/96x96/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/128x128/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/192x192/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/256x256/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/512x512/apps/$bin_name.png" >> $uninstall_script + echo "sudo rm -v /usr/share/icons/hicolor/scalable/apps/$bin_name.svg" >> $uninstall_script + echo "sudo rm -v /usr/share/applications/$bin_name.desktop" >> $uninstall_script + + echo "echo Finished." >> $uninstall_script + + chmod +x $setup_script + + makeself ./build $installer_file "$app_name Installation" ./setup.sh + + fi + + fi + +fi + +if [ -d "$tmp_dir" ]; then + + rm -rf $tmp_dir + +fi \ No newline at end of file diff --git a/src/cmd_line.cpp b/src/cmd_line.cpp new file mode 100644 index 0000000..691e276 --- /dev/null +++ b/src/cmd_line.cpp @@ -0,0 +1,286 @@ +#include "cmd_line.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +CmdLine::CmdLine(QWidget *parent) : QComboBox(parent) +{ + localData = Shared::localData; + flags = 0; + + setEditable(true); + setDuplicatesEnabled(true); + loadTextSettings(localData, this); + + if (!localData->contains("command_hist")) + { + localData->insert("command_hist", QJsonArray()); + } + + if (!localData->contains("hist_limit")) + { + localData->insert("hist_limit", DEFAULT_HIST_LIMIT); + } + + saveLocalData(localData); + syncHistFromFile(); + + connect(lineEdit(), SIGNAL(selectionChanged()), this, SLOT(selectionCheck())); + connect(lineEdit(), SIGNAL(textEdited(QString)), this, SLOT(hideText(QString))); + connect(lineEdit(), SIGNAL(textEdited(QString)), this, SLOT(checkForHistReset(QString))); +} + +void CmdLine::setFlags(int flgs) +{ + flags |= flgs; +} + +void CmdLine::unsetFlags(int flgs) +{ + flags ^= flgs; +} + +void CmdLine::selectionCheck() +{ + if (flags & HIDDEN) lineEdit()->deselect(); +} + +void CmdLine::hideText(const QString &txt) +{ + if (flags & HIDDEN) + { + int currentPos = lineEdit()->cursorPosition(); + + if (txt.size() > hiddenText.size()) + { + int len = txt.size() - hiddenText.size(); + + hiddenText.insert(currentPos - len, txt.mid(currentPos - len, len)); + + lineEdit()->setText(QString(hiddenText.size(), '#')); + } + else if (hiddenText.size() > txt.size()) + { + int len = hiddenText.size() - txt.size(); + + hiddenText.remove(currentPos, len); + } + + lineEdit()->setCursorPosition(currentPos); + } +} + +void CmdLine::checkForHistReset(const QString &txt) +{ + if (txt.isEmpty()) setCurrentIndex(-1); +} + +QString CmdLine::cmdNameOnly(const QString &line) +{ + QString ret = line; + int pos = line.indexOf(" "); + + if (pos != -1) + { + ret = line.left(pos); + } + + return ret.toLower(); +} + +void CmdLine::echo(const QString &line) +{ + if (!line.trimmed().isEmpty()) + { + emit mainTxtOut(line + "\n\n"); + } +} + +void CmdLine::clearHist() +{ + localData->insert("command_hist", QJsonArray()); + + saveLocalData(localData); + clear(); + + lineEdit()->clear(); +} + +void CmdLine::syncHistToFile() +{ + QJsonArray hist; + + for (int i = 0; i < count(); ++i) + { + hist.append(itemData(i, Qt::DisplayRole).toString()); + } + + localData->insert("command_hist", hist); + + saveLocalData(localData); +} + +void CmdLine::syncHistFromFile() +{ + clear(); + + QJsonArray hist = localData->value("command_hist").toArray(); + + for (auto item : hist) + { + addItem(item.toString()); + } + + setCurrentIndex(-1); + setInsertPolicy(QComboBox::InsertAtTop); + + lineEdit()->clear(); +} + +void CmdLine::toHost(const QString &cmdName, const QString &args) +{ + if (flags & HOST_HOOK) + { + emit dataToHookedHost(toTEXT(args), TEXT); + } + else if (!cmdName.isEmpty()) + { + quint16 cmdId = Shared::hostCmds->key(cmdName); + + if (!Shared::hostCmds->values().contains(cmdName)) + { + emit errTxtOut("err: No such command: " + cmdName + "\n\n"); + } + else if (Shared::genfileCmds->contains(cmdId)) + { + emit dataToGenFile(cmdId, toTEXT(args)); + } + else + { + emit dataToHost(cmdId, toTEXT(args), TEXT); + } + } +} + +void CmdLine::toLocalCmd(const QString &cmdName, const QString &args) +{ + if (flags & LOCAL_HOOK) + { + emit dataToHookedCmdObj(args); + } + else + { + emit dataToCommandObj(cmdName, args); + } +} + +void CmdLine::procCmdLine(const QString &line) +{ + QString cmdName; + QString argsLine; + + if (!(flags & (GEN_HOOK | HOST_HOOK | LOCAL_HOOK))) + { + cmdName = cmdNameOnly(line.trimmed()); + argsLine = line.trimmed().mid(cmdName.size() + 1); + } + else if (Shared::hookBypass->contains(cmdNameOnly(line), Qt::CaseInsensitive)) + { + cmdName = cmdNameOnly(line.trimmed()); + argsLine = line.trimmed().mid(cmdName.size() + 1); + } + else if (flags & HIDDEN) + { + argsLine = hiddenText; + } + else + { + argsLine = line.trimmed(); + } + + if (flags & GEN_HOOK) + { + emit dataToHookedGenFile(toTEXT(argsLine)); + } + else if (cmdName.startsWith(CMD_ESCAPE)) + { + toHost(cmdName.mid(1), argsLine); + } + else if (Shared::clientCmds->contains(cmdName)) + { + toLocalCmd(cmdName, argsLine); + } + else + { + toHost(cmdName, argsLine); + } +} + +void CmdLine::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu *menu = lineEdit()->createStandardContextMenu(); + + menu->addAction("Clear History", this, SLOT(clearHist())); + menu->exec(event->globalPos()); + menu->deleteLater(); +} + +void CmdLine::duplicateScan(const QString &txt) +{ + // this will remove any duplicates in the command line history, skipping over 1st line. + // why not setDuplicatesEnabled(false)? the problem with that is it does an "inplace + // replace" which means the duplicate item does not move from its position on the list + // when inserted. i want this app to "float the duplicate to the top" when inserted + // hence why i created this function. + + if (!(flags & HIDDEN)) + { + for (int i = 1; i < count(); ++i) + { + if (itemText(i) == txt) + { + removeItem(i); + } + } + } +} + +void CmdLine::keyReleaseEvent(QKeyEvent *event) +{ + if (event->key() == Qt::Key_Return) + { + echo(lineEdit()->text()); + procCmdLine(lineEdit()->text()); + duplicateScan(lineEdit()->text()); + + if (flags & HIDDEN) + { + removeItem(0); + unsetFlags(HIDDEN); + + hiddenText.clear(); + } + + lineEdit()->clear(); + + syncHistToFile(); + setCurrentIndex(-1); + } + else + { + QComboBox::keyReleaseEvent(event); + } +} diff --git a/src/cmd_line.h b/src/cmd_line.h new file mode 100644 index 0000000..65cf81e --- /dev/null +++ b/src/cmd_line.h @@ -0,0 +1,71 @@ +#ifndef CMDLINE_H +#define CMDLINE_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include "common.h" + +class CmdLine : public QComboBox +{ + Q_OBJECT + +private: + + QJsonObject *localData; + QString hiddenText; + int flags; + + void keyReleaseEvent(QKeyEvent *event); + void contextMenuEvent(QContextMenuEvent *event); + void procCmdLine(const QString &line); + void echo(const QString &line); + void syncHistToFile(); + void syncHistFromFile(); + void duplicateScan(const QString &txt); + void toHost(const QString &cmdName, const QString &args); + void toLocalCmd(const QString &cmdName, const QString &args); + QString cmdNameOnly(const QString &line); + +private slots: + + void selectionCheck(); + void hideText(const QString &txt); + void checkForHistReset(const QString &txt); + +public: + + explicit CmdLine(QWidget *parent = nullptr); + +public slots: + + void setFlags(int flgs); + void unsetFlags(int flgs); + void clearHist(); + +signals: + + void dataToCommandObj(const QString &cmdName, const QString &argsLine); + void dataToHookedCmdObj(const QString &argsLine); + void dataToHost(quint16 cmdId, const QByteArray &data, uchar dType); + void dataToHookedHost(const QByteArray &data, uchar dType); + void dataToGenFile(quint16 cmdId, const QByteArray &data); + void dataToHookedGenFile(const QByteArray &data); + void mainTxtOut(const QString &txt); + void errTxtOut(const QString &txt); +}; + +#endif // CMDLINE_H diff --git a/src/cmd_objs/bookmarks.cpp b/src/cmd_objs/bookmarks.cpp new file mode 100644 index 0000000..649b1b6 --- /dev/null +++ b/src/cmd_objs/bookmarks.cpp @@ -0,0 +1,222 @@ +#include "bookmarks.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +SaveBookmark::SaveBookmark(QObject *parent) : Command(parent) +{ + setObjectName("save_bookmark"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString SaveBookmark::shortText() {return tr("create or update a host bookmark.");} +QString SaveBookmark::ioText() {return tr("[-name (text) {-addr (text)} {-port (text)} {-force}]/[text]");} +QString SaveBookmark::longText() {return TXT_SaveBookmark;} + +ListBookmarks::ListBookmarks(QObject *parent) : Command(parent) +{ + setObjectName("list_bookmarks"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString ListBookmarks::shortText() {return tr("list all bookmarks available for loading.");} +QString ListBookmarks::ioText() {return tr("[none]/[text]");} +QString ListBookmarks::longText() {return TXT_ListBookmarks;} + +DeleteBookmark::DeleteBookmark(QObject *parent) : Command(parent) +{ + setObjectName("delete_bookmark"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString DeleteBookmark::shortText() {return tr("permanently delete a bookmark.");} +QString DeleteBookmark::ioText() {return tr("[-name (text)]/[text]");} +QString DeleteBookmark::longText() {return TXT_DeleteBookmark;} + +SeeBookmark::SeeBookmark(QObject *parent) : Command(parent) +{ + setObjectName("view_bookmark"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString SeeBookmark::shortText() {return tr("view the contents of a bookmark.");} +QString SeeBookmark::ioText() {return tr("[-name (text)]/[text]");} +QString SeeBookmark::longText() {return TXT_SeeBookmark;} + +void SaveBookmark::term() +{ + baseArgs.clear(); + baseName.clear(); + + emit unsetUserIO(LOCAL_HOOK); +} + +void SaveBookmark::run(const QString &name, QStringList &args) +{ + QFile file(appDataDir() + BOOKMARK_FOLDER + "/" + name + ".json"); + + QJsonObject json; + + if (file.open(QFile::WriteOnly | QFile::Truncate)) + { + QString addr = getParam("-addr", args); + int port = getParam("-port", args).toInt(); + + if (addr.isEmpty()) addr = *Shared::hostAddress; + if (port == 0) port = *Shared::hostPort; + + json.insert("address", addr); + json.insert("port", port); + + QJsonDocument doc(json); + + file.write(doc.toJson()); + } + else + { + emit errTxtOut("err: Could not open the bookmark file for writing, reason: " + file.errorString() + "\n"); + } + + file.close(); +} + +void SaveBookmark::askOverwrite() +{ + emit mainTxtOut("'" + baseName + "' already exists. do you want to overwrite? (y/n): "); + emit setUserIO(LOCAL_HOOK); +} + +void SaveBookmark::dataIn(const QString &argsLine) +{ + if (activeHook()) + { + if (QRegExp("y", Qt::CaseInsensitive).exactMatch(argsLine)) + { + run(baseName, baseArgs); + term(); + } + else if (QRegExp("n", Qt::CaseInsensitive).exactMatch(argsLine)) + { + term(); + } + else + { + askOverwrite(); + } + } + else + { + QStringList args = parseArgs(argsLine); + bool force = argExists("-force", args); + QString name = getParam("-name", args); + + if (name.isEmpty()) + { + emit errTxtOut("err: Bookmark name (-name) not given.\n"); + } + else + { + baseName = name; + baseArgs = args; + + if (QFile(appDataDir() + BOOKMARK_FOLDER + "/" + name + ".json").exists()) + { + if (force) run(name, args); + else askOverwrite(); + } + else + { + run(name, args); + } + } + } +} + +void ListBookmarks::dataIn(const QString &argsLine) +{ + Q_UNUSED(argsLine); + + QStringList list = QDir(appDataDir() + BOOKMARK_FOLDER).entryList(QStringList() << "*.json", QDir::Files, QDir::Name); + + if (list.isEmpty()) + { + emit mainTxtOut("Empty...\n"); + } + else + { + emit mainTxtOut("Bookmarks:\n\n"); + + for (int i = 0; i < list.size(); ++i) + { + emit mainTxtOut(" " + QFileInfo(list[i]).baseName() + "\n"); + } + } +} + +void DeleteBookmark::dataIn(const QString &argsLine) +{ + QStringList args = parseArgs(argsLine); + QString name = getParam("-name", args); + + if (name.isEmpty()) + { + emit errTxtOut("err: Bookmark name (-name) not given.\n"); + } + else + { + QString path = appDataDir() + BOOKMARK_FOLDER + "/" + name + ".json"; + + if (!QFile::remove(path)) + { + emit errTxtOut("err: Could not delete the bookmark, the file might not exist or you don't have write permissions.\n"); + } + } +} + +void SeeBookmark::dataIn(const QString &argsLine) +{ + QStringList args = parseArgs(argsLine); + QString name = getParam("-name", args); + + if (name.isEmpty()) + { + emit errTxtOut("err: Bookmark name (-name) not given.\n"); + } + else + { + QString path = appDataDir() + BOOKMARK_FOLDER + "/" + name + ".json"; + + QFile file(path, this); + + if (file.open(QFile::ReadOnly)) + { + QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); + + emit mainTxtOut("address: " + doc.object().value("address").toString() + "\n"); + emit mainTxtOut("port: " + QString::number(doc.object().value("port").toInt()) + "\n"); + } + else + { + emit errTxtOut("err: Could not open the requested bookmark file for reading, reason: " + file.errorString() + '\n'); + } + + file.close(); + } +} diff --git a/src/cmd_objs/bookmarks.h b/src/cmd_objs/bookmarks.h new file mode 100644 index 0000000..ac1e7d3 --- /dev/null +++ b/src/cmd_objs/bookmarks.h @@ -0,0 +1,115 @@ +#ifndef BOOKMARKS_H +#define BOOKMARKS_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "command.h" + +class SaveBookmark : public Command +{ + Q_OBJECT + +private: + + QString baseName; + QStringList baseArgs; + + void askOverwrite(); + +public: + + void run(const QString &name, QStringList &args); + + QString shortText(); + QString ioText(); + QString longText(); + void term(); + + explicit SaveBookmark(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//--------------------------------------- + +class ListBookmarks : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit ListBookmarks(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//-------------------------------------- + +class DeleteBookmark : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit DeleteBookmark(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//------------------------------------- + +class SeeBookmark : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit SeeBookmark(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +#endif // BOOKMARKS_H diff --git a/src/cmd_objs/command.cpp b/src/cmd_objs/command.cpp new file mode 100644 index 0000000..6069ce8 --- /dev/null +++ b/src/cmd_objs/command.cpp @@ -0,0 +1,116 @@ +#include "command.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +Command::Command(QObject *parent) : QObject(parent) +{ + // the QObject::objectName property determines the command + // name for any object inheriting this object. avoid using + // spaces and keep in mind that all command names are case + // insensitive. avoid starting the command with the char + // defined in CMD_ESCAPE, this char is used to send + // commands directly to the host in case of naming + // conflicts with the host commands. + + setObjectName("do_nothing"); + + connect(this, &Command::setUserIO, this, &Command::setHook); + connect(this, &Command::unsetUserIO, this, &Command::unsetHook); +} + +void Command::setHook(int flgs) +{ + if (flgs & LOCAL_HOOK) + { + *Shared::clientHookedCmd = objectName(); + } +} + +bool Command::activeHook() +{ + return *Shared::clientHookedCmd == objectName(); +} + +void Command::unsetHook(int flgs) +{ + if ((flgs & LOCAL_HOOK) && activeHook()) + { + Shared::clientHookedCmd->clear(); + } +} + +QString Command::shortText() +{ + // return a short summary on what this command actually does. + // the client will use this to display help when '?' is + // passed. + + return ""; +} + +QString Command::ioText() +{ + // just like shortText(), this is a help text command that + // describes what input/output data to expect to/from this + // command. the client will use the "[i]/[o]" format so it's + // recommanded to display the text like this: [text]/[binary] + // or you can be more descriptive like this: + // [directory(text)]/[pcm_data(binary)]. + + return "[none]/[none]"; +} + +QString Command::longText() +{ + // this is a help text function that is used by the client to + // display full detailed information about the command and + // it's usage. it's recommanded to be as thorough as possible + // to help users understand proper usage of your command. + + return ""; +} + +QString Command::libText() +{ + // return the library name and version this command object + // belongs to. there's no need to change this function's + // output if creating an internal command. + + return QString(APP_NAME) + " v" + QCoreApplication::applicationVersion(); +} + +void Command::cmdCall(const QString &cmdName, const QString &argsLine) +{ + if (cmdName == objectName()) + { + dataIn(argsLine); + postExec(); + } +} + +void Command::hookedCmdCall(const QString &argsLine) +{ + if (activeHook()) + { + cmdCall(objectName(), argsLine); + } +} + +void Command::postExec() +{ + emit mainTxtOut("\nFinished: " + objectName() + "\n\n"); +} diff --git a/src/cmd_objs/command.h b/src/cmd_objs/command.h new file mode 100644 index 0000000..9452261 --- /dev/null +++ b/src/cmd_objs/command.h @@ -0,0 +1,71 @@ +#ifndef COMMAND_H +#define COMMAND_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include "../common.h" + +class Command : public QObject +{ + Q_OBJECT + +private slots: + + void setHook(int flgs); + void unsetHook(int flgs); + +protected: + + bool activeHook(); + +public: + + virtual QString shortText(); + virtual QString ioText(); + virtual QString longText(); + virtual QString libText(); + virtual void dataIn(const QString &) {} + virtual void term() {} + + explicit Command(QObject *parent = nullptr); + + void postExec(); + +public slots: + + virtual void onStartup() {} + + void cmdCall(const QString &cmdName, const QString &argsLine); + void hookedCmdCall(const QString &argsLine); + +signals: + + void mainTxtOut(const QString &txt); + void errTxtOut(const QString &txt); + void bigTxtOut(const QString &txt); + void setUserIO(int flgs); + void unsetUserIO(int flgs); + void setMaxLines(int value); + void termHostCmd(); + void connectToHost(); + void quitApp(); + void disconnectHost(); + void colorsChanged(); + void fontChanged(); +}; + +#endif // COMMAND_H diff --git a/src/cmd_objs/exec.cpp b/src/cmd_objs/exec.cpp new file mode 100644 index 0000000..64c5bd7 --- /dev/null +++ b/src/cmd_objs/exec.cpp @@ -0,0 +1,140 @@ +#include "exec.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +Connect::Connect(QObject *parent) : Command(parent) +{ + setObjectName("connect"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString Connect::shortText() {return tr("connect a MRCI host.");} +QString Connect::ioText() {return tr("[-addr (text) -port (text) {-save (bookmark)}] or [-load (bookmark)]/[text]");} +QString Connect::longText() {return TXT_Connect;} + +Quit::Quit(QObject *parent) : Command(parent) +{ + setObjectName("quit"); + + Shared::hookBypass->append(objectName()); + Shared::clientCmds->insert(objectName(), this); +} + +QString Quit::shortText() {return tr("close the application.");} +QString Quit::ioText() {return tr("[none]/[none]");} +QString Quit::longText() {return TXT_Quit;} + +EndSession::EndSession(QObject *parent) : Command(parent) +{ + setObjectName("end_session"); + + Shared::hookBypass->append(objectName()); + Shared::clientCmds->insert(objectName(), this); +} + +QString EndSession::shortText() {return tr("disconnect from the host.");} +QString EndSession::ioText() {return tr("[none]/[none]");} +QString EndSession::longText() {return TXT_EndSession;} + +Term::Term(QObject *parent) : Command(parent) +{ + setObjectName("term"); + + Shared::hookBypass->append(objectName()); + Shared::clientCmds->insert(objectName(), this); +} + +QString Term::shortText() {return tr("terminate the currently running command.");} +QString Term::ioText() {return tr("[none]/[CMD_ID]");} +QString Term::longText() {return TXT_Term;} + +void Connect::dataIn(const QString &argsLine) +{ + QStringList args = parseArgs(argsLine); + + *Shared::hostAddress = getParam("-addr", args); + *Shared::hostPort = getParam("-port", args).toUShort(); + + QString saveName = getParam("-save", args); + QString loadName = getParam("-load", args); + + if (!saveName.isEmpty()) + { + SaveBookmark(this).run(saveName, args); + } + + if (!loadName.isEmpty()) + { + QFile file(appDataDir() + BOOKMARK_FOLDER + "/" + loadName + ".json", this); + + if (file.open(QFile::ReadOnly)) + { + QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); + + *Shared::hostAddress = doc.object().value("address").toString(); + *Shared::hostPort = static_cast(doc.object().value("port").toInt()); + } + else + { + emit errTxtOut("err: Could not open the requested bookmark for reading, reason: " + file.errorString() + "\n"); + } + + file.close(); + } + + if (Shared::hostAddress->isEmpty()) + { + emit errTxtOut("err: Host address is empty.\n"); + } + else if (QHostAddress(*Shared::hostAddress).isNull()) + { + emit errTxtOut("err: '" + *Shared::hostAddress + "' is not a valid address.\n"); + } + else if (*Shared::hostPort == 0) + { + emit errTxtOut("err: The host port cannot be 0.\n"); + } + else + { + emit connectToHost(); + } +} + +void Quit::dataIn(const QString &argsLine) +{ + Q_UNUSED(argsLine); + + emit quitApp(); +} + +void EndSession::dataIn(const QString &argsLine) +{ + Q_UNUSED(argsLine); + + if (*Shared::connectedToHost) + { + emit disconnectHost(); + } +} + +void Term::dataIn(const QString &argsLine) +{ + Q_UNUSED(argsLine); + + emit termHostCmd(); +} diff --git a/src/cmd_objs/exec.h b/src/cmd_objs/exec.h new file mode 100644 index 0000000..6aacf1d --- /dev/null +++ b/src/cmd_objs/exec.h @@ -0,0 +1,99 @@ +#ifndef EXEC_H +#define EXEC_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include + +#include "bookmarks.h" +#include "command.h" + +class Connect : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit Connect(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//------------------------------------------ + +class Quit : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit Quit(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//---------------------------------------- + +class EndSession : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit EndSession(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//--------------------------------------- + +class Term : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit Term(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +#endif // EXEC_H diff --git a/src/cmd_objs/info.cpp b/src/cmd_objs/info.cpp new file mode 100644 index 0000000..50af343 --- /dev/null +++ b/src/cmd_objs/info.cpp @@ -0,0 +1,99 @@ +#include "info.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +About::About(QObject *parent) : Command(parent) +{ + setObjectName("about"); + + Shared::clientCmds->insert(objectName(), this); +} + +void About::onStartup() {dataIn(QString());} +QString About::shortText() {return tr("display information about this MRCI client and display available client specific commands.");} +QString About::ioText() {return tr("[{cmd_name}]/[text]");} +QString About::longText() {return TXT_About;} + +void About::dataIn(const QString &argsLine) +{ + QStringList args = parseArgs(argsLine); + + if (args.size() > 0) + { + QString cmdName = args[0].toLower().trimmed(); + + if (Shared::clientCmds->contains(cmdName)) + { + Command *obj = Shared::clientCmds->value(cmdName); + QString txt; + + QTextStream txtOut(&txt); + + wordWrap("i/o: ", txtOut, obj->ioText(), Shared::mainWidget); + txtOut << "" << endl; + wordWrap("library: ", txtOut, obj->libText(), Shared::mainWidget); + txtOut << "" << endl; + wordWrap("usage: ", txtOut, obj->longText(), Shared::mainWidget); + + emit mainTxtOut(txt); + } + else + { + emit errTxtOut("err: No such command: '" + cmdName + "'\n"); + } + } + else + { + QString txt; + QTextStream txtOut(&txt); + + txtOut << libText() << endl << endl; + txtOut << "Based on QT " << QT_VERSION_STR << " " << 8 * QT_POINTER_SIZE << "bit" << endl << endl; + txtOut << "MRCI host support: " << MRCI_VERSION << endl << endl; + txtOut << "The program is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE" << endl; + txtOut << "WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE." << endl << endl; + txtOut << "note: In special cases when an internal client command is the same as a" << endl; + txtOut << " remote command, start your command line with a '" << CMD_ESCAPE << "' to bypass the" << endl; + txtOut << " client's parsing." << endl << endl; + txtOut << "usage: " << endl << endl; + txtOut << "" << endl << endl; + + QStringList cmdNames = Shared::clientCmds->keys(); + int largestCmd = 0; + + for (int i = 0; i < cmdNames.size(); ++i) + { + if (cmdNames[i].size() > largestCmd) largestCmd = cmdNames[i].size(); + } + + cmdNames.sort(Qt::CaseInsensitive); + + for (int i = 0; i < cmdNames.size(); ++i) + { + wordWrap(cmdNames[i].leftJustified(largestCmd, ' ') + " - ", txtOut, Shared::clientCmds->value(cmdNames[i])->shortText(), Shared::mainWidget); + } + + txtOut << endl << endl << "for more detailed information about a command type: about " << endl << endl; + + emit mainTxtOut(txt); + } +} + +void About::run() +{ + dataIn(QString()); +} diff --git a/src/cmd_objs/info.h b/src/cmd_objs/info.h new file mode 100644 index 0000000..156c14f --- /dev/null +++ b/src/cmd_objs/info.h @@ -0,0 +1,44 @@ +#ifndef INFO_H +#define INFO_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include + +#include "command.h" + +class About : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + void run(); + + explicit About(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); + void onStartup(); +}; + +#endif // INFO_H diff --git a/src/cmd_objs/long_txt.h b/src/cmd_objs/long_txt.h new file mode 100644 index 0000000..b954643 --- /dev/null +++ b/src/cmd_objs/long_txt.h @@ -0,0 +1,68 @@ +#ifndef LONG_TXT_H +#define LONG_TXT_H + +#define TXT_SaveBookmark "\ +create or update a bookmark given using the -name argument. you can pass the optional -force \ +argument to overwrite an existing bookmark without a confirmation question. you can also pass \ +-addr and/or -port to set the bookmark parameters; if any of these are not passed, it is \ +backfilled with the currently set address/port." + +#define TXT_ListBookmarks "\ +this list all available bookmarks that can be used with the -load option when connecting to a \ +host." + +#define TXT_DeleteBookmark "\ +permanently delete the bookmark given in -name." + +#define TXT_SeeBookmark "\ +view all of the parameters currently set in a bookmark given by the -name argument." + +#define TXT_Connect "\ +connect to the host passed by -addr and -port. example: connect -addr 127.0.0.1 -port 3548. you can \ +also pass -save to save this host address/port to a bookmark for later use with the -load so you \ +don't have to re-enter this information everytime. note: the -save option overwrites the \ +bookmark if it exists." + +#define TXT_Quit "\ +exit the client and end the current session if connected to a host." + +#define TXT_Help "\ +list all available commands in this interface. if connected to a host, this will list all host \ +commands as well. pass the optional cmd_name parameter to see more detailed information about the \ +command." + +#define TXT_About "\ +display application usage information, along with it's version number and supported MRCI protocol \ +version. you can pass the cmd_name of another command to display more information specific to it. \ +example: about connect" + +#define TXT_SeeParams "\ +view the current session's parameters and connection status information (as seen by this \ +application)." + +#define TXT_Term "\ +this will terminate all actions currently being performed by any command; both remotely and \ +locally." + +#define TXT_EndSession "\ +this diconnects the client from the currently connected host. this will inturn end the session \ +at the host side. warning: this will inturpt any running command at the host." + +#define TXT_SetColors "\ +this sets the colors that this application use when displaying text/error output as well as the \ +background color. -text is for regular text output, -error for error output and the -bg for the \ +background. each of these arguments take an RGB color code that must begin with a #. pass an empty \ +parameter on any of these arguments to reset it to the default. example: -text or -text ''" + +#define TXT_SetFont "\ +set the font family for all text displayed by this application given in -name and font size given in \ +-size. it's highly recommended to use monospaced font. don't forget to add quotes if passing a font \ +family name that contain spaces. pass an empty parameter on any of these arguments to reset it to the \ +default. example: -name or -name ''" + +#define TXT_SetMaxLines "\ +set or view the maximum amount of lines of text that can be displayed in this application. pass -value to \ +to set this limit or leave it out to display what the limit is currently set at. this has a minimum value \ +of 50 and a maxmum of 100000." + +#endif // LONG_TXT_H diff --git a/src/cmd_objs/status.cpp b/src/cmd_objs/status.cpp new file mode 100644 index 0000000..f227742 --- /dev/null +++ b/src/cmd_objs/status.cpp @@ -0,0 +1,70 @@ +#include "status.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +Status::Status(QObject *parent) : Command(parent) +{ + setObjectName("status"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString Status::shortText() {return tr("view the current session parameters.");} +QString Status::ioText() {return tr("[none]/[text]");} +QString Status::longText() {return TXT_SeeParams;} + +void Status::dataIn(const QString &argsLine) +{ + Q_UNUSED(argsLine); + + QString txt; + QTextStream txtOut(&txt); + + txtOut << "--Local data" << endl << endl; + txtOut << " Client version : " << QCoreApplication::applicationVersion() << endl; + txtOut << " Connected? : " << boolText(*Shared::connectedToHost) << endl; + txtOut << " Address : " << *Shared::hostAddress << endl; + txtOut << " Port : " << *Shared::hostPort << endl; + + if (*Shared::connectedToHost) + { + txtOut << "" << endl; + txtOut << "--Session data" << endl << endl; + txtOut << " Client address : " << Shared::socket->localAddress().toString() << endl; + txtOut << " Host address : " << Shared::socket->peerAddress().toString() << endl; + txtOut << " Session id : " << Shared::sessionId->toHex() << endl; + txtOut << " Host version : " << verText(*Shared::servMajor, *Shared::servMinor, *Shared::servPatch) << endl; + txtOut << " GEN_FILE commands : "; + + QStringList genCmds = Shared::genfileCmds->values(); + + if (genCmds.isEmpty()) + { + genCmds.sort(Qt::CaseInsensitive); + + txtOut << "" << endl; + } + + for (int i = 0; i < genCmds.size(); ++i) + { + if (i != 0) txtOut << " " << genCmds[i] << endl; + else txtOut << genCmds[i] << endl; + } + } + + emit mainTxtOut(txt); +} diff --git a/src/cmd_objs/status.h b/src/cmd_objs/status.h new file mode 100644 index 0000000..5ca3549 --- /dev/null +++ b/src/cmd_objs/status.h @@ -0,0 +1,39 @@ +#ifndef STATUS_H +#define STATUS_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include "command.h" + +class Status : public Command +{ + Q_OBJECT + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit Status(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +#endif // STATUS_H diff --git a/src/cmd_objs/style.cpp b/src/cmd_objs/style.cpp new file mode 100644 index 0000000..bf3a7e9 --- /dev/null +++ b/src/cmd_objs/style.cpp @@ -0,0 +1,174 @@ +#include "style.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +void checkArgs(bool *changed, QJsonObject *jsonData, const QString &arg, const QStringList &args, const QString &dataKey, const QString &defaultData) +{ + if (argExists(arg, args)) + { + QString data = getParam(arg, args); + QJsonObject obj = jsonData->value("text_settings").toObject(); + + if (data.isEmpty()) + { + *changed = true; + + obj.insert(dataKey, defaultData); + } + else if (dataKey == "font_family") + { + *changed = true; + + obj.insert(dataKey, data); + } + else if (dataKey == "font_size") + { + bool ok; + + data.toInt(&ok); + + if (ok) + { + *changed = true; + + obj.insert(dataKey, data); + } + } + else + { + QColor colorObj(data); + + if (colorObj.isValid()) + { + *changed = true; + + obj.insert(dataKey, data); + } + } + + if (*changed) + { + jsonData->insert("text_settings", obj); + } + } +} + +SetColors::SetColors(QObject *parent) : Command(parent) +{ + localData = Shared::localData; + + setObjectName("colors"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString SetColors::shortText() {return tr("set the colors (text/background) of this terminal emulator.");} +QString SetColors::ioText() {return tr("[{-text} ({color_code}) {-error} ({color_code}) {-bg} ({color_code})]/[none]");} +QString SetColors::longText() {return TXT_SetColors;} + +SetFont::SetFont(QObject *parent) : Command (parent) +{ + localData = Shared::localData; + + setObjectName("font"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString SetFont::shortText() {return tr("set/view the text font family and size for this terminal emulator.");} +QString SetFont::ioText() {return tr("[-name (text)]/[none]");} +QString SetFont::longText() {return TXT_SetFont;} + +SetMaxLines::SetMaxLines(QObject *parent) : Command (parent) +{ + localData = Shared::localData; + + setObjectName("max_lines"); + + Shared::clientCmds->insert(objectName(), this); +} + +QString SetMaxLines::shortText() {return tr("set/view the maximum amount of lines this terminal emulator can display.");} +QString SetMaxLines::ioText() {return tr("[{-value (int)}]/[none]");} +QString SetMaxLines::longText() {return TXT_SetMaxLines;} + +void SetColors::dataIn(const QString &argsLine) +{ + bool changed = false; + QStringList args = parseArgs(argsLine); + + checkArgs(&changed, localData, "-text", args, "text_color", "#FBFBD7"); + checkArgs(&changed, localData, "-error", args, "err_color", "#BB55D8"); + checkArgs(&changed, localData, "-bg", args, "bg_color", "#363A49"); + + QJsonObject obj = localData->value("text_settings").toObject(); + + emit mainTxtOut("text: " + obj.value("text_color").toString() + "\n"); + emit mainTxtOut("error: " + obj.value("err_color").toString() + "\n"); + emit mainTxtOut("bg: " + obj.value("bg_color").toString() + "\n"); + + if (changed) emit colorsChanged(); +} + +void SetFont::dataIn(const QString &argsLine) +{ + bool changed = false; + QStringList args = parseArgs(argsLine); + + checkArgs(&changed, localData, "-name", args, "font_family", "courier"); + checkArgs(&changed, localData, "-size", args, "font_size", "9"); + + QJsonObject obj = localData->value("text_settings").toObject(); + + emit mainTxtOut("family: " + obj.value("font_family").toString() + "\n"); + emit mainTxtOut("size: " + obj.value("font_size").toString() + "\n"); + + if (changed) emit fontChanged(); +} + +void SetMaxLines::dataIn(const QString &argsLine) +{ + QStringList args = parseArgs(argsLine); + QString valStr = getParam("-value", args); + + if (valStr.isEmpty()) + { + emit mainTxtOut(QString::number(localData->value("max_lines").toInt()) + "\n"); + } + else + { + bool ok; + int val = valStr.toInt(&ok); + + if (!ok) + { + emit errTxtOut("err: '" + valStr + "' is not a valid integer.\n"); + } + else if ((val < 50) || (val > 100000)) + { + emit errTxtOut("err: The value must range 50 - 100000.\n"); + } + else + { + localData->insert("max_lines", val); + + saveLocalData(localData); + + emit setMaxLines(val); + } + } +} diff --git a/src/cmd_objs/style.h b/src/cmd_objs/style.h new file mode 100644 index 0000000..071ead7 --- /dev/null +++ b/src/cmd_objs/style.h @@ -0,0 +1,96 @@ +#ifndef STYLE_H +#define STYLE_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include +#include +#include +#include + +#include "command.h" + +void checkArgs(bool *changed, QJsonObject *jsonData, const QString &arg, const QStringList &args, const QString &dataKey, const QString &defaultData); + +class SetColors: public Command +{ + Q_OBJECT + +private: + + QJsonObject *localData; + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit SetColors(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//------------------------- + +class SetFont: public Command +{ + Q_OBJECT + +private: + + QJsonObject *localData; + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit SetFont(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +//-------------------------- + +class SetMaxLines: public Command +{ + Q_OBJECT + +private: + + QJsonObject *localData; + +public: + + QString shortText(); + QString ioText(); + QString longText(); + + explicit SetMaxLines(QObject *parent = nullptr); + +public slots: + + void dataIn(const QString &argsLine); +}; + +#endif // STYLE_H diff --git a/src/common.cpp b/src/common.cpp new file mode 100644 index 0000000..e783c79 --- /dev/null +++ b/src/common.cpp @@ -0,0 +1,395 @@ +#include "common.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +void setupTextSettings(QJsonObject *data) +{ + QString txtColorStr = "#FBFBD7"; + QString bgColorStr = "#363A49"; + QString errColorStr = "#BB55D8"; + QString fontFamily = "courier"; + QString fontSize = "9"; + + QJsonObject obj; + + if (data->contains("text_settings")) + { + obj = data->value("text_settings").toObject(); + + if (!obj.contains("text_color")) obj.insert("text_color", txtColorStr); + if (!obj.contains("err_color")) obj.insert("err_color", errColorStr); + if (!obj.contains("font_family")) obj.insert("font_family", fontFamily); + if (!obj.contains("bg_color")) obj.insert("bg_color", bgColorStr); + if (!obj.contains("font_size")) obj.insert("font_size", fontSize); + } + else + { + obj.insert("text_color", txtColorStr); + obj.insert("err_color", errColorStr); + obj.insert("font_family", fontFamily); + obj.insert("bg_color", bgColorStr); + obj.insert("font_size", fontSize); + } + + data->insert("text_settings", obj); + + if (!data->contains("max_lines")) + { + data->insert("max_lines", DEFAULT_MAX_LINES); + } + + saveLocalData(data); +} + +void loadTextSettings(QJsonObject *data, QWidget *widget) +{ + QString bgColor = data->value("text_settings").toObject().value("bg_color").toString(); + QString txtColor = data->value("text_settings").toObject().value("text_color").toString(); + QString fntFamily = data->value("text_settings").toObject().value("font_family").toString(); + QString fntSize = data->value("text_settings").toObject().value("font_size").toString(); + QPalette pal = widget->palette(); + QFont fnt = widget->font(); + + pal.setColor(QPalette::Active, QPalette::Base, QColor(bgColor)); + pal.setColor(QPalette::Inactive, QPalette::Base, QColor(bgColor)); + pal.setColor(QPalette::Active, QPalette::Text, QColor(txtColor)); + fnt.setFamily(fntFamily); + fnt.setPointSize(fntSize.toInt()); + + widget->setPalette(pal); + widget->setFont(fnt); +} + +QString appDataDir() +{ + QString path = QDir::homePath() + "/"; + +#ifndef Q_OS_WIN32 + + path.append("." + QString(APP_TARGET) + "/"); + +#else + + path.append(QString("AppData/Local/") + QString(APP_TARGET) + "/"); + +#endif + + QDir dir; + + dir.mkpath(path); + dir.mkpath(path + BOOKMARK_FOLDER); + + return path; +} + +void saveLocalData(QJsonObject *obj) +{ + QFile file(appDataDir() + CONFIG_FILENAME); + + if (file.open(QFile::WriteOnly | QFile::Truncate)) + { + file.write(QJsonDocument(*obj).toJson()); + } + + file.close(); +} + +void loadLocalData(QJsonObject *obj) +{ + QFile file(appDataDir() + CONFIG_FILENAME); + + if (file.open(QFile::ReadOnly)) + { + *obj = QJsonDocument::fromJson(file.readAll()).object(); + } + + file.close(); +} + +QByteArray wrFrame(quint16 cmdId, const QByteArray &data, uchar dType) +{ + QByteArray typeBa = wrInt(dType, 8); + QByteArray cmdBa = wrInt(cmdId, 16); + QByteArray sizeBa = wrInt(data.size(), 24); + + return typeBa + cmdBa + sizeBa + data; +} + +QByteArray toTEXT(const QString &txt) +{ + QByteArray ret = QTextCodec::codecForName(TXT_CODEC)->fromUnicode(txt); + + return ret.mid(2); +} + +QString fromTEXT(const QByteArray &txt) +{ + return QTextCodec::codecForName(TXT_CODEC)->toUnicode(txt); +} + +QByteArray wrInt(quint64 num, int numOfBits) +{ + // convert quint64 values into little endian QByteArrays. + // if any invalid numOfBits is passed the function will + // return an empty QByteArray. vaild range: 1-64. + + // also note that this function will truncate in a per byte + // bases but not in a per bit bases. + + // eg. wrInt(1024, 8) will return 0. + // 1024 (0x00, 0x04) to 8 bits (0x00) + // eg. wrInt(255, 2) will still return 255. + // 255 (0xFF) to 2 bits (0xFF) + + QByteArray ret; + quint64 leNum = qToLittleEndian(num); + char *ptr = static_cast(static_cast(&leNum)); + + if (numOfBits < 8) numOfBits = 8; + if (numOfBits <= 64) ret.append(ptr, numOfBits / 8); + + return ret; +} + +quint64 rdInt(const QByteArray &bytes) +{ + // convert little endian QByteArrays into local sytem + // endianness uints. + + QByteArray ba = bytes.leftJustified(sizeof(quint64), 0); + + return qFromLittleEndian((void*) ba.data()); +} + +QString extractCmdName(const QByteArray &data) +{ + QStringList args = parseArgs(data, 1); + QString ret; + + if (!args.isEmpty()) + { + ret = args[0]; + } + + return ret; +} + +QStringList parseArgs(const QByteArray &data, int maxArgs) +{ + QStringList ret; + QString arg; + QString line = fromTEXT(data); + bool inDQuotes = false; + bool inSQuotes = false; + bool escaped = false; + + for (int i = 0; i < line.size(); ++i) + { + if ((line[i] == '\'') && !inDQuotes && !escaped) + { + // single quote ' + + inSQuotes = !inSQuotes; + } + else if ((line[i] == '\"') && !inSQuotes && !escaped) + { + // double quote " + + inDQuotes = !inDQuotes; + } + else + { + escaped = false; + + if (line[i].isSpace() && !inDQuotes && !inSQuotes) + { + // space + + if (!arg.isEmpty()) + { + ret.append(arg); + arg.clear(); + } + } + else + { + if ((line[i] == '\\') && ((i + 1) < line.size())) + { + if ((line[i + 1] == '\'') || (line[i + 1] == '\"')) + { + escaped = true; + } + else + { + arg.append(line[i]); + } + } + else + { + arg.append(line[i]); + } + } + } + + if ((ret.size() >= maxArgs) && (maxArgs != -1)) + { + break; + } + } + + if (!arg.isEmpty() && !inDQuotes && !inSQuotes) + { + ret.append(arg); + } + + return ret; +} + +QStringList parseArgs(const QString &line) +{ + return parseArgs(toTEXT(line), -1); +} + +void wordWrap(const QString &label, QTextStream &txtOut, const QString &txtIn, QWidget *measureWid) +{ + // this breaks up a long text line into smaller lines of text + // equal to or less then the given len. this also avoids line + // breaking mid-word and also honors line breaks by treating + // lines with line breaks as complete text bodies. + + int width = measureWid->width() / 8; + bool labelWr = true; + QString indent = QString(label.size(), ' '); + QStringList textBodies = txtIn.split('\n'); + + for (int i = 0; i < textBodies.size(); ++i) + { + int index = 0; + QStringList words = textBodies[i].split(' '); + QString line; + + while(index < words.size()) + { + line.append(words[index] + " "); + + if ((index == (words.size() - 1)) && !line.isEmpty()) + { + // add the last remaining line if there are no more + // words left to add. + + line.chop(1); + + if (labelWr) txtOut << label << line << endl; + else txtOut << indent << line << endl; + + labelWr = false; + } + else if ((line.size() + words[index + 1].size() + 1) >= width) + { + // check ahead in the words list to see if the next + // word would cause the line to be >= len. if that is + // the case, the line is added to the return and then + // cleared. + + if (labelWr) txtOut << label << line << endl; + else txtOut << indent << line << endl; + + line.clear(); + + labelWr = false; + } + + index++; + } + } +} + +QString boolText(bool state) +{ + if (state) return QString("True"); + else return QString("False"); +} + +QString verText(quint16 maj, quint16 min, quint16 patch) +{ + return QString::number(maj) + "." + QString::number(min) + "." + QString::number(patch); +} + +QString getParam(const QString &key, const QStringList &args) +{ + // this can be used by command objects to pick out parameters + // from a command line that are pointed by a name identifier + // example: -i /etc/some_file, this function should pick out + // "/etc/some_file" from args if "-i" is passed into key. + + QString ret; + + int pos = args.indexOf(QRegExp(key, Qt::CaseInsensitive)); + + if (pos != -1) + { + // key found. + + if ((pos + 1) <= (args.size() - 1)) + { + // check ahead to make sure pos + 1 will not go out + // of range. + + if (!args[pos + 1].startsWith("-")) + { + // the "-" used throughout this application + // indicates an argument so the above 'if' + // statement will check to make sure it does + // not return another argument as a parameter + // in case a back-to-back "-arg -arg" is + // present. + + ret = args[pos + 1]; + } + } + } + + return ret; +} + +bool argExists(const QString &key, const QStringList &args) +{ + return args.contains(key, Qt::CaseInsensitive); +} + +bool *Shared::connectedToHost = nullptr; +QJsonObject *Shared::localData = nullptr; +QHash *Shared::clientCmds = nullptr; +QHash *Shared::hostCmds = nullptr; +QHash *Shared::genfileCmds = nullptr; +QStringList *Shared::hookBypass = nullptr; +QByteArray *Shared::sessionId = nullptr; +QString *Shared::clientHookedCmd = nullptr; +ushort *Shared::servMajor = nullptr; +ushort *Shared::servMinor = nullptr; +ushort *Shared::servPatch = nullptr; +QString *Shared::hostAddress = nullptr; +quint16 *Shared::hostPort = nullptr; +quint16 *Shared::termCmdId = nullptr; +QSslSocket *Shared::socket = nullptr; +CmdLine *Shared::cmdLine = nullptr; +Genfile *Shared::genFile = nullptr; +MainWindow *Shared::mainWin = nullptr; +Session *Shared::session = nullptr; +TextBody *Shared::textBody = nullptr; +ContextReloader *Shared::contextReloader = nullptr; +QWidget *Shared::mainWidget = nullptr; diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..cf3db63 --- /dev/null +++ b/src/common.h @@ -0,0 +1,192 @@ +#ifndef COMMON_H +#define COMMON_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cmd_objs/long_txt.h" + +#define DEFAULT_HIST_LIMIT 100 +#define DEFAULT_MAX_LINES 5000 +#define RDBUFF 128000 +#define CMD_ESCAPE '#' +#define TXT_CODEC "UTF-16LE" +#define BOOKMARK_FOLDER "bookmarks" +#define CONFIG_FILENAME "config.json" +#define APP_NAME "Cmdr" +#define APP_TARGET "cmdr" +#define APP_VERSION "1.0.0" +#define MRCI_VERSION "1.0.0" + +enum TypeID +{ + GEN_FILE = 30, + TEXT = 31, + ERR = 32, + PRIV_TEXT = 33, + IDLE = 34, + HOST_CERT = 35, + FILE_INFO = 36, + PEER_INFO = 37, + MY_INFO = 38, + PEER_STAT = 39, + P2P_REQUEST = 40, + P2P_CLOSE = 41, + P2P_OPEN = 42, + BYTES = 43, + SESSION_ID = 44, + NEW_CMD = 45, + CMD_ID = 46, + BIG_TEXT = 47 +}; + +enum ChannelMemberLevel +{ + OWNER = 1, + ADMIN = 2, + OFFICER = 3, + REGULAR = 4, + PUBLIC = 5 +}; + +enum UserIOFlags +{ + HOST_HOOK = 1, + LOCAL_HOOK = 1 << 2, + GEN_HOOK = 1 << 3, + HIDDEN = 1 << 4 +}; + +void setupTextSettings(QJsonObject *data); +void loadTextSettings(QJsonObject *data, QWidget *widget); +void saveLocalData(QJsonObject *obj); +void loadLocalData(QJsonObject *obj); +void wordWrap(const QString &label, QTextStream &txtOut, const QString &txtIn, QWidget *measureWid); +bool argExists(const QString &key, const QStringList &args); +QByteArray wrInt(quint64 num, int numOfBits); +QByteArray wrFrame(quint16 cmdId, const QByteArray &data, uchar dType); +QByteArray toTEXT(const QString &txt); +QStringList parseArgs(const QByteArray &data, int maxArgs); +QStringList parseArgs(const QString &line); +QString fromTEXT(const QByteArray &txt); +QString appDataDir(); +QString getParam(const QString &key, const QStringList &args); +QString extractCmdName(const QByteArray &data); +QString boolText(bool state); +QString verText(quint16 maj, quint16 min, quint16 patch); +quint64 rdInt(const QByteArray &bytes); + +class Command; +class CmdLine; +class Genfile; +class MainWindow; +class Session; +class TextBody; +class ContextReloader; + +class Shared : public QObject +{ + Q_OBJECT + +public: + + static bool *connectedToHost; + static QByteArray *sessionId; + static ushort *servMajor; + static ushort *servMinor; + static ushort *servPatch; + static QString *hostAddress; + static QString *clientHookedCmd; + static quint16 *hostPort; + static QStringList *hookBypass; + static QSslSocket *socket; + static QHash *clientCmds; + static QHash *hostCmds; + static QHash *genfileCmds; + static QJsonObject *localData; + static quint16 *termCmdId; + static CmdLine *cmdLine; + static Genfile *genFile; + static MainWindow *mainWin; + static Session *session; + static TextBody *textBody; + static ContextReloader *contextReloader; + static QWidget *mainWidget; + + explicit Shared(QObject *parent = nullptr); +}; + +class ContextReloader : public QObject +{ + Q_OBJECT + +public: + + explicit ContextReloader(QObject *parent = nullptr); + +public slots: + + void reloadCmdLine(); +}; + + +#endif // COMMON_H diff --git a/src/gen_file.cpp b/src/gen_file.cpp new file mode 100644 index 0000000..3d19a48 --- /dev/null +++ b/src/gen_file.cpp @@ -0,0 +1,359 @@ +#include "gen_file.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +Genfile::Genfile(QObject *parent) : QObject(parent) +{ + file = new QFile(this); + hook = 0; + + finished(); + + connect(this, &Genfile::rdFileLoop, this, &Genfile::hookedDataIn); +} + +void Genfile::finished() +{ + flags = 0; + bytesRW = 0; + hook = 0; + + localFile.clear(); + remoteFile.clear(); + len.clear(); + offs.clear(); + + if (file->isOpen()) + { + file->close(); + } + + emit enableGenFile(false); +} + +void Genfile::askOverwrite() +{ + flags |= CONFIRM_NEEDED; + + emit setUserIO(GEN_HOOK); + emit mainTxtOut("About to overwrite file: '" + localFile + "' do you want to continue? (y/n): "); +} + +bool Genfile::seekToOffset() +{ + bool ret = false; + + if (offs.isEmpty()) + { + ret = file->seek(0); + } + else + { + bool ok; + qint64 pos = offs.toLongLong(&ok, 10); + + if (!ok) + { + emit errTxtOut("err: Invalid offset was provided: " + offs + "\n"); + } + + ret = file->seek(pos); + } + + return ret; +} + +bool Genfile::lenOk() +{ + bool ret = false; + + if (len.isEmpty() && (flags & READ_MODE)) + { + len = QString::number(file->bytesAvailable()); + ret = true; + } + else if (len.isEmpty()) + { + emit errTxtOut("err: The -len parameter is empty.\n"); + } + else + { + len.toLongLong(&ret, 10); + } + + return ret; +} + +void Genfile::setupForWriting() +{ + flags |= WRITE_MODE; + + QFile::OpenMode mode = QFile::ReadWrite; + + if (flags & TRUNCATE) + { + mode |= QFile::Truncate; + } + + file->setFileName(localFile); + + if (!file->open(mode)) + { + emit errTxtOut("err: Could not open the client file for writing. reason: " + file->errorString() + "\n"); + + finished(); + } + else if (!seekToOffset()) + { + emit errTxtOut("err: Could not seek to offset postion: " + offs + " of the client file.\n"); + + finished(); + } + else if (!lenOk()) + { + emit errTxtOut("err: The -len parameter (" + len + ") is invalid.\n"); + + finished(); + } + else + { + emit hookedDataOut(QByteArray()); + } +} + +void Genfile::setupForReading() +{ + flags |= READ_MODE; + + file->setFileName(localFile); + + if (!file->open(QFile::ReadOnly)) + { + emit errTxtOut("err: Could not open the client file for reading. reason: " + file->errorString() + "\n"); + + finished(); + } + else if (!seekToOffset()) + { + emit errTxtOut("err: Could not seek to offset postion: " + offs + " of the client file.\n"); + + finished(); + } + else if (!lenOk()) + { + emit errTxtOut("err: The -len parameter (" + len + ") is invalid.\n"); + + finished(); + } +} + +bool Genfile::atEnd() +{ + return (bytesRW >= len.toLongLong()) || ((flags & READ_MODE) && file->atEnd()); +} + +bool Genfile::wrToFile(const QByteArray &data) +{ + bool ret = false; + qint64 bytes = file->write(data); + + if (bytes != -1) + { + ret = true; + bytesRW += bytes; + + if (atEnd()) + { + finished(); + } + else if (flags & SINGLE_STEP_MODE) + { + emit hookedDataOut(QByteArray()); + } + } + else + { + emit errTxtOut("err: Client write failure - " + file->errorString() + "\n"); + } + + return ret; +} + +qint64 Genfile::getRdBuff() +{ + qint64 buff = RDBUFF; + qint64 bytesAvailable = len.toLongLong() - bytesRW; + + if (buff > bytesAvailable) + { + buff = bytesAvailable; + } + + return buff; +} + +bool Genfile::rdFromFile() +{ + bool ret = false; + QByteArray data; + + data.resize(static_cast(getRdBuff())); + + if (file->read(data.data(), data.size()) != -1) + { + ret = true; + bytesRW += data.size(); + + emit hookedDataOut(data); + + if (atEnd()) + { + finished(); + } + else if (!(flags & SINGLE_STEP_MODE)) + { + emit rdFileLoop(); + } + } + else + { + emit errTxtOut("err: Client read failure - " + file->errorString() + "\n"); + } + + return ret; +} + +QByteArray Genfile::autoFill(const QByteArray &data) +{ + len = QString::number(QFileInfo(localFile).size()); + + QStringList args = parseArgs(data, -1); + int ind = args.indexOf(QRegExp("-len", Qt::CaseInsensitive)); + + if (ind != -1) + { + args.removeAt(ind); + + if ((ind + 1) < args.size()) + { + args.removeAt(ind + 1); + } + } + + args.append("-len"); + args.append(len); + + return toTEXT(args.join(' ')); +} + +void Genfile::hookedDataIn(const QByteArray &data) +{ + dataIn(hook, data); +} + +void Genfile::dataIn(quint16 cmdId, const QByteArray &data) +{ + if (!(flags & CLIENT_PARAMS_RDY)) + { + QStringList args = parseArgs(data, -1); + + hook = cmdId; + localFile = getParam("-client_file", args); + remoteFile = getParam("-remote_file", args); + len = getParam("-len", args); + offs = getParam("-offset", args); + + if (args.contains("-force", Qt::CaseInsensitive)) + { + flags |= DO_NOT_ASK; + } + + flags |= CLIENT_PARAMS_RDY; + + emit enableGenFile(true); + emit dataOut(cmdId, autoFill(data)); + } + else if (!(flags & HOST_PARAMS_RDY)) + { + QStringList args = parseArgs(data, -1); + + if (args.contains("-single_step", Qt::CaseInsensitive)) + { + flags |= SINGLE_STEP_MODE; + } + + if (args.contains("-truncate", Qt::CaseInsensitive)) + { + flags |= TRUNCATE; + } + + if (args.contains("-to_host", Qt::CaseInsensitive)) + { + setupForReading(); + + flags |= HOST_PARAMS_RDY; + } + else if (args.contains("-from_host", Qt::CaseInsensitive)) + { + if (QFile::exists(localFile) && !(flags & DO_NOT_ASK)) + { + askOverwrite(); + } + else + { + setupForWriting(); + } + + flags |= HOST_PARAMS_RDY; + } + else + { + emit errTxtOut("err: The host did not return -to_host or -from_host, making this command call ambiguous.\n"); + + finished(); + } + } + else if (flags & CONFIRM_NEEDED) + { + QString ans = fromTEXT(data); + + if (QRegExp("y", Qt::CaseInsensitive).exactMatch(ans)) + { + emit unsetUserIO(GEN_HOOK); + + flags ^= CONFIRM_NEEDED; + + setupForWriting(); + } + else if (QRegExp("n", Qt::CaseInsensitive).exactMatch(ans)) + { + finished(); + } + else + { + askOverwrite(); + } + } + else if (flags & WRITE_MODE) + { + if (!wrToFile(data)) finished(); + } + else if (flags & READ_MODE) + { + if (!rdFromFile()) finished(); + } +} diff --git a/src/gen_file.h b/src/gen_file.h new file mode 100644 index 0000000..793ebda --- /dev/null +++ b/src/gen_file.h @@ -0,0 +1,82 @@ +#ifndef GEN_FILE_H +#define GEN_FILE_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include "common.h" + +class Genfile : public QObject +{ + Q_OBJECT + +private: + + enum GenfileFlags + { + CLIENT_PARAMS_RDY = 1, + HOST_PARAMS_RDY = 1 << 1, + SINGLE_STEP_MODE = 1 << 2, + TRUNCATE = 1 << 3, + DO_NOT_ASK = 1 << 4, + CONFIRM_NEEDED = 1 << 5, + WRITE_MODE = 1 << 6, + READ_MODE = 1 << 7 + }; + + uint flags; + QFile *file; + quint16 hook; + qint64 bytesRW; + QString localFile; + QString remoteFile; + QString len; + QString offs; + + bool wrToFile(const QByteArray &data); + bool rdFromFile(); + bool seekToOffset(); + bool lenOk(); + bool atEnd(); + void askOverwrite(); + void setupForWriting(); + void setupForReading(); + QByteArray autoFill(const QByteArray &data); + qint64 getRdBuff(); + +public slots: + + void finished(); + void hookedDataIn(const QByteArray &data); + void dataIn(quint16 cmdId, const QByteArray &data); + +public: + + explicit Genfile(QObject *parent = nullptr); + +signals: + + void enableGenFile(bool state); + void mainTxtOut(const QString &txt); + void errTxtOut(const QString &txt); + void setUserIO(int flgs); + void unsetUserIO(int flgs); + void dataOut(quint16 cmdId, const QByteArray &data, uchar typeID = GEN_FILE); + void hookedDataOut(const QByteArray &data, uchar typeID = GEN_FILE); + void rdFileLoop(QByteArray data = QByteArray()); +}; + +#endif // GEN_FILE_H diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..5e44f7b --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,227 @@ +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include +#include +#include +#include +#include + +#include "cmd_objs/command.h" +#include "cmd_objs/status.h" +#include "cmd_objs/bookmarks.h" +#include "cmd_objs/info.h" +#include "cmd_objs/exec.h" +#include "cmd_objs/style.h" +#include "main_ui.h" +#include "session.h" +#include "gen_file.h" +#include "text_body.h" +#include "cmd_line.h" + +void setupClientCmds(); +void setupCmdLine(); +void setupGenFile(); +void setupSession(); + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + app.setApplicationName(APP_NAME); + app.setApplicationVersion(APP_VERSION); + + bool connected = false; + ushort servMajor = 0; + ushort servMinor = 0; + ushort servPatch = 0; + quint16 hostPort = 0; + quint16 termCmdId = 0; + QByteArray sessionId; + QString clientHookCmd; + QString hostAddress; + QStringList hookBypass; + QHash genfileCmds; + QHash clientCmds; + QHash hostCmds; + QJsonObject localData; + + loadLocalData(&localData); + setupTextSettings(&localData); + + Shared::connectedToHost = &connected; + Shared::genfileCmds = &genfileCmds; + Shared::clientCmds = &clientCmds; + Shared::hostCmds = &hostCmds; + Shared::sessionId = &sessionId; + Shared::servMajor = &servMajor; + Shared::servMinor = &servMinor; + Shared::servPatch = &servPatch; + Shared::hostAddress = &hostAddress; + Shared::hostPort = &hostPort; + Shared::hookBypass = &hookBypass; + Shared::termCmdId = &termCmdId; + Shared::localData = &localData; + Shared::clientHookedCmd = &clientHookCmd; + Shared::contextReloader = new ContextReloader(&app); + Shared::session = new Session(&app); + Shared::mainWin = new MainWindow(); + Shared::textBody = new TextBody(Shared::mainWin); + Shared::cmdLine = new CmdLine(Shared::mainWin); + Shared::genFile = new Genfile(&app); + Shared::socket = Shared::session; + Shared::mainWidget = Shared::mainWin; + + new SaveBookmark(&app); + new ListBookmarks(&app); + new DeleteBookmark(&app); + new SeeBookmark(&app); + new Status(&app); + new Connect(&app); + new Quit(&app); + new About(&app); + new EndSession(&app); + new Term(&app); + new SetColors(&app); + new SetFont(&app); + new SetMaxLines(&app); + new Genfile(&app); + + setupClientCmds(); + setupCmdLine(); + setupGenFile(); + setupSession(); + + Shared::mainWin->setTextBody(Shared::textBody); + Shared::mainWin->setCmdLine(Shared::cmdLine); + Shared::mainWin->showUi(); + + return app.exec(); +} + +ContextReloader::ContextReloader(QObject *parent) : QObject(parent) {} + +void ContextReloader::reloadCmdLine() +{ + Shared::cmdLine->close(); + + Shared::cmdLine = new CmdLine(Shared::mainWin); + + Shared::mainWin->setCmdLine(Shared::cmdLine); + + for (auto command : Shared::clientCmds->values()) + { + QObject::connect(Shared::cmdLine, &CmdLine::dataToCommandObj, command, &Command::cmdCall); + QObject::connect(Shared::cmdLine, &CmdLine::dataToHookedCmdObj, command, &Command::hookedCmdCall); + } + + setupCmdLine(); +} + +void setupClientCmds() +{ + Session *session = Shared::session; + CmdLine *cmdLine = Shared::cmdLine; + TextBody *textBody = Shared::textBody; + Genfile *genFile = Shared::genFile; + MainWindow *mainWin = Shared::mainWin; + ContextReloader *reloader = Shared::contextReloader; + + for (auto command : Shared::clientCmds->values()) + { + QObject::connect(command, &Command::mainTxtOut, textBody, &TextBody::addMainTxt); + QObject::connect(command, &Command::errTxtOut, textBody, &TextBody::addErrTxt); + QObject::connect(command, &Command::bigTxtOut, textBody, &TextBody::addBigTxt); + + QObject::connect(cmdLine, &CmdLine::dataToCommandObj, command, &Command::cmdCall); + QObject::connect(cmdLine, &CmdLine::dataToHookedCmdObj, command, &Command::hookedCmdCall); + + QObject::connect(command, &Command::setUserIO, cmdLine, &CmdLine::setFlags); + QObject::connect(command, &Command::unsetUserIO, cmdLine, &CmdLine::unsetFlags); + + QObject::connect(command, &Command::termHostCmd, session, &Session::termHostCmd); + QObject::connect(command, &Command::connectToHost, session, &Session::connectToServ); + QObject::connect(command, &Command::quitApp, session, &Session::disconnectFromServ); + QObject::connect(command, &Command::disconnectHost, session, &Session::disconnectFromServ); + + QObject::connect(command, &Command::quitApp, QCoreApplication::instance(), &QCoreApplication::quit); + + QObject::connect(command, &Command::termHostCmd, genFile, &Genfile::finished); + QObject::connect(command, &Command::quitApp, genFile, &Genfile::finished); + + QObject::connect(command, &Command::colorsChanged, textBody, &TextBody::reload); + QObject::connect(command, &Command::fontChanged, textBody, &TextBody::reload); + QObject::connect(command, &Command::setMaxLines, textBody, &TextBody::setMaxLines); + + QObject::connect(command, &Command::colorsChanged, reloader, &ContextReloader::reloadCmdLine); + QObject::connect(command, &Command::fontChanged, reloader, &ContextReloader::reloadCmdLine); + + QObject::connect(mainWin, &MainWindow::startup, command, &Command::onStartup); + } +} + +void setupCmdLine() +{ + Session *session = Shared::session; + CmdLine *cmdLine = Shared::cmdLine; + TextBody *textBody = Shared::textBody; + Genfile *genFile = Shared::genFile; + + QObject::connect(cmdLine, &CmdLine::dataToHost, session, &Session::binToServer); + QObject::connect(cmdLine, &CmdLine::dataToHookedHost, session, &Session::hookedBinToServer); + + QObject::connect(cmdLine, &CmdLine::mainTxtOut, textBody, &TextBody::addMainTxt); + QObject::connect(cmdLine, &CmdLine::errTxtOut, textBody, &TextBody::addErrTxt); + + QObject::connect(cmdLine, &CmdLine::dataToGenFile, genFile, &Genfile::dataIn); + QObject::connect(cmdLine, &CmdLine::dataToHookedGenFile, genFile, &Genfile::hookedDataIn); +} + +void setupGenFile() +{ + Session *session = Shared::session; + CmdLine *cmdLine = Shared::cmdLine; + TextBody *textBody = Shared::textBody; + Genfile *genFile = Shared::genFile; + + QObject::connect(genFile, &Genfile::dataOut, session, &Session::binToServer); + QObject::connect(genFile, &Genfile::hookedDataOut, session, &Session::hookedBinToServer); + QObject::connect(genFile, &Genfile::enableGenFile, session, &Session::enableGenFile); + + QObject::connect(genFile, &Genfile::setUserIO, cmdLine, &CmdLine::setFlags); + QObject::connect(genFile, &Genfile::unsetUserIO, cmdLine, &CmdLine::unsetFlags); + + QObject::connect(genFile, &Genfile::mainTxtOut, textBody, &TextBody::addMainTxt); + QObject::connect(genFile, &Genfile::errTxtOut, textBody, &TextBody::addErrTxt); +} + +void setupSession() +{ + Session *session = Shared::session; + CmdLine *cmdLine = Shared::cmdLine; + TextBody *textBody = Shared::textBody; + Genfile *genFile = Shared::genFile; + + QObject::connect(session, &Session::hostFinished, genFile, &Genfile::finished); + QObject::connect(session, &Session::toGenFile, genFile, &Genfile::hookedDataIn); + + QObject::connect(session, &Session::setUserIO, cmdLine, &CmdLine::setFlags); + QObject::connect(session, &Session::unsetUserIO, cmdLine, &CmdLine::unsetFlags); + + QObject::connect(session, &Session::bigTxtOut, textBody, &TextBody::addBigTxt); + QObject::connect(session, &Session::mainTxtOut, textBody, &TextBody::addMainTxt); + QObject::connect(session, &Session::errTxtOut, textBody, &TextBody::addErrTxt); +} diff --git a/src/main_ui.cpp b/src/main_ui.cpp new file mode 100644 index 0000000..2972963 --- /dev/null +++ b/src/main_ui.cpp @@ -0,0 +1,95 @@ +#include "main_ui.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) +{ + QWidget *mainWidget = new QWidget(this); + + mainLayout = new QVBoxLayout(mainWidget); + localData = Shared::localData; + + QSize winSize; + + if (localData->contains("window_size")) + { + QJsonValue value = localData->value("window_size"); + + if (value.isArray()) + { + QJsonArray array = value.toArray(); + + if (array.count() == 2) + { + winSize.setHeight(array[0].toInt()); + winSize.setWidth(array[1].toInt()); + } + } + } + else + { + QScreen *screen = QGuiApplication::screens()[0]; + + winSize.setHeight(screen->availableSize().height() / 2); + winSize.setWidth(screen->availableSize().width() / 2); + } + + mainLayout->setSpacing(0); + mainLayout->setContentsMargins(0, 0, 0, 0); + + resize(winSize); + setCentralWidget(mainWidget); + setContentsMargins(0, 0, 0, 0); +} + +void MainWindow::saveWindowSize() +{ + QJsonArray array; + + array.append(height()); + array.append(width()); + + localData->insert("window_size", array); + + saveLocalData(localData); +} + +void MainWindow::resizeEvent(QResizeEvent *event) +{ + saveWindowSize(); + + QMainWindow::resizeEvent(event); +} + +void MainWindow::setCmdLine(QWidget *widget) +{ + widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + mainLayout->insertWidget(1, widget); +} + +void MainWindow::setTextBody(QWidget *widget) +{ + widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + mainLayout->insertWidget(0, widget); +} + +void MainWindow::showUi() +{ + show(); + + emit startup(); +} diff --git a/src/main_ui.h b/src/main_ui.h new file mode 100644 index 0000000..e869f45 --- /dev/null +++ b/src/main_ui.h @@ -0,0 +1,47 @@ +#ifndef USER_IO_H +#define USER_IO_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include "common.h" + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +private: + + QJsonObject *localData; + QVBoxLayout *mainLayout; + + void resizeEvent(QResizeEvent *event); + void saveWindowSize(); + +public: + + explicit MainWindow(QWidget *parent = nullptr); + + void setCmdLine(QWidget *widget); + void setTextBody(QWidget *widget); + void showUi(); + +signals: + + void startup(); +}; + +#endif // USER_IO_H diff --git a/src/session.cpp b/src/session.cpp new file mode 100644 index 0000000..23110be --- /dev/null +++ b/src/session.cpp @@ -0,0 +1,424 @@ +#include "session.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +Session::Session(QObject *parent) : QSslSocket(parent) +{ + dSize = 0; + hook = 0; + dType = 0; + flags = 0; + reconnect = false; + + connect(this, SIGNAL(encrypted()), this, SLOT(handShakeDone())); + connect(this, SIGNAL(connected()), this, SLOT(isConnected())); + connect(this, SIGNAL(disconnected()), this, SLOT(isDisconnected())); + connect(this, SIGNAL(readyRead()), this, SLOT(dataIn())); + connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(sockerr(QAbstractSocket::SocketError))); +} + +void Session::hookedBinToServer(const QByteArray &data, uchar typeId) +{ + if (*Shared::connectedToHost) + { + write(wrFrame(hook, data, typeId)); + } + else + { + emit errTxtOut("err: not connected to a host.\n"); + } +} + +void Session::binToServer(quint16 cmdId, const QByteArray &data, uchar typeId) +{ + if (*Shared::connectedToHost) + { + hook = cmdId; + + emit setUserIO(HOST_HOOK); + + write(wrFrame(cmdId, data, typeId)); + } + else + { + emit errTxtOut("err: not connected to a host.\n"); + } +} + +void Session::sockerr(QAbstractSocket::SocketError err) +{ + if (err == QAbstractSocket::RemoteHostClosedError) + { + emit mainTxtOut("\nThe remote host closed the session.\n"); + } + else + { + emit errTxtOut("\nerr: " + errorString() + "\n"); + + if (state() == QAbstractSocket::UnconnectedState) + { + hook = 0; + } + } +} + +void Session::isConnected() +{ + // client header format: [4bytes(tag)][2bytes(major)][2bytes(minor)][2bytes(patch)][128bytes(appName)][272bytes(coName)] + + // tag = 0x4D, 0x52, 0x43, 0x49 (MRCI) + // major = 16bit little endian int + // minor = 16bit little endian int + // patch = 16bit little endian int + // appName = UTF16LE string + // coName = UTF16LE string + + emit mainTxtOut("Connected.\n"); + + QByteArray header; + QStringList ver = QString(MRCI_VERSION).split('.'); + + header.append(SERVER_HEADER_TAG); + header.append(wrInt(ver[0].toULongLong(), 16)); + header.append(wrInt(ver[1].toULongLong(), 16)); + header.append(wrInt(ver[2].toULongLong(), 16)); + header.append(toTEXT(QString(QString(APP_NAME) + " v" + QString(APP_VERSION)).leftJustified(64, ' ', true))); + header.append(toTEXT(Shared::hostAddress->leftJustified(136, ' ', true))); + + if (header.size() == CLIENT_HEADER_LEN) + { + write(header); + } + else + { + emit errTxtOut("\nerr: client bug! - header len not equal to " + QString::number(CLIENT_HEADER_LEN) + "\n"); + + disconnectFromHost(); + } +} + +void Session::handShakeDone() +{ + QSslCipher cipher = sessionCipher(); + QString txt; + + QTextStream txtOut(&txt); + + txtOut << "SSL Handshake sucessful." << endl + << "cipher details:" << endl + << " #cipher - " << cipher.name() << endl + << " #protocol - " << cipher.protocolString() << endl + << " #bit_depth - " << cipher.usedBits() << endl + << " #key_exchange - " << cipher.keyExchangeMethod() << endl + << " #authentication - " << cipher.authenticationMethod() << endl; + + emit mainTxtOut(txt); +} + +void Session::isDisconnected() +{ + dSize = 0; + hook = 0; + dType = 0; + flags = 0; + + *Shared::servMajor = 0; + *Shared::servMinor = 0; + *Shared::servPatch = 0; + *Shared::connectedToHost = false; + + Shared::sessionId->clear(); + Shared::hostCmds->clear(); + Shared::genfileCmds->clear(); + + emit mainTxtOut("\nHost session ended. (disconnected)\n\n"); + + if (reconnect) + { + reconnect = false; + + connectToServ(); + } +} + +void Session::connectToServ() +{ + if (state() == QAbstractSocket::ConnectedState) + { + reconnect = true; + + disconnectFromServ(); + } + else + { + emit mainTxtOut("Connecting to address: " + *Shared::hostAddress + " port: " + QString::number(*Shared::hostPort) + "\n"); + + connectToHost(*Shared::hostAddress, *Shared::hostPort); + } +} + +void Session::disconnectFromServ() +{ + *Shared::connectedToHost = false; + + if (state() == QAbstractSocket::ConnectedState) + { + emit mainTxtOut("Disconnecting.\n"); + + disconnectFromHost(); + } + + close(); +} + +void Session::termHostCmd() +{ + if (hook != 0) + { + binToServer(*Shared::termCmdId, wrInt(hook, 16), CMD_ID); + } +} + +void Session::enableGenFile(bool state) +{ + if (state) + { + flags |= GEN_FILE_ON; + } + else + { + flags &= ~GEN_FILE_ON; + } +} + +void Session::dataFromHost(const QByteArray &data) +{ + if (cmdId == ASYNC_SYS_MSG) + { + if (dType == HOST_CERT) + { + QSslCertificate cert(data, QSsl::Pem); + QSslError selfSigned(QSslError::SelfSignedCertificate, cert); + + emit mainTxtOut("SSL cert received.\n\n"); + + if (cert.isSelfSigned()) + { + emit mainTxtOut("WARNING: the cert is self signed. be careful if in a public network.\n\n"); + } + + ignoreSslErrors(QList() << selfSigned); + addCaCertificate(cert); + startClientEncryption(); + } + else if (dType == TEXT) + { + emit mainTxtOut(fromTEXT(data)); + } + else if (dType == BIG_TEXT) + { + emit bigTxtOut(fromTEXT(data)); + } + else if (dType == ERR) + { + emit errTxtOut(fromTEXT(data)); + } + } + else if (cmdId == ASYNC_ADD_CMD) + { + if ((dType == NEW_CMD) && (data.size() >= 131)) + { + quint16 id = static_cast(rdInt(data.mid(0, 2))); + QString cmdName = fromTEXT(data.mid(3, 128)).trimmed(); + + if (cmdName.toLower() == "term") + { + *Shared::termCmdId = id; + } + + if (!Shared::hostCmds->contains(id)) + { + Shared::hostCmds->insert(id, cmdName); + + if (data[2]) + { + Shared::genfileCmds->insert(id, cmdName); + } + } + } + } + else if (cmdId == ASYNC_RM_CMD) + { + if ((dType == CMD_ID) && (data.size() == 2)) + { + quint16 id = static_cast(rdInt(data.mid(0, 2))); + + if (id == hook) hook = 0; + + if (Shared::hostCmds->contains(id)) + { + Shared::genfileCmds->remove(id); + Shared::hostCmds->remove(id); + } + } + } + else if ((cmdId == ASYNC_RDY) || (cmdId == ASYNC_EXE_CRASH)) + { + hook = 0; + + if (dType == TEXT) + { + emit mainTxtOut(fromTEXT(data)); + } + else if (dType == ERR) + { + emit errTxtOut(fromTEXT(data)); + } + } + else if ((cmdId == hook) && (hook != 0)) + { + if ((dType == TEXT) || (dType == PRIV_TEXT)) + { + emit mainTxtOut(fromTEXT(data)); + + if (dType == PRIV_TEXT) + { + emit setUserIO(HIDDEN); + } + } + else if (dType == BIG_TEXT) + { + emit bigTxtOut(fromTEXT(data)); + } + else if (dType == ERR) + { + emit errTxtOut(fromTEXT(data)); + } + else if (dType == IDLE) + { + hook = 0; + + emit hostFinished(); + emit unsetUserIO(HOST_HOOK); + + if (Shared::hostCmds->contains(cmdId)) + { + emit mainTxtOut("\nFinished: " + Shared::hostCmds->value(cmdId) + "\n\n"); + } + else + { + emit mainTxtOut("\nFinished: Unknown\n\n"); + } + } + else if ((dType == GEN_FILE) && (flags & GEN_FILE_ON)) + { + emit toGenFile(data); + } + } +} + +void Session::dataIn() +{ + if (flags & DSIZE_RDY) + { + if (bytesAvailable() >= dSize) + { + flags ^= DSIZE_RDY; + + dataFromHost(read(dSize)); + dataIn(); + } + } + else if (flags & VER_OK) + { + if (bytesAvailable() >= FRAME_HEADER_LEN) + { + QByteArray header = read(FRAME_HEADER_LEN); + + dType = static_cast(header[0]); + cmdId = static_cast(rdInt(header.mid(1, 2))); + dSize = static_cast(rdInt(header.mid(3, 3))); + flags |= DSIZE_RDY; + + dataIn(); + } + } + else if (bytesAvailable() >= SERVER_HEADER_LEN) + { + // host header format: [1byte(reply)][2bytes(major)][2bytes(minor)][2bytes(patch)][28bytes(sesId)] + + // reply is an 8bit little endian int the indicates the result of the client header + // sent to the host from the isConnected() function. + + // sesId = 224bit sha3 hash + // major = 16bit little endian uint (host ver major) + // minor = 16bit little endian uint (host ver minor) + // patch = 16bit little endian uint (host ver patch) + + uchar reply = static_cast(rdInt(read(1))); + + if ((reply == 1) || (reply == 2)) + { + *Shared::servMajor = static_cast(rdInt(read(2))); + *Shared::servMinor = static_cast(rdInt(read(2))); + *Shared::servPatch = static_cast(rdInt(read(2))); + + emit mainTxtOut("Detected host version: " + verText(*Shared::servMajor, *Shared::servMinor, *Shared::servPatch) + "\n"); + + if (*Shared::servMajor == 1) + { + *Shared::sessionId = read(28); + *Shared::connectedToHost = true; + + flags |= VER_OK; + + emit mainTxtOut("Host assigned session id: " + Shared::sessionId->toHex() + "\n"); + + if (reply == 2) + { + emit mainTxtOut("Awaiting SSL cert from the host.\n"); + } + else + { + emit mainTxtOut("The host claims SSL is not needed. the connection will not be encrypted.\n"); + } + } + else + { + emit errTxtOut("err: Host not compatible.\n"); + + disconnectFromHost(); + } + } + else if (reply == 3) + { + emit errTxtOut("err: Client version rejected by the host.\n"); + } + else if (reply == 4) + { + emit errTxtOut("err: The host was unable to find a SSL cert for common name: " + *Shared::hostAddress + ".\n"); + } + else + { + emit errTxtOut("err: Invalid reply id from the host: " + QString::number(reply) + ".\n"); + } + + if ((reply != 1) && (reply != 2)) disconnectFromHost(); + + dataIn(); + } +} diff --git a/src/session.h b/src/session.h new file mode 100644 index 0000000..3a3339f --- /dev/null +++ b/src/session.h @@ -0,0 +1,124 @@ +#ifndef SOCKET_H +#define SOCKET_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cmd_objs/command.h" +#include "cmd_objs/bookmarks.h" + +#define SERVER_HEADER_TAG "MRCI" +#define CLIENT_HEADER_LEN 410 +#define SERVER_HEADER_LEN 35 +#define FRAME_HEADER_LEN 6 + +#define ASYNC_RDY 1 +#define ASYNC_SYS_MSG 2 +#define ASYNC_EXE_CRASH 3 +#define ASYNC_TO_PEER 21 +#define ASYNC_LIMITED_CAST 22 +#define ASYNC_P2P 24 +#define ASYNC_NEW_CH_MEMBER 26 +#define ASYNC_DEL_CH 27 +#define ASYNC_RENAME_CH 28 +#define ASYNC_CH_ACT_FLAG 29 +#define ASYNC_NEW_SUB_CH 30 +#define ASYNC_RM_SUB_CH 31 +#define ASYNC_RENAME_SUB_CH 32 +#define ASYNC_INVITED_TO_CH 33 +#define ASYNC_RM_CH_MEMBER 34 +#define ASYNC_INVITE_ACCEPTED 35 +#define ASYNC_MEM_LEVEL_CHANGED 36 +#define ASYNC_SUB_CH_LEVEL_CHG 37 +#define ASYNC_ADD_RDONLY 38 +#define ASYNC_RM_RDONLY 39 +#define ASYNC_ADD_CMD 40 +#define ASYNC_RM_CMD 41 +#define ASYNC_USER_RENAMED 42 + +class Session : public QSslSocket +{ + Q_OBJECT + +private: + + uint flags; + uint dSize; + quint16 cmdId; + quint16 hook; + uchar dType; + bool reconnect; + + void dataFromHost(const QByteArray &data); + +private slots: + + void dataIn(); + void isConnected(); + void isDisconnected(); + void handShakeDone(); + void sockerr(QAbstractSocket::SocketError err); + +public: + + enum SessionFlags : uint + { + VER_OK = 1, + DSIZE_RDY = 1 << 2, + GEN_FILE_ON = 1 << 3 + }; + + explicit Session(QObject *parent = nullptr); + +public slots: + + void hookedBinToServer(const QByteArray &data, uchar typeId); + void binToServer(quint16 cmdId, const QByteArray &data, uchar typeId); + void enableGenFile(bool state); + void termHostCmd(); + void connectToServ(); + void disconnectFromServ(); + +signals: + + void hostFinished(); + void setUserIO(int flgs); + void unsetUserIO(int flgs); + void toGenFile(const QByteArray &data); + void mainTxtOut(const QString &txt); + void errTxtOut(const QString &txt); + void bigTxtOut(const QString &txt); +}; + +#endif // SOCKET_H diff --git a/src/text_body.cpp b/src/text_body.cpp new file mode 100644 index 0000000..e1802c6 --- /dev/null +++ b/src/text_body.cpp @@ -0,0 +1,159 @@ +#include "text_body.h" + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +TextBody::TextBody(QWidget *parent) : QTextEdit(parent) +{ + localData = Shared::localData; + reloading = false; + lineCount = 0; + + txtDocument = new QTextDocument(this); + txtCursor = new QTextCursor(txtDocument); + + setDocument(txtDocument); + setReadOnly(true); + setWordWrapMode(QTextOption::NoWrap); + loadTextSettings(localData, this); + loadTextBodySettings(); + + txtDocument->setMaximumBlockCount(maxLines); +} + +void TextBody::loadTextBodySettings() +{ + mainColor = localData->value("text_settings").toObject().value("text_color").toString(); + errColor = localData->value("text_settings").toObject().value("err_color").toString(); + maxLines = localData->value("max_lines").toInt(); +} + +QString TextBody::htmlEsc(const QString &txt) +{ + QString ret = txt; + + ret.replace(">", ">"); + ret.replace("<", "<"); + + return ret; +} + +void TextBody::addTextBlock(const QString &txt, const QString &color, TextType tType) +{ + QStringList lines = htmlEsc(txt).split("\n"); + + lineCount += lines.size(); + + for (int i = 0; i < lines.size(); ++i) + { + txtCursor->insertHtml("
" + lines[i] + "
"); + + if (i == lines.size() - 1) + { + if (!reloading) textCache.append(QPair(tType, lines[i])); + } + else + { + if (!reloading) textCache.append(QPair(tType, lines[i] + "\n")); + + txtCursor->insertBlock(); + } + + ensureCursorVisible(); + } +} + +void TextBody::setMaxLines(int value) +{ + txtDocument->setMaximumBlockCount(value); + + trimCache(); +} + +void TextBody::trimCache() +{ + for (;lineCount > maxLines; --lineCount) + { + textCache.removeFirst(); + } +} + +void TextBody::addMainTxt(const QString &txt) +{ + moveCursor(QTextCursor::End); + addTextBlock(txt, mainColor, MAIN); + trimCache(); +} + +void TextBody::addErrTxt(const QString &txt) +{ + moveCursor(QTextCursor::End); + addTextBlock(txt, errColor, ERROR); + trimCache(); +} + +void TextBody::addBigTxt(const QString &txt) +{ + QString lines; + QTextStream txtOut(&lines); + + wordWrap("", txtOut, txt, Shared::mainWidget); + + addMainTxt(lines); +} + +void TextBody::clearCache() +{ + lineCount = 0; + + textCache.clear(); +} + +void TextBody::reload() +{ + clear(); + + loadTextSettings(localData, this); + saveLocalData(localData); + loadTextBodySettings(); + + reloading = true; + + for (int i = 0; i < textCache.size(); ++i) + { + if (textCache[i].first == ERROR) + { + addErrTxt(textCache[i].second); + } + else + { + addMainTxt(textCache[i].second); + } + } + + reloading = false; +} + +void TextBody::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu *menu = createStandardContextMenu(); + QAction *action = menu->addAction("Clear", this, SLOT(clear())); + + connect(action, SIGNAL(triggered()), this, SLOT(clearCache())); + + menu->exec(event->globalPos()); + menu->deleteLater(); +} diff --git a/src/text_body.h b/src/text_body.h new file mode 100644 index 0000000..76e47fa --- /dev/null +++ b/src/text_body.h @@ -0,0 +1,67 @@ +#ifndef TEXT_BODY_H +#define TEXT_BODY_H + +// This file is part of Cmdr. + +// Cmdr is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Cmdr is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Cmdr under the LICENSE.md file. If not, see +// . + +#include "common.h" + +class TextBody : public QTextEdit +{ + Q_OBJECT + +private: + + enum TextType + { + ERROR, + MAIN + }; + + QList > textCache; + QTextDocument *txtDocument; + QTextCursor *txtCursor; + QJsonObject *localData; + QString errColor; + QString mainColor; + bool reloading; + int maxLines; + int lineCount; + + QString htmlEsc(const QString &txt); + void trimCache(); + void loadTextBodySettings(); + void contextMenuEvent(QContextMenuEvent *event); + void addTextBlock(const QString &txt, const QString &color, TextType tType); + +private slots: + + void clearCache(); + +public: + + explicit TextBody(QWidget *parent = nullptr); + +public slots: + + void addMainTxt(const QString &txt); + void addErrTxt(const QString &txt); + void addBigTxt(const QString &txt); + void setMaxLines(int value); + void reload(); +}; + +#endif // TEXT_BODY_H