Tuesday, March 26, 2019

Prevent and Mitigate Stack Overflow

When programming micro-controllers you usually have to be more careful with your memory usage and also for smaller devices you often don't get any help from the hardware.

On ARM micro-controllers the memory layout is such that the stack is placed at the higher address range of the memory and writes 'downwards' towards the lower memory addresses. While the heap fills up memory from the lower to the higher addresses. In cases of high use of static/program memory use, heap use and stack use, the stack can overflow and overwrite heap memory. This may result in weird and undefined behavior. This is bad.


Some methods that can be used to prevent this:
  • Use the HW memory protection unit: HW unit that causes an interrupt or fault if stack is written passed a defined address.
  • Canary: Write a unique value to address designated as top of stack and check that this value is still written to top of stack address in main loop.
  • Add stack protection code: GCC can add functionality to check wether writes to stack would overflow. Results in larger program binary and higher overall stack usage.
  • Stack depth analysis: Compile time or static analysis of code to determine how much stack each function will use and combinations that would result in stack overflow. Some tools:
    • GCC -fstack-usage, doesn't work in combination with -lto (link time optimization).
    • ARM compiler, with Keil microvision (uvision), but gives only one number for each interrupt level.
  • Water mark: Fill stack with pattern for each main loop to, check stack usage after each automatic test. Create tests that you think will cause the most high stack usage functions to execute (preferably simultaneously/interrupted).

Well known case of this: https://developers.slashdot.org/story/14/02/21/2349204/stack-overflow-could-explain-toyota-vehicles-unintended-acceleration

Monday, April 18, 2016

Kerberos with groups on Tomcat 7

To provide Single-SignOn (SSO) to your web service on a linux server in a windows environment (Active Directory) you can add a login filter to tomcat to accept Kerberos tokens. It's really quite simple, if you set it up correctly, which is not simple to figure out.

Ack: Compiled from http://portlandlanguagecraft.com/ and https://pixabay.com/en/chain-gold-power-connection-rights-307886/

I did it using a custom SPNEGO filter to also extract AD groups from the kerberos tokens.

Mostly follow https://tomcat.apache.org/tomcat-7.0-doc/windows-auth-howto.html but with many additional tweaks.

You will need to create/edit the following files (On Ubuntu):

/etc/tomcat7/web.xml
/etc/tomcat7/login.conf
/etc/tomcat7/krb5.conf
/etc/tomcat7/mykeytab.keytab
/usr/share/tomcat7/libs/spnego-r7.jar

(These files are also found in /var/lib/tomcat7/conf).

Step-by-step (First section just for login and second section for getting groups too):

AUTHENTICATION (Login):


Download the Spnego HTTP filter:
Available from https://sourceforge.net/projects/spnego/. Put the file under /usr/share/tomcat7/libs/spnego-r7.jar to make tomcat load it on startup.

On the Active Directory (AD) / Kerberos Key Distribution Center (KDC) / Windows server:

Add service user:
Add a service user to let you linux server "log in" and validate kerberos tokens.

Link SPN to service user:
SPN (Service Principal Names) are identifiers for users or hosts. We need to add the ones representing our server. NOTE: The SPN is case sensitive and you must use the same case everywhere. The command is on the form:
setspn.exe -A HTTP/<HOSTNAME> DOMAIN\<SERVICE USER>

So on your windows/AD server enter the following

setspn.exe -A HTTP/myserver DOMAIN\myserviceuser
setspn.exe -A HTTP/myserver.domain.local DOMAIN\myserviceuser

to link the SPN HTTP/myserver to the user myserviceuser.

Generate keytab:
The keytab is file which stores SPNs/usernames and password for them.

According to the apache tutorial you should do this on your windos/AD server using the ktpass tool. I found it was better to use the ktab.exe that comes with java on windows:
ktab -a HTTP/<HOSTNAME> <SERVICE USER PASSWORD> -k <OUTPUT FILE> -n 0
e.g.
ktab -a HTTP/myserver.domain.local myservicepassword -k mykeytab.keytab -n 0

Note the n 0 flag which sets key version number, it needs to be 0 for tomcat/Spnego to find the key.

Put the mykeytab.keytab file under /etc/tomcat7/mykeytab.keytab on your linux server.


We also need to make the computers in the windows network trust our server, to do this we can use Group Policy on the AD server. But we'll get back to that later.


On the linux server (as sudo):

Add a filter to /etc/tomcat7/web.xml:

<!-- ======================== SPNEGO filter ==============================-->
  <filter>
    <filter-name>SpnegoHttpFilter</filter-name>
    <filter-class>net.sourceforge.spnego.SpnegoHttpFilter</filter-class>

    <init-param>
        <param-name>spnego.allow.basic</param-name>
        <param-value>true</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.allow.localhost</param-name>
        <param-value>false</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.allow.unsecure.basic</param-name>
        <param-value>true</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.login.client.module</param-name>
        <param-value>com.sun.security.jgss.krb5.initiate</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.krb5.conf</param-name>
        <param-value>conf/krb5.conf</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.login.conf</param-name>
        <param-value>conf/login.conf</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.preauth.username</param-name>
        <param-value>SERVICE_USER_USERNAME</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.preauth.password</param-name>
        <param-value>SERVICE_USER_PASSWORD</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.login.server.module</param-name>
        <param-value>com.sun.security.jgss.krb5.accept</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.prompt.ntlm</param-name>
        <param-value>true</param-value>
    </init-param>
  
    <init-param>
        <param-name>spnego.logger.level</param-name>
        <param-value>1</param-value>
    </init-param>
</filter>


You need to replace SERVICE_USER_NAME and SERVICE_USER_PASSWORD with the ones you use to create your keytab. spnego.allow.basic, spnego.prompt.ntlm are true to let users who haven't logged into windows to log in (WARNING: username and password are sent in cleartext/base64 to the linux server!). spnego.allow.unsecure.basic needs to be true if you don't use https, which you should do.

  <filter-mapping>
    <filter-name>SpnegoHttpFilter</filter-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>


To apply filter to all files.


Create/edit the login.conf:

com.sun.security.jgss.krb5.initiate {
    com.sun.security.auth.module.Krb5LoginModule required;
};

com.sun.security.jgss.krb5.accept {
    com.sun.security.auth.module.Krb5LoginModule required
    doNotPrompt=true
    useKeyTab=true
    principal="HTTP/myserver.domain.local@DOMAIN.LOCAL"
    keyTab="/var/lib/tomcat7/conf/mykeytab.keytab"
    storeKey=true
    isInitiator=false;
};


Differently from the apache tutorial, the initate object should only contain the module, otherwise tomcat will throw a parse error on startup.


Create/edit the krb5.conf:

[libdefaults]
default_realm = DOMAIN.LOCAL
default_keytab_name = FILE:/etc/tomcat7/mykeytab.keytab
default_tkt_enctypes = rc4-hmac,aes256-cts-hmac-sha1-96,aes128-cts-hmac-sha1-96
default_tgs_enctypes = rc4-hmac,aes256-cts-hmac-sha1-96,aes128-cts-hmac-sha1-96
forwardable = true

[realms]
DOMAIN.LOCAL = {
        kdc = 192.168.1.5:88
}

[domain_realm]
domain.local = DOMAIN.LOCAL
.domain.local = DOMAIN.LOCAL

[login]
        krb4_convert = true
        krb4_get_tickets = false


The kdc parameter should support the hostname of the KDC/AD server e.g. kdc.domain.local, but mine had trouble with DNS lookup for it, luckily IP works fine.

NOTE: Make sure time is within a few minutes of the AD server, consider installing a NTP client to keep in sync.

AUTHORIZATION (roles/groups):


You will need to create/edit the following files (On Ubuntu):

/var/lib/tomcat7/webapps/ROOT/WEB-INF/web.xml
/usr/share/tomcat7/libs/bcprov-jdk15on-147.jar
/usr/share/tomcat7/libs/spnego-pac.jar

Active Directory adds a blob to their kerberos tokens called PAC (Privilege Attribute Certificate), which includes a users roles. We can extract these roles from our ticket so we don't have to do an additional LDAP request (which is the normal way).

To do this we need a custom build of the spnego library by Ricardo Martín Camarero (rickyepoderi) (see http://blogs.nologin.es/rickyepoderi/index.php?/archives/73-SPNEGOKerberos-in-JavaEE-PAC.html) which utilizes JaasLounge and Bouncy Castle ASN1 to extract the PAC roles.
I've added support for fetching a users kerberos token when using Basic Auth as well as adding compressed PAC from another library.

The spnego-pac source code is available from github (https://github.com/asmund1/spnego-pac), and the final binaries used in this project from https://github.com/asmund1/spnego-pac/blob/master/jars/spnego-pac.jar and https://github.com/asmund1/spnego-pac/blob/master/jars/bcprov-jdk15on-147.jar (additional library needed).

On the linux server (as sudo):

Copy spnego-pac.jar and bcprov-jdk15on-147.jar to /usr/share/tomcat7/libs/ so that tomcat loads it on startup. NOTE: Remove the original spnego jar if you have it there already.

The PAC contains only the numerical representation for each role for the user, you can use this directly in your servlets, but I added some aliases for my roles. I did this in the webapp web.xml, but it should work in the global web.xml too (/etc/tomcat7/web.xml):

    <context-param>
        <param-name>myserver_write_role</param-name>
        <param-value>S-1-5-21-123456789-1234567890-1234567890-1234</param-value>
        <description>Alias for write access role</description>
    </context-param>


To get the value for your roles, check your tomcat log (/var/lib/tomcat7/logs/catalina.out) after login using kerberos, the library prints the SIDs found for a user.
You might have to change the log level since they are printed at FINER level. Do this by appending
net.sourceforge.spnego.SpnegoAuthenticator = FINER
to the bottom of /etc/tomcat/logging.properties file and restarting tomcat.

GET USER AND ROLES (CODE):


The username/SPN of the logged in user and his/her roles are added to the request object, so to fetch them in Java servlets / JSP use the following lines of code:

For Java Servlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletContext;

public class MyServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        // Fetches username of logged in user
        req.getRemoteUser()

         // Check if user has write access
        ServletContext context = req.getServletContext();
        if (!req.isUserInRole(context.getInitParameter("myserver_write_role"))) {
            resp.sendError(resp.SC_FORBIDDEN);
            return;
        }
    }
}


For JSP:
<%= request.getRemoteUser() %>
and
<%= request.isUserInRole(request.getServletContext().getInitParameter("myserver_write_role")) %>

TRUSTED SERVER:


To get the kerberos token from windows you need to be on the trusted server list. Chrome and IE use a common list while firefox and other browsers have their own.

To add you server as trusted in IE (and Chrome) open Internet Options -> Security -> Local intranet -> Sites button -> Advanced button
Enter the url for your server and press the Add button.

To do the same for firefox do the following:
1. Open Firefox, and type "about:config" in the Address Bar.
2. In the Search field, type "negotiate".
3. Set the following fields:
      network.negotiate-auth.trusted-uris  myserver.domain.local
      network.negotiate-auth.delegation-uris myserver.domain.local

(https://bugzilla.mozilla.org/show_bug.cgi?id=520668)

To add  your server for IE and Chrome for all windows machines in the intranet, you can use Group Policy: https://www.serverknowledge.net/group-policy/adding-trusted-sites-internet-explorer-using-group-policy-gpo/

TEST:


On the linux server (as sudo):
Start/Restart tomcat server to load changes in config and load jars:
service tomcat7 restart

Then tail the log output for any errors:
tail -f /var/lib/tomcat7/logs/catalina.out

Then navigate to your server in IE/Chrome. You should not be prompted for username or password. If you go to the server from a non-windows logged on computer (e.g. mobile phone) you should get a popup asking you to enter username and password. If you enter the incorrect password you should get a white page, with correct credentials you should see your content.

Sources:

http://spnego.sourceforge.net/spnego_tomcat.html
http://spnego.sourceforge.net/pre_flight.html
http://spnego.sourceforge.net/reference_docs.html
http://spnego.sourceforge.net/client_keytab.html
http://spnego.sourceforge.net/ExampleSpnegoAuthenticatorValve.java
http://spnego.sourceforge.net/HelloKeytab.java
https://sourceforge.net/p/spnego/discussion/1003769/thread/98e5ea01/

http://jaaslounge.sourceforge.net/howto/SSO_Tomcat_Howto.pdf
http://www.oracle.com/technetwork/articles/idm/weblogic-sso-kerberos-1619890.html
http://stackoverflow.com/questions/20152000/get-ad-groups-with-kerberos-ticket-in-java
https://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html#JNDIRealm
http://docs.oracle.com/javase/7/docs/technotes/guides/security/jgss/lab/part6.html
http://kerberos.996246.n3.nabble.com/kinit-Cannot-contact-any-KDC-for-realm-EXAMPLE-COM-while-getting-initial-credentials-td19145.html
http://serverfault.com/questions/166768/kinit-wont-connect-to-a-domain-server-realm-not-local-to-kdc-while-getting-in
http://stackoverflow.com/questions/31877027/kerberos-cannot-find-key-of-appropriate-type-to-decrypt-ap-rep-rc4-with-hmac

https://docs.google.com/document/d/1G7WAaYEKMzj16PTHT_cIYuKXJG6bBcrQ7QQBQ6ihOcQ/edit#heading=h.yh8m8tkjdx9h
http://stackoverflow.com/questions/3568635/android-authenticating-with-kerberos

http://stackoverflow.com/questions/2518256/override-intranet-compatibility-mode-ie8

Friday, April 15, 2016

Share one file

Frequently I have two computers next to each other and I want to copy a file or directory from one to the other. What do you do? Mail it to yourself, sync it via some cloud service, set up samba? No just use woof (http://www.home.unix-ag.org/simon/woof.html).

 

A tiny python server that serves one file and then shuts down as soon as the file has been downloaded. (You can also share a directory as a tar archive).

Just do:
python woof.py 'file to share'

Enter the resulting URL e.g.:
http://10.0.0.94:8080/IMG_0017.jpg
in a web browser on the other machine
and voila.

NOTE: the computers need to be on the same network. + you need to be running linux/unix with python 2.7.x.

Wednesday, April 6, 2016

Framebuffer screen dumps to PNG and back

I've got a nice card with an Atmel AVR32 processor and a nice big 320x240 (monochrome!) screen. :)
I can put data on the screen from buildroot linux by writing directly to the framebuffer, /dev/fb0. However the data there is in raw format. Here is how to dump from screen. Then convert, using ffmpeg, the raw data to a PNG and then back to raw data after editing:

  1. Get a screenshot of the framebuffer using cat /dev/fb0 > screendump.bin.
  2. Convert to PNG using ffmpeg: ffmpeg   -vcodec rawvideo   -f rawvideo   -pix_fmt monow   -s 320x240   -i screendump.bin     -f image2   -vcodec png screendump.png
    This will read raw video from the screendump.bin, handle it as pixel monochrome data from a 320x240 screen and save as sreendump PNG file.
  3. Next, open in Gimp or similar to edit. Save as PNG afterwards.
  4. Convert to rawvideo binary again using ffmpeg: ffmpeg -vcodec png -i savedimage.png -vcodec rawvideo -f rawvideo -pix_fmt monow savedimage.bin
  5. Put the data on the screen: cat savedimage.bin > /dev/fb0
Use ffmpeg -pix_fmts to see other raw video types to convert from/to.

Sources: Check out these great sites for more:
http://www.catswhocode.com/blog/19-ffmpeg-commands-for-all-needs
http://forum.videohelp.com/threads/334333-Help-with-lossless-ffmpeg-command-%5Bvideo-png-back-to-video%5D
http://stackoverflow.com/questions/3781549/how-to-convert-16-bit-rgb-frame-buffer-to-a-viewable-format
https://community.freescale.com/docs/DOC-100347

Remote Desktop over the Internet using UltraVNC on Windows

Here is a HowTo for setting up a UltraVNC server on your computer, automatically open needed ports, and creating a configured UltraVNC single-click client to let you see someones desktop where all they have to do is start the client you send to them. No installations!
(A great alternative is TeamViewer which is free for personal use, but expensive for commercial use)

Here is how:

- Download UltraVNC and install:
See bottom of: http://www.uvnc.com/downloads/ultravnc.html

- Download UltraVNC SingleClick custom.zip package from:
http://www.uvnc.com/pchelpware/sc/create.html

- Extract helpdesk.txt file.

- Edit to look like you want to.
Example helpdesk.txt:

[TITLE]
UltraVnc SC

[HOST]
My RDC connection
-connect 158.158.158.158:5900 -noregistry

[TEXTTOP]
Double click to open connection

[TEXTMIDDLE]

[TEXTBOTTOM]


[TEXTRBOTTOM]


[TEXTRMIDDLE]


[TEXTRTOP]


[TEXTBUTTON]
UltraVNC web

[WEBPAGE]
http://www.ultravnc.net

[TEXTCLOSEBUTTON]
Cancel


[BALLOON1TITLE]
Establishing connection ...

[BALLOON1A]
5 min connection attempt

[BALLOON1B]
If it fails, the software will close.

[BALLOON1C]


[BALLOON2TITLE]
Connection active.

[BALLOON2A]
Warning, your desktop is visible remotely

[BALLOON2B]
You can break the connection any time

[BALLOON2C]
by using the close button



(remember to replace 158.158.158.158 with your external IP, e.g. from https://www.whatismyip.com/)

- Create a ZIP file with only helpdesk.txt in it.

- Go to:
http://support1.uvnc.com/cgi-bin/upload4.pl

- Enter user: foo
- Enter password: foobar
- Select Zip file containing helpdesk.txt
- Click Upload
- Wait until you a link to download exe file appears. Then download the exe file.
- Start it to see what it looks like.


- Download UPnP PortMapper to open the needed port on your computer (if you havent done so manually on your router).
https://sourceforge.net/projects/upnp-portmapper/files/latest/download
https://github.com/kaklakariada/portmapper

- Open PortMapper jar file (should need only double-click if you have Java installed).
- Under the section "Port Mapping presets", select Create button.
- Enter a description, e.g. UltraVNC.
- Then click Add button.
- Change port 1 to 5900 in both External Port and Internal Port columns.
- Not sure if you also need UDP port open, but might be useful so click Add again and select UDP with port 5900 internal and external.
- Click save.

- Click connect to connect to your router.
When successfully connected (you might get an error, but stuff seems to work regardless).
- Select your UltraVNC entry in the list and press "Use".
- Wait for ports to show up in the list above.

Now you have ports open. You need to start VNC listener:
- Open command line prompt (cmd in windows start menu) and navigate to where you installed UltraVNC and run it with flag -listen 5900 to tell it to listen on port 5900:

cd "C:\Program Files\uvnc bvba\UltraVnc"
vncviewer.exe -listen 5900


- Finally, send the exe file you generated from helpdesk.txt (not the zip file) to the person you want to connect to. Get the person to open the file and double click on the top option and you should get a message on your computer asking you to accept the connection.


Source:
http://www.uvnc.com/docs/uvnc-sc/76-how-to-setup-and-configure-a-custom-Ultra%20VNC-sc.html

Sites to read about AngularJS and Ionic

Top 10 angularjs mistakes:
https://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make#9-manual-testing


Best practice dir structure angularjs/ionic:
https://scotch.io/tutorials/angularjs-best-practices-directory-structure
I've tried both. Unsure which one I think is best. I think the most important point is to create a directory structure to group your files according to how they are used. So that other people can understand how you program is structured more quickly.


Tips for ionic:
http://www.betsmartmedia.com/what-i-learned-building-an-app-with-ionic-framework (https://web.archive.org/web/20150925034548/http://www.betsmartmedia.com/what-i-learned-building-an-app-with-ionic-framework)


Intro and how to use jasmine unit test framework:
http://jasmine.github.io/edge/introduction.html
Great test tool!

Promises in AngularJS

 

Introduction to AngularJS promises (as a cartoon):
http://andyshora.com/promises-angularjs-explained-as-cartoon.html

Promise anti-patterns
Flatten chaining, clean up, and broken chains:
http://taoofcode.net/promise-anti-patterns/

HTTP promise not like Q promise, use deferred:
http://weblog.west-wind.com/posts/2014/Oct/24/AngularJs-and-Promises-with-the-http-Service

AngularJS Q:
https://docs.angularjs.org/api/ng/service/$q

Nice features to put on headless linux box

 

Unattended-upgrades:

Automatically download and install stable updates.

Install using:
sudo apt-get install unattended-upgrades
Configure using:
sudo dpkg-reconfigure -plow unattended-upgrades

Source:
http://raspberrypi.stackexchange.com/questions/4698/how-can-i-keep-my-raspbian-wheezy-up-to-date
https://help.ubuntu.com/community/AutomaticSecurityUpdates


Fail2ban:

http://www.fail2ban.org/wiki/index.php/Main_Page
https://en.wikipedia.org/wiki/Fail2ban





Imapgrab:

To automatically backup email:


http://www.linux-magazine.com/Online/Blogs/Productivity-Sauce/Back-up-Email-with-a-Single-Command
https://sourceforge.net/projects/imapgrab/ 

Android LayerDrawable in HTML using CSS

So a neat feature for Android is the LayerDrawable which lets you make an image compiled from other images. You define an array of images that shuld be drawn on top of each other and receive the resulting image.
This feature exists in CSS too. It's called background-image and lets you define one or more images to be displayed as a background of a container.

background-image: url(front.png), url(behind.png);





Remember to make the container a block element and if you don't have any content in it you should set the container height and width or a padding-bottom to give it size (Otherwise you will be shown approximately 0px of your background). See http://stackoverflow.com/questions/1495407/css-a-way-to-maintain-aspect-ratio-when-resizing-a-div

.container-with-background-image {
    width: 100%;
    padding-bottom: 75%;
}


Source:
http://www.css3.info/preview/multiple-backgrounds/
http://stackoverflow.com/questions/5846637/why-an-inline-background-image-style-doesnt-work-in-chrome-10-and-internet-ex

Wednesday, September 23, 2015

Using gettext Library for Translations

GNU gettext is a C library which lets you add translation support to your program with fallbacks to original text if no translation is available.

Here's a list of links to how you use the different utils in the gettext package:

See http://stackoverflow.com/questions/1003360/complete-c-i18n-gettext-hello-world-example for a hello world example using gettext.

See http://www.gnu.org/software/libc/manual/html_node/Locating-gettext-catalog.html for selecting translation file in code.
See http://www.gnu.org/software/libc/manual/html_node/Translation-with-gettext.html for using gettext in code.
See http://www.gnu.org/software/gettext/manual/html_node/lib_002fgettext_002eh.html for using gettext.h instead of libintl.h to get extended capabilities such as pgettext (adds context) and support for replacing gettext commmands with no-op if gettext is not installed on system. See http://www.gnu.org/software/gettext/manual/html_node/PO-Files.html for how PO files work (text files translations).
See http://www.heiner-eichmann.de/autotools/using_gettext.html, http://www.gnu.org/software/gettext/FAQ.html, and http://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/xgettext-Invocation.html for some information on using xgettext to extract strings for translation into a POT file.
See http://www.gnu.org/software/gettext/manual/html_node/msginit-Invocation.html on how msginit generates language specific translation files (PO) from POT file.
See http://www.gnu.org/software/gettext/manual/html_node/msgmerge-Invocation.html on how msgmerge generates updated language specific translation files (PO) from a changed POT file.
See http://www.gnu.org/software/gettext/manual/html_node/msgfmt-Invocation.html on how msgfmt generates binary translation files (MO) from human readable translation files (PO).


See http://www.gnu.org/software/gettext/FAQ.html#integrating_noop for troubleshooting missing translations


Simple example

  1. Copy gettext.h from /usr/share/gettext/ to your component or project.
  2. Set macro ENABLE_NLS to 1
  3. Include gettext.h in your cpp file.
  4. Example code:
    ::setlocale(LC_ALL, "");
    
    // Set directory to search for translation files in (which contains
    
    // en_US.UTF-8/LC_MESSAGES/hellogt.mo)
    
    bindtextdomain("hellogt", ".");
    
    // Set name of translation file to use (hellogt.mo)
    
    textdomain( "hellogt");
    
    std::cout << gettext("hi") << std::endl;
    
    std::cout << pgettext("bob", "hello, world!") << std::endl;
    

Generate translation files

#Common
find . -name "*.cpp" > files.txt
xgettext --package-name mygt --package-version 1.2 --default-domain mygt --output mygt.pot -f files.txt

#Spanish translations
sudo locale-gen es_MX.UTF-8
msginit --no-translator --locale es_MX --output-file mygt_spanish.po --input mygt.pot
mkdir -p ./es_MX.UTF-8/LC_MESSAGES
msgfmt --check --verbose --output-file ./es_MX.UTF-8/LC_MESSAGES/mygt.mo mygt_spanish.po

#Norwegian translations
sudo locale-gen nb_NO.UTF-8
msginit --no-translator --locale nb_NO --output-file mygt_norwegian.po --input mygt.pot
mkdir -p ./nb_NO.UTF-8/LC_MESSAGES
msgfmt --check --verbose --output-file ./nb_NO.UTF-8/LC_MESSAGES/mygt.mo mygt_norwegian.po

Update translation files

Add changes in code to language specific translation file:
xgettext --package-name mytgt --package-version 1.2 --default-domain mygt --output mygt.pot -f files.txt
msgmerge mygt_norwegian.po_old mygt.pot --output-file=mygt_norwegian.po_new
use msgfmt to generate new mygt.mo file from mygt_norwegian.po_new.

Sunday, June 7, 2015

AirPlay from Windows PC

If you need to play audio or video using Apple AirPlay from a windows machine here's the way:
Don't try AirParrot or TorrenTV as they don't work. And VLC streaming via Iphone/Ipad AirPlay is just silly.
Unfortunately the solution is: Apple has supplied iTunes for Windows with AirPlay functionality, so use that.
Or maybe we should just get a Chromecast. :)

Wednesday, March 11, 2015

AngularJS vs Ionic abstract state


Ionic is a wrapper for AngularJS and one of the changes that they've done is to the abstract state of the ui-router. I tried to follow an AngularJS tutorial for abstract state and added the following code:
.state('myparent', {
    abstract: true,
    url: '/myparent',
    // Note: abstract still needs a ui-view for its children to populate.
    // You can simply add it inline here.
    template: '<ui-view/>',
    controller: 'MyParentController'
})
.state('myparent.mychild', {
    url: '/mychild',
    templateUrl: 'mychild.view.html',
    controller: 'MyChildController'
})


Inside mychild.view.html I had:

<ion-view>
    <ion-content>
    ...
    </ion-content>
</ion-view>


This resultet in a blank page (although the controller was executed since it fetched the model from my backend). Also my navigation, for which I used $ionicHistory, was all messed up.

The trick apparently is to use ion-nav-view instead of ui-view in the abstract state:
.state('myparent', {
    abstract: true,
    url: '/myparent',
    // Note: abstract still needs a ui-view for its children to populate.
    // You can simply add it inline here.
    template: '<ion-nav-view/>',
    controller: 'MyParentController'
})


Lesson learned, use Ionic tutorials. :)

Source:
http://learn.ionicframework.com/formulas/navigation-and-routing-part-2/
https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#abstract-states
http://ionicframework.com/docs/api/service/$ionicHistory/

Friday, March 6, 2015

Android 9-patch image in HTML5 CSS3

One feature that Android has adopted is 9-patch images. The Android Studio contains a Draw 9-patch tool which lets you 'create bitmap images that automatically resize'. Basically you select areas of an image that can be repeated or stretched while others are kept at the same size. Giving you almost SVG functionality for bitmap images, especially great for buttons.


Now this feature would be great for web as well, e.g. responsive design pages. To achieve this we can use the CSS3 feature border-image which combines border-image-source, border-image-width, border-image-slice and border-image-outset.

border-image-source defines which image to use.

border-image-width defines the width of the border image. Stretches or shrinks the image regions to fit the widths.

border-image-slice divides the image into 9 regions, thereby the name (see the image above) deciding which parts can be repeated/stretched. The regions are: four corners, four edges and a middle. The fill property decides if the middle should be filled in or kept transparent.

border-image-outset decides how far out from the border the image will appear. Together with border-width this enables the border to not take up all the space inside the container caused by it having a wide border to fit the image inside (See http://www.norabrowndesign.com/css-experiments/border-image-frame.html#one). This is especially great for select/dropdown boxes as they can't work around this by using line-height (http://stackoverflow.com/questions/18613279/text-over-the-top-of-a-border-image-using-the-border-as-an-expandable-backgroun)

border-image combines the four above properties, but I felt I had more control when splitting them up. However, as of right now browser support for border-image and especially border-image-outset is a bit limited. Most browsers support border-image, but might need browser-specific CSS (e.g. -webkit-border-image).


 Example:
border-style: solid;
border-width: 5px;
border-image-source: url(dropdown.png);
border-image-width: 25% 10% 25% 5%;
border-image-slice: 10 70 20 60 fill;
border-image-outset: 12px;


http://border-image.com lets you generate border-image CSS from an image. but it doesn't put in border-image-outset.

Source:
https://github.com/chrislondon/9-Patch-Image-for-Websites/wiki/What-Are-9-Patch-Images
http://stackoverflow.com/questions/6806559/does-9-patch-png-can-work-somehow-with-css-on-browsers
http://stackoverflow.com/questions/3659457/nine-patch-images-for-web-development
https://teamtreehouse.com/forum/borderimageslice-vs-borderimagewidth 

Friday, February 13, 2015

Mockito for Play 2 Framework

Mocking is great! :)
To use Mockito to mock stuff for your tests in Play 2 Framework do the following:

1. Add mockito as dependency in Build.scala:
val appDependencies = Seq(
    ...,
    "org.mockito" % "mockito-all" % "1.10.19"
)
Find latest version from https://github.com/mockito/mockito/blob/master/doc/release-notes/official.md

2. Add imports to your JUnit java file:
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;

Note the static import of Mockito. This lets you call mock and when without "Mockito." prefix, like most of the tutorials do.

3. Create mocks:
Either by putting @RunWith(MockitoJUnitRunner.class) on your test class and using @Mock for class members. E.g.:
@RunWith(MockitoJUnitRunner.class)
public class HomeControllerTest {

    @Mock
    HomeForm mockHome;

or by creating the mocks in your code:
HomeForm mockHome = mock(HomeForm.class);

4. Set up mock behavior:
List mockNames = (List) mock(List.class);
when(mockNames.get(0)).thenReturn("bob");
when(mockCompany.getNames()).thenReturn(mockNames);


5. Run using play test, you might want to run play clean first to make sure mockito is downloaded.

Nice feature:
If you've used googlemock - Google C++ Mocking Framework and miss the "Uninteresting function call encountered" messages, for example for debugging, you can get verbose output from mocks by adding withSettings().verboseLogging() like this:
HomeForm mockHome = mock(HomeForm.class, withSettings().verboseLogging());

Sources:
http://www.javacodegeeks.com/2013/05/junit-and-mockito-cooperation.html
http://stackoverflow.com/questions/11802088/how-do-i-enable-mockito-debug-messages
http://www.baeldung.com/mockito-behavior

Monday, July 21, 2014

Make your Raspberry Pi wireless

Make your Raspberry Pi wireless and be able to hide it away wherever you have a power outlet handy, just follow these steps:

1. Buy a Edimax EW-7811Un 150M 11n Wi-Fi USB Adapter, great plug and play adapter.
2. Follow the steps on http://www.savagehomeautomation.com/projects/raspberry-pi-installing-the-edimax-ew-7811un-usb-wifi-adapte.html
3. Follow https://www.modmypi.com/blog/tutorial-how-to-give-your-raspberry-pi-a-static-ip-address to set a static IP address

Consider upgrading your software and firmware by following https://raspberrypi.stackexchange.com/questions/4698/how-can-i-keep-my-raspbian-wheezy-up-to-date

Good luck! Have fun with your pi. :)

Tuesday, June 24, 2014

Play 2 framework access files in WAR

So you've created WAR files from your Play project, see Play 2 framework WAR file. But how to fetch files within you WAR file.

I previously used:
new File(play.Play.application().path().toString() + "//mydirectory//myfile.txt");
which works fine when running on the Play "stack".

After exporting to WAR file the path ended up looking in the application home directory, e.g. /home/<runninguser>/.
Still works for files not in the WAR, since they are expected to be found here anyways.

Solution for my WAR files:
InputStream is = Play.class.getResourceAsStream("/mydirectory/myfile.txt"");
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, Charsets.UTF_8);
writer.toString();


Source: http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string and http://stackoverflow.com/questions/6888343/getting-a-resource-file-as-an-inputstream-in-playframework

Note: Jetty will unpack you WAR file to a temp directory, either /tmp or below you application path /home/<runninguser>/ so this is what you are accessing. Remember not to have a script deleting these files as this will crash your web application.

Play 2 framework WAR file

Play 2 framework is a nice framework for writing web applications in Java/Scala. Play runs it's own netty server so you get it up and running by just writing play run. It detects file changes and recompiles classes as needed upon page refresh in development mode.

A small catch is that Play does not natively support running in a container, e.g. Jetty, Tomcat, Glassfish, or JBoss. In fact it doesn't support ServletContext at all as far as I can see. (See http://www.playframework.com/documentation/1.2.2/faq and http://guillaumebort.tumblr.com/post/558830013/why-there-is-no-servlets-in-play)
This is a minus when trying to get started with Play in existing server environments. Luckily Damien Lecan started an open source project to build WAR files from Play, play2war plugin.

Follow https://github.com/play2war/play2-war-plugin/wiki/Configuration to install the plugin.

Basically your Build.scala file should look something like:
import com.github.play2war.plugin._
object ApplicationBuild extends Build {
    val main = play.Project(appName, appVersion, appDependencies)
        .settings(Play2WarPlugin.play2WarSettings: _*)
        .settings(
      // Add your own project settings here 
      Play2WarKeys.servletVersion := "3.0"
    )

}

and your plugins.sbt:
// Use play2war for creating war files using 'play war'
addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.2-beta4")

And hopfully, magic! (Note currently (2014.06.24) only support Play 2.2.1)

Once installed, just run play war and a war file is created for you. In addition you will need a config file for your application, the application.conf in your project folder, and any extra files/folders like the private folder of your project.

Friday, June 6, 2014

Wednesday, May 28, 2014

Add new user in Linux/Ubuntu

To add a new user using command line on an Ubuntu machine there are at least two commands that may be used: useradd and adduser

Use adduser instead of useradd if you are not totally certain useradd is the tool you want to use because:
1. useradd is a low level tool.
2. useradd will not add home directory for new user.
3. useradd will not add many other defaults for new user.
4. adduser is more user friendly (but uses useradd in backend).
5. adduser will create home directory.
6. manpages of useradd recommends use of adduser.

Use it like this:
sudo adduser <username>

and to add a system user which has no shell (cannot log in, but just run programs):
sudo adduser --system <username>
 instead of
sudo useradd <username> -s /bin/false
Using adduser, the system user a home directory will be created.

See http://askubuntu.com/questions/374870/home-directory-not-being-created and http://askubuntu.com/questions/345974/what-is-the-difference-between-adduser-and-useradd for good reasons with links to manpages.

Java Listeners and Adapters, almost anonymous functions

Java allows developers to easily add listeners to different events.
e.g. button.addMouseListener(this);
However, often you don't want to implement a listener interface for your class or add an inner class
MyClass implements MouseListener
MyClass {
    private class ListenerClass implements MouseListener {
            public void mouseClicked(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            .
    }
}

With all the functions required by the interface cluttering up your code. Often you don't even need more than one or two of the functions.

Enter Adapters.
Adapters are classes which are made to match a listeners interface and only that. They do nothing when called, but the developer will override the function he needs:
button.addMouseListener( new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
    }
}


This adds flexibility to Java, almost like the anonymous functions of JavaScript.

Source: https://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters
http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html