Monday, June 17, 2019

How to change Windows 10 login screen inactivity timeout?


We are developing some MFA (multi-factor authentication) support on Windows. After entering the user password it will have other challenge like email/phone calls.
But on Windows 10 we found that the login screen (not remote) will close after 30s of inactivity. In some cases the email/phone challenge may take more than 30s, and logon screen being closed will stop the email/phone wait.
Is there any way, like registry, to change the Windows 10 logon timeout value?

The registry controlling the login screen timeout is
Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI
DWORD Value: IdleTimeOut
Unit: msec

Because the registry key wasn't here and adding it didn't work.

My windows versions (for info):

(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\WindowsNT\CurrentVersion").ReleaseId
#1803
Get-WmiObject win32_operatingsystem | Select-Object caption, version
#caption                  version
#-------                  -------
#Microsoft Windows 10 Pro 10.0.17134
1. Get Your Scheme or use 'SCHEME_CURRENT' alias
Check your current power scheme:

powercfg.exe /LIST
#Existing Power Schemes (* Active)
#-----------------------------------
#Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced) *
#Power Scheme GUID: 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c  (High performance)
#Power Scheme GUID: a1841308-3541-4fab-bc81-f71556f20b4a  (Power saver)
Get your current scheme alias:

(powercfg.exe /QUERY ((powercfg.exe /GETACTIVESCHEME) -replace '.* ([0-9a-f-]{36}) .*', '$1'))|Select-String -Pattern "^  GUID Alias"
#GUID Alias: SCHEME_BALANCED
2. Set lock timeout AC or DC
Use /SETACVALUEINDEX when you are not on battery

Use /SETDCVALUEINDEX when on battery

The value is in seconds, so here 1200s = 60s * 20 i.e. 20minutes

powercfg.exe /SETACVALUEINDEX SCHEME_CURRENT SUB_VIDEO VIDEOCONLOCK 1200






Wednesday, June 12, 2019

Build google protocol-buffer with NDK r19c

I was build google protocol buffer 3.30 with NDK r16 

It call the ./configure  pass in standalone toolchain as parameter, it works.

2 years later, the NDK upgrade to r19c
google protocol buffer upgrade to 3.8.0

When call ./configure same as previous version, report an error :

checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features by default... no
checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features with -std=c++11... no
checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features with +std=c++11... no
checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features with -h std=c++11... no
checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features with -std=c++0x... no
checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features with +std=c++0x... no
checking whether #ndk/toolchains/android/arm-linux-androideabi/bin/arm-linux-androideabi-clang++ supports C++11 features with -h std=c++0x... no
configure: error: *** A compiler with support for C++11 language features is required.  

Finally, found solution: call cmake instead of ./autogen , ./configure

cd cmake
cmake \
-Dprotobuf_BUILD_SHARED_LIBS=OFF \
-Dprotobuf_BUILD_STATIC_LIBS=ON \
-DCMAKE_VERBOSE_MAKEFILE=ON \
-Dprotobuf_BUILD_TESTS=OFF \
-Dprotobuf_BUILD_EXAMPLES=OFF \
-Dprotobuf_BUILD_PROTOC_BINARIES=OFF \
-DCMAKE_TOOLCHAIN_FILE=$CMAKE_TOOLCHAIN \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=$INSTALL_PATH \
-DANDROID_NDK=$ANDROID_NDK_ROOT \
-DANDROID_TOOLCHAIN=clang \
-DANDROID_ABI=$androidabi \
-DANDROID_NATIVE_API_LEVEL=26 \
-DANDROID_STL=c++_shared \
-DANDROID_LINKER_FLAGS="-landroid -llog" \
-DANDROID_CPP_FEATURES="rtti exceptions" \
.
cmake --build .
make install

Friday, May 10, 2019

Docker overview

Docker Engine is a client-server application with these major components:
  • A server which is a type of long-running program called a daemon process (the dockerd command).The Docker daemon (dockerd) listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services.
  • A REST API which specifies interfaces that programs can use to talk to the daemon and instruct it what to do.
  • A command line interface (CLI) client (the docker command).The Docker client (docker) is the primary way that many Docker users interact with Docker. When you use commands such as docker run, the client sends these commands to dockerd, which carries them out. The docker command uses the Docker API. The Docker client can communicate with more than one daemon.

The CLI uses the Docker REST API to control or interact with the Docker daemon through scripting or direct CLI commands. Many other Docker applications use the underlying API and CLI.The daemon creates and manages Docker objects, such as images, containers, networks, and volumes.

Docker registries

A Docker registry stores Docker images. Docker Hub is a public registry that anyone can use, and Docker is configured to look for images on Docker Hub by default. You can even run your own private registry. If you use Docker Datacenter (DDC), it includes Docker Trusted Registry (DTR).
When you use the docker pull or docker run commands, the required images are pulled from your configured registry. When you use the docker push command, your image is pushed to your configured registry.

Docker objects

When you use Docker, you are creating and using images, containers, networks, volumes, plugins, and other objects. This section is a brief overview of some of those objects.

IMAGES

An image is a read-only template with instructions for creating a Docker container. Often, an image is based on another image, with some additional customization. For example, you may build an image which is based on the ubuntu image, but installs the Apache web server and your application, as well as the configuration details needed to make your application run.
You might create your own images or you might only use those created by others and published in a registry. To build your own image, you create a Dockerfile with a simple syntax for defining the steps needed to create the image and run it. Each instruction in a Dockerfile creates a layer in the image. When you change the Dockerfile and rebuild the image, only those layers which have changed are rebuilt. This is part of what makes images so lightweight, small, and fast, when compared to other virtualization technologies.

CONTAINERS

A container is a runnable instance of an image. You can create, start, stop, move, or delete a container using the Docker API or CLI. You can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state.
By default, a container is relatively well isolated from other containers and its host machine. You can control how isolated a container’s network, storage, or other underlying subsystems are from other containers or from the host machine.
A container is defined by its image as well as any configuration options you provide to it when you create or start it. When a container is removed, any changes to its state that are not stored in persistent storage disappear.

SERVICES

Services allow you to scale containers across multiple Docker daemons, which all work together as a swarm with multiple managersand workers. Each member of a swarm is a Docker daemon, and the daemons all communicate using the Docker API. A service allows you to define the desired state, such as the number of replicas of the service that must be available at any given time. By default, the service is load-balanced across all worker nodes. To the consumer, the Docker service appears to be a single application. Docker Engine supports swarm mode in Docker 1.12 and higher.

## List Docker CLI commands
docker
docker container --help

## Display Docker version and info
docker --version
docker version
docker info

## Execute Docker image
docker run hello-world

## List Docker images
docker image ls

## List Docker containers (running, all, all in quiet mode)
docker container ls
docker container ls --all
docker container ls -aq
docker build -t friendlyhello .  # Create image using this directory's Dockerfile
docker run -p 4000:80 friendlyhello  # Run "friendlyhello" mapping port 4000 to 80
docker run -d -p 4000:80 friendlyhello         # Same thing, but in detached mode
docker container ls                                # List all running containers
docker container ls -a             # List all containers, even those not running
docker container stop <hash>           # Gracefully stop the specified container
docker container kill <hash>         # Force shutdown of the specified container
docker container rm <hash>        # Remove specified container from this machine
docker container rm $(docker container ls -a -q)         # Remove all containers
docker image ls -a                             # List all images on this machine
docker image rm <image id>            # Remove specified image from this machine
docker image rm $(docker image ls -a -q)   # Remove all images from this machine
docker login             # Log in this CLI session using your Docker credentials
docker tag <image> username/repository:tag  # Tag <image> for upload to registry
docker push username/repository:tag            # Upload tagged image to registry
docker run username/repository:tag                   # Run image from a registry
docker stack ls                                            # List stacks or apps
docker stack deploy -c <composefile> <appname>  # Run the specified Compose file
docker service ls                 # List running services associated with an app
docker service ps <service>                  # List tasks associated with an app
docker inspect <task or container>                   # Inspect task or container
docker container ls -q                                      # List container IDs
docker stack rm <appname>                             # Tear down an application
docker swarm leave --force      # Take down a single node swarm from the managerdocker-machine create --driver virtualbox myvm1 # Create a VM (Mac, Win7, Linux)
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 # Win10
docker-machine env myvm1                # View basic information about your node
docker-machine ssh myvm1 "docker node ls"         # List the nodes in your swarm
docker-machine ssh myvm1 "docker node inspect <node ID>"        # Inspect a node
docker-machine ssh myvm1 "docker swarm join-token -q worker"   # View join token
docker-machine ssh myvm1   # Open an SSH session with the VM; type "exit" to end
docker node ls                # View nodes in swarm (while logged on to manager)
docker-machine ssh myvm2 "docker swarm leave"  # Make the worker leave the swarm
docker-machine ssh myvm1 "docker swarm leave -f" # Make master leave, kill swarm
docker-machine ls # list VMs, asterisk shows which VM this shell is talking to
docker-machine start myvm1            # Start a VM that is currently not running
docker-machine env myvm1      # show environment variables and command for myvm1
eval $(docker-machine env myvm1)         # Mac command to connect shell to myvm1
& "C:\Program Files\Docker\Docker\Resources\bin\docker-machine.exe" env myvm1 | Invoke-Expression   # Windows command to connect shell to myvm1
docker stack deploy -c <file> <app>  # Deploy an app; command shell must be set to talk to manager (myvm1), uses local Compose file
docker-machine scp docker-compose.yml myvm1:~ # Copy file to node's home dir (only required if you use ssh to connect to manager and deploy the app)
docker-machine ssh myvm1 "docker stack deploy -c <file> <app>"   # Deploy an app using ssh (you must have first copied the Compose file to myvm1)
eval $(docker-machine env -u)     # Disconnect shell from VMs, use native docker
docker-machine stop $(docker-machine ls -q)               # Stop all running VMs
docker-machine rm $(docker-machine ls -q) # Delete all VMs and their disk images

Thursday, April 18, 2019

Run Powershell with elevate without prompt - verb runas start-process


Based on https://ss64.com/ps/syntax-elevate.html this:


Create a script as :

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))

{

  # Relaunch as an elevated process:

  Start-Process powershell.exe   "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs

  exit

}

# Now running elevated so launch the script:

& $scriptPath + "\test.ps1" "Long Argument 1" "Long Argument 2"

To disable the UAC pop up windows

REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f

Tuesday, April 16, 2019

c++ mutithreading mistakes

https://www.acodersjourney.com/top-20-cplusplus-multithreading-mistakes/

Mistake # 1: Not using join() to wait for background threads before terminating an application
If we forgot to join a thread or detach it(make it unjoinable) before the main program terminates, it'll cause in a program crash.

Mistake # 2: Trying to join a thread that has been previously detached
If you have detached a thread and at some point, you cannot rejoin it to the main thread.
The problem is that this'll not cause a compilation error,  instead it'll crash your program.

Mistake # 3: Not realizing that std::thread::join() blocks the calling thread

Mistake # 4: Thinking that thread function arguments are pass by reference by default
Thread function arguments are by default pass by value. So if you need the change persisted in the arguments passed in, you'll need to pass them by reference using std::ref().

Mistake # 5: Not protecting shared data or shared resources with a critical section (eg. mutex)
In a multithreaded environment, more than one thread is often competing for a resource or shared data. This often results in undefined behavior for the resource or data , unless the resource or data is protected using some mechanics that only allows ONE thread to act on it at a time.

Mistake # 6: Forgetting to release locks after a critical section
should use std::lock_guard which uses RAII style to manage the duration of mutex lock. 

Mistake # 7: Not keeping critical sections as compact and small as possible


Mistake # 8 : Not acquiring multiple locks in the same order
This is one of the most common causes of DEADLOCK

Mistake # 10: Using mutexes when std::atomic types will suffice
When you have simple data types that needs to be updated, for example, a simple bool or a integer counter, using std:atomic will almost yield better performance than using a mutex.

Mistake # 11: Creating and Destroying a lot of threads directly when using a thread pool is available
Two of the most popular libraries that implements thread pools are Intel Thread Building Blocks(TBB) and Microsoft Parallel Patterns Library(PPL).

Mistake # 12: Not handling exceptions in background threads
Exceptions thrown in one thread cannot be caught in another thread

Mistake # 13: Using threads to simulate Asyn jobs when std::async will do
If you just need some code executed asynchronously i.e. without blocking execution of Main thread, your best bet is to use the std::async functionality to execute the code. 

Mistake # 14: Not using std::launch::async if asynchronicity is desired
std::async is a bit of a misnomer because the function in it's default form may not execute in an asynchronous way !


Mistake # 15: Calling .Get() on a std::future in a time sensitive code path

Mistake # 16: Not realizing that an exception thrown inside an async task is propagated when std::future::get() is invoked.

Mistake # 17: Using std::async when you need granular control over thread execution
Mistake # 18: Creating many more "Runnable" threads than available cores

Mistake # 19: Using "volatile" keyword for synchronization
The "volatile" keyword in front of a variable type declaration does not make the operations on that variable atomic or thread safe in any way. What you probably want is an std::atomic.

Mistake # 20: Using a Lock Free architecture unless absolutely needed



c++ Multithreading


1 Header Required:
#include <thread>

2 We can attach a callback with the std::thread object, that will be executed when this new thread starts.
These callbacks can be:
a.) Function Pointer
b.) Function Objects
c.) Lambda functions

3 Joining Threads with std::thread::join()
std::thread th(funcPtr);
th.join();

Detaching Threads using std::thread::detach()
std::thread th(funcPtr);
th.detach();

1.) Never call join() or detach() on std::thread object with no associated executing thread
2.) Never forget to call either join or detach on a std::thread object with associated executing thread

4 Pass Arguments to Threads
By default all arguments are copied into the internal storage of new thread.
Don’t pass addresses of variables from local stack to thread’s callback function.
Be careful while passing pointer to memory located on heap to thread. Because it might be possible that some thread deletes that memory before new thread tries to access it.
As arguments are copied to new threads stack so, if you need to pass references in common way.  ie.
   void threadCallback(int const & x)
   {
       int & y = const_cast<int &>(x);
       y++;
   }
   int main()
   {
    int x = 9;
    std::thread threadObj(threadCallback,std::ref(x));
    threadObj.join();
    return 0;
    }

Assigning pointer to member function of a class as thread function:
Pass the pointer to member function as callback function and pass pointer to Object as second argument.

#include <thread>
class DummyClass {
public:
    DummyClass()
    {}
    DummyClass(const DummyClass & obj)
    {}
    void sampleMemberFunction(int x)
    {
        std::cout<<"Inside sampleMemberFunction "<<x<<std::endl;
    }
};
int main() {

    DummyClass dummyObj;
    int x = 10;
    std::thread threadObj(&DummyClass::sampleMemberFunction,&dummyObj, x);
    threadObj.join();
    return 0;
}

5 std::mutex
There are two important methods of mutex:
a.) lock()
b.) unlock()
std::lock_guard
std::lock_guard is a class template, which implements the RAII RESOURCE ACQUISITION IS INITIALIZATION (RAII) for mutex.
It wraps the mutex inside it’s object and locks the attached mutex in its constructor. When it’s destructor is called it releases the mutex.

Condition Variables.
Condition Variable is a kind Event used for signaling between 2 threads. One thread can wait for it to get signaled, while other thread can signal this.

7std::future is a class template and its object stores the future value.
Now what the hell is this future value.
Actually a std::future object internally stores a value that will be assigned in future and it also provides a mechanism to access that value i.e. using get() member function. But if somebody tries to access this associated value of future through get() function before it is available, then get() function will block till value is not available.
std::promise is also a class template and its object promises to set the value in future. Each std::promise object has an associated std::future object that will give the value once set by the std::promise object.
A std::promise object shares data with its associated std::future object.

If std::promise object is destroyed before setting the value the calling get() function on associated std::future object will throw exception.
A part from this, if you want your thread to return multiple values at different point of time then just pass multiple std::promise objects in thread and fetch multiple return values from thier associated multiple std::future objects.

Wednesday, April 3, 2019

STL Overview

STL Overview
Containers:
Sequence: vector deque list
Associative: set, multiset, map, multimap

Iterators:
Input, output, forward, bidirectional, random access
Each container declares a trait for the type of iterator it provides

Generic Algorithms:
Sequence (mutating and non-mutating) sorting numeric

STLContainers are Abstract Data Types
All Containers are parameterized by the type they contain
Sequence containers are ordered
Associative containers are unordered
Each container declares an iterator typedef trait
Each container provides special factory methods for iterators

What's STL? Why use STL?

What's STL? Why use STL?

The Standard Template Library provides a set of well structured generic C++ components that work together in a seamless way.
–AlexanderStepanov&MengLee, The Standard Template Library
A collection of composable class and function templates.
- Helper class and function templates, operators, pair
- Container and iterator class templates
- Generic algorithms that operate over iterators
- Function objects
- Adaptors


Enables generic programming in c++
-Each generic algorithm can operate over any iterator for which the necessary operations are provided.
-Extensible can support new algorithm containers iterators
Resue
The STL hides complex tedious and error-prone details
Typesafe plug compatibility between STL component
Flexibility
Iterator decouple algorithms for containers
Unanticipated combinations easily supported
Efficiency
Templates avoid virtual function overhead
Strict attention to the time complexity of algorithms