How to disable VirtualStore for C++ programs? - c++

I'd like my program to throw an error when it tries to create files in protected locations like the root of the C:\ drive (eg: FILE* FileHandle = fopen("\\file.txt", a)). Instead the file gets created in the Virtual Store under %APPDATA%.
How can I disable that Virtual Store?
Thanks
EDIT: Just to be clear, I'm not asking how to circumvent the security and create my file in a protected location. I want the file creation to FAIL so that I can tell the user he was an idiot.

You add an application manifest. Choose asInvoker, highestAvailable, or requireAdministrator. It sounds like you want asInvoker.
From http://msdn.microsoft.com/en-us/library/bb756929.aspx:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0"
processorArchitecture="X86"
name="IsUserAdmin"
type="win32"/>
<description>Description of your application</description>
<!-- Identify the application security requirements. -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel
level="asInvoker"
uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

From MSDN:
Virtualization is only enabled for:
32 bit interactive processes
Administrator writeable file/folder
and registry keys
Virtualization is disabled for:
64 bit processes
Non-interactive processes
Processes that impersonate
Kernel mode callers
Executables that have a requestedExecutionLevel
Your best bet, as Adam Maras noted, is to set a requestedExecutionLevel on your application by adding a manifest. A requestedExecutionLevel of "asInvoker" will cause file operations to fail on protected locations, rather than redirecting to the virtual store or prompting for elevation.

Here is an article that shows how to turn off the virtualization.
http://www.interworks.com/blogs/dsmith/2011/09/21/disabling-windows-7-virtual-store
The short of it is:
-From the Windows 7 Start Orb, do a search for Local Security Policy and select it.
-Expand Local Policies and click on Security Options. On the right pane, scroll all the way to the bottom and you will find a setting called " User Account Control: Virtualize file and registry write failures to per-user locations", double click on that setting and change it to Disabled.

Related

Is there a way to catch container-generated STDOUT within embedded Jetty Logback?

Situation is:
-> a homemade container app, using logback, configured with ConsoleAppender. Different loggers to specify log levels depending on package:
<logger name="com.mycompany.package1">
<level value="DEBUG"/>
</logger>
<logger name="com.mycompany.package2">
<level value="INFO"/>
</logger>
-> an embedded Jetty app, using logback, configured with RollingFileAppender.
I need both log outputs to be sent to the same rolling file, so I'm trying to catch the container STDOUT within the embedded Jetty app. Is there a way to do that? is it the wrong way to go about it?
NOTE: I have access to both logback.xml for editing.
If you have a logback configuration going to ConsoleAppender then don't attempt to catch output and log it again (you just created a loop).
Instead, just configure Jetty to use slf4j for its own events and NOT use the RolloverFileOutputStream or the console-capture module (from jetty-home).
The easiest way is to not do anything, the mere existence of slf4j-api-<ver>.jar in the server classpath is sufficient to make Jetty use slf4j to log its own events on.
In short, your server classpath needs:
slf4j-api-<ver>.jar
Your logback jars (probably logback-classic-<ver>.jar and logback-core-<ver>.jar)
A ${jetty.base}/resources/ directory on your classpath with 2 files:
a jetty-logging.properties with a single line org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.Slf4jLog
your logback configuration files. (eg: logback.xml)
Make sure you are not using Jetty's RollingFileOutputStream to capture System.out and/or System.err to a file.

Change windows installer error message if service installation fails

I'm currently struggling with WIX (disclaimer: I'm a very beginner in terms of WIX).
I need to install a service. The specific part of the .wxs file looks like this:
<ServiceInstall
Id="ServiceInstaller"
Vital="yes"
Type="ownProcess"
Name="ABC_MyService"
DisplayName="TestService"
Description="Monitoring and management Jobs"
Start="auto"
Arguments="--service"
Account="LocalSystem"
ErrorControl="normal"
Interactive="no"
/>
<ServiceControl Id="StartService" Start="install" Stop="both" Remove="uninstall" Name="ABC_MyService" Wait="yes" />
Unfortunately the start of the service can fail in some cases (a port is already in use etc.). In that case you will get the super generic and confusing WIX error msg:
Service xy failed to start. Verify that you have sufficient privileges
to start system services.
Is there any way to propagate error messages / exceptions which can occur when starting the service and override the generic error msg?

JEE7/JAX-RS How to programatically create a JDBC connectionpool

I'm currently developing a REST service to replace an existing solution. I'm using plain Payara/JEE7/JAX-RS. I am not using Spring and I do not intent to.
The problem I'm facing is that we want to reuse as much of the original configuration as possible (deployment on multiple nodes in a cluster with puppet controlling the configuration files).
Usually in Glassfish/Payara, you'd have a domain.xml file that has some content like this:
<jdbc-connection-pool driver-classname="" pool-resize-quantity="10" datasource-classname="org.postgresql.ds.PGSimpleDataSource" max-pool-size="20" res-type="javax.sql.DataSource" steady-pool-size="10" description="" name="pgsqlPool">
<property name="User" value="some_user"/>
<property name="DatabaseName" value="myDatabase"/>
<property name="LogLevel" value="0"/>
<property name="Password" value="some_password"/>
<!-- bla --->
</jdbc-connection-pool>
<jdbc-resource pool-name="pgsqlPool" description="" jndi-name="jdbc/pgsql"/>
Additionally you'd have a persistence.xml file in your archive like this:
<persistence-unit name="myDatabase">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/pgsql</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!-- bla -->
</properties>
</persistence-unit>
I need to replace both of these configuration files by a programmatic solution so I can read from the existing legacy configuration files and (if needed) create the connection pools and persistence units on the server's startup.
Do you have any idea how to accomplish that?
Actually you do not need to edit each domain.xml by hands. Just create glassfish-resources.xml file like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool driver-classname="" pool-resize-quantity="10" datasource-classname="org.postgresql.ds.PGSimpleDataSource" max-pool-size="20" res-type="javax.sql.DataSource" steady-pool-size="10" description="" name="pgsqlPool">
<property name="User" value="some_user"/>
<property name="DatabaseName" value="myDatabase"/>
<property name="LogLevel" value="0"/>
<property name="Password" value="some_password"/>
<!-- bla --->
</jdbc-connection-pool>
<jdbc-resource pool-name="pgsqlPool" description="" jndi-name="jdbc/pgsql"/>
</resources>
Then either use
$PAYARA_HOME/bin/asadmin add-resources glassfish-resources.xml
on each node once or put it under WEB-INF/ of your war (note, in this case jndi-name SHOULD be java:app/jdbc/pgsql because you do not have access to global: scope at this context).
Note that your persistence.xml should be under META-INF/ of any jar in your classpath.
If you do not like this, you may use
#PersistenceUnit(unitName = "MyDatabase")
EmtityManagerFactory emf;
to create EntityManager on fly:
createEntityManager(java.util.Map properties).
By the way, using Payara you can share configuration with JCache across you cluster.
Since the goal is to have a dockerized server that runs a single application, I can very well use an embedded server.
Using an embedded sever, the solution to my problem looks roughly like this:
For the server project, create a Maven dependency:
<dependencies>
<dependency>
<groupId>fish.payara.extras</groupId>
<artifactId>payara-embedded-all</artifactId>
<version>4.1.1.163.0.1</version>
</dependency>
</dependencies>
Start your server like this:
final BootstrapProperties bootstrapProperties = new BootstrapProperties();
final GlassFishRuntime runtime = GlassFishRuntime.bootstrap();
final GlassFishProperties glassfishProperties = new GlassFishProperties();
final GlassFish glassfish = runtime.newGlassFish(glassfishProperties);
glassfish.start();
Add your connection pools to the started instance:
final CommandResult createPoolCommandResult = commandRunner.run("create-jdbc-connection-pool",
"--datasourceclassname=org.postgresql.ds.PGConnectionPoolDataSource", "--restype=javax.sql.ConnectionPoolDataSource", //
"--property=DatabaseName=mydb"//
+ ":ServerName=127.0.0.1"//
+ ":PortNumber=5432"//
+ ":User=myUser"//
+ ":Password=myPassword"//
//other properties
, "Mydb"); //the pool name
Add a corresponding jdbc resource:
final CommandResult createResourceCommandResult = commandRunner.run("create-jdbc-resource", "--connectionpoolid=Mydb", "jdbc__Mydb");
(In the real world you would get the data from some external configuration file)
Now deploy your application:
glassfish.getDeployer().deploy(new File(pathToWarFile));
(Usually you would read your applications from some deployment directory)
In the application itself you can just refer to the configured pools like this:
#PersistenceContext(unitName = "mydb")
EntityManager mydbEm;
Done.
A glassfish-resources.xml would have been possible too, but with a catch: My configuration file is external, shared by some applications (so the file format is not mine) and created by external tools on deployment. I would need to XSLT the file to a glassfish-resources.xml file and run a script that does the "asadmin" calls.
Running an embedded server is an all-java solution that I can easily build on a CI server and my application's test suite could spin up the same embedded server build to run some integration tests.

How to configure Jetty in spring-boot (easily?)

By following the tutorial, I could bring up the spring-boot with Jetty running using the following dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
However, how could I configure the Jetty server such as:
Server threads (Queue thread pool)
Server connectors
Https configurations.
all those configuration available in Jetty...?
Is there an easy way to do in
application.yml?
Configuration class?
Any example would be greatly appreciated.
Many thanks!!
There are some general extension points for servlet containers and also options for plugging Jetty API calls into those, so I assume everything you would want is in reach. General advice can be found in the docs. Jetty hasn't received as much attention yet so there may not be the same options available for declarative configuration as with Tomcat, and for sure it won't have been used much yet. If you would like to help change that, then help is welcome.
Possibility to configure Jetty (in parts) programatically from http://howtodoinjava.com/spring/spring-boot/configure-jetty-server/
#Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
JettyEmbeddedServletContainerFactory jettyContainer =
new JettyEmbeddedServletContainerFactory();
jettyContainer.setPort(9000);
jettyContainer.setContextPath("/home");
return jettyContainer;
}
If anyone is using Spring Boot - you can easily configure this in you application.properties thusly:
server.max-http-post-size=n
where n is the maximum size to which you wish to set this property. For example I use:
server.max-http-post-size=5000000
As of the year 2020, while working on newer versions, this is what you need to do, to configure Jetty port, context path and thread pool properties. I tested this on Spring Boot version 2.1.6 while the document I referred to is for version 2.3.3
Create a server factory bean in a configuration file.
#Bean
public ConfigurableServletWebServerFactory webServerFactory() {
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
factory.setPort(8080);
factory.setContextPath("/my-app");
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(10);
threadPool.setMaxThreads(100);
threadPool.setIdleTimeout(60000);
factory.setThreadPool(threadPool);
return factory;
}
Following is the link to Spring Docs:
customizing-embedded-containers
Spring Boot provides following Jetty specific configuration through property file:-
server:
jetty:
connection-idle-timeout: # Time that the connection can be idle before it is closed.
max-http-form-post-size: # Maximum size of the form content in any HTTP post request e.g. 200000B
accesslog:
enabled: # Enable access log e.g. true
append: # Enable append to log e.g. true
custom-format: # Custom log format
file-date-format: # Date format to place in log file name
filename: # Log file name, if not specified, logs redirect to "System.err"
format: # Log format e.g ncsa
ignore-paths: # Request paths that should not be logged
retention-period: # Number of days before rotated log files are deleted e.g. 31
threads:
acceptors: # Number of acceptor threads to use. When the value is -1, the default, the number of acceptors is derived from the operating environment.
selectors: # Number of selector threads to use. When the value is -1, the default, the number of selectors is derived from the operating environment.
min: # Minimum number of threads e.g. 8
max: # Maximum number of threads e.g. 200
max-queue-capacity: # Maximum capacity of the thread pool's backing queue. A default is computed based on the threading configuration.
idle-timeout: # Maximum thread idle time in millisecond e.g. 60000ms
Please refer official Spring Boot documentation for more configuration details.

AppFabric Cluster

I am having an issue with AppFabric in a load balanced environment. For some reason when I start the AppFabric cluster, I don’t see anything listening on the ports (22233). Below is our config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="dataCache" type="Microsoft.ApplicationServer.Caching.DataCacheSection, Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<dataCache size="Small">
<hosts>
<host replicationPort="22236" arbitrationPort="22235" clusterPort="22234"
hostId="2035002654" size="4095" leadHost="true" account="ServiceAccount"
cacheHostName="AppFabricCachingService" name="Server2"
cachePort="22233" />
<host replicationPort="22236" arbitrationPort="22235" clusterPort="22234"
hostId="434992406" size="4095" leadHost="true" account="ServiceAccount"
cacheHostName="AppFabricCachingService" name="Server1"
cachePort="22233" />
</hosts>
</dataCache>
</configuration>
If I change the config to make ONE of the servers a leadHost, that host now listens on port 22233. But in order to keep high availability, I need both up and running.
As far as i know about AppFabric, you must have a server configured as a leadhost. Also there has to be only 1 leadhost in the cache cluster.
Please let me know if i am wrong.
Thanks and Regards
Gagan Janjua