An SSL Truster

Tim Pizey from Tim Pizey

Should you wish, when testing say, to trust all ssl certificates:


import java.net.URL;

import javax.net.ssl.*;

import com.mediagraft.shared.utils.UtilsHandbag;

/**
* Modify the JVM wide SSL trusting so that locally signed https urls, and others, are
* no longer rejected.
*
* Use with care as the JVM should not be used in production after activation.
*
*/
public class JvmSslTruster {

private static boolean activated_;

private static X509TrustManager allTrustingManager_ = new X509TrustManager() {

public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}

public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
};

public static SSLSocketFactory trustingSSLFactory() {
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{allTrustingManager_}, new java.security.SecureRandom());
new URL(UtilsHandbag.getSecureApplicationURL()); //Force loading of installed trust manager
}
catch (Exception e) {
throw new RuntimeException("Unhandled exception", e);
}
return sc.getSocketFactory();
}

public static void startTrusting() {
if (!activated_) {
HttpsURLConnection.setDefaultSSLSocketFactory(trustingSSLFactory());
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(trustingSSLFactory());
activated_ = true;
}
}

private JvmSslTruster() {
}
}

When a Swift immutable collection isn’t or is at least immutable-ish

Pete Barber from C#, C++, Windows & other ramblings

Take the following code:

 struct Foo  
{
var value: Int
}

let foo = [Foo(value: 1), Foo(value: 2)]

By using 'let foo' an immutable array has been created. As such no members of this array can be replaced and nor can an element's contents be modified. As such both statements below result in compilation errors.

 foo[0] = Foo(value: 777) // error!  
foo[0].value = 8 // error!

If foo were declared var then both of the above statements would work.

This changes slightly when using reference types:

 class Bar  
{
var value: Int = 0

init(value: Int)
{
self.value = value
}
}

let bar = [Bar(value: 1), Bar(value: 2)]

bar[0] = Foo(value: 777) // error!
bar[0].value = 8 // allowed

The first case of trying to replace an element fails as before but modifying the instance referenced by that element is permitted. This is because the immutable collection holds a reference to the instance of Bar. Modifying the instance does not change the reference so the collection remains unchanged.

If you're making an effort to make your code as immutable (const) as possible (I'm from a C++ background so I endeavour to making everything as const I can) then this is a gotcha to lookout for.

The only way to make Bar properly const is to provide a private setter for the member, assuming it's defined in it's own source file (so this example doesn't work in a Plaground), i.e.

 class Baz  
{
private(set) var value: Int = 0

init(value: Int)
{
self.value = value
}

func f()
{
value = 88;
}
}

Which now prevents value being assigned too.

 let baz = [Baz(value: 1), Baz(value: 2)]  
baz[0].value = 8 // error!


Even if all the properties have private setters there might be methods on the reference type that modify the instance, such as f() above. Just having an immutable collection of reference types is not sufficient to stop these mutating the instances referred too. Invoking f() in the above collection will change the value to 88, i.e.

 println("\(baz[0].value)") // Gives 1  
baz[0].f()
println("\(baz[0].value)") // Gives 88


This differs to C++ where if a collection is const or is returned as a const reference (from a method) than not only is the container immutable but so are its contents. It would be good if Swift were to gain a mechanism that would mark the collection and its contents completely immutable other than having to use a value type.

Anyway, beware of making a collection of reference types immutable and assuming that both the collection and its contents cannot be modified!

Visual Studio 2013, PC-lint and C++ 11 Variadic Templates

Products, the Universe and Everything from Products, the Universe and Everything

Although we added support for Visual Studio 2013 some time ago, PC-lint has lagged behind somewhat and even now (well over a year after it was released) has difficulty analysing any projects for it which use the Standard Template Library (STL) to any significant extent. In large part this is due to the fact that PC-lint has to date lacked support for C++ 11 variadic templates (which are heavily used in parts of the Visual Studio 2013 system headers). With PC-lint 9.00L (the current patch level) even a simple #include <map> will trigger an internal error (9.00k was less vocal, but still raised errors you had to suppress). Although this was not a huge problem when Visual Studio 2013 first came out (most development teams take their time moving to new versions of Visual Studio), it is now sufficiently mature that many teams are moving to it, and that's potentially a big problem if you also use PC-lint. The arrival of the free Visual Studio 2013 Community Edition has of course accelerated this trend. Although we were expecting this to have been fixed by Gimpel around the middle of last year they apparently found that doing so proved to be far trickier than anticipated, with the end result that this limitation has become an increasingly large problem. The latest information we have is that there will be a beta with full support for variadic templates available sometime in March, so at least there is now some light at the end of this particular tunnel. However, that does probably mean that there won't be a complete "production" fix for at least a couple of months after that. Hence we have been looking at potential workarounds (with one of our customers who is in the process of moving their codebase to Visual Studio 2013 and has run into this issue) to see what we can do in the meantime. The most promising approach we have identified so far is actually very simple - just substitute the system headers for an earlier version of Visual Studio while analysing Visual Studio 2013 projects by modifying the -i directives for the system headers, while leaving the rest of the analysis configuration unchanged. The major caveat is of course that you need to have an earlier version of Visual Studio co-installed, but in practice that's pretty common. The second caveat is that you may run into problems if you are using STL functionality (e.g. std::make_unique) which is implemented in the Visual Studio 2013 system headers but absent from earlier versions. Even then, there are workarounds in some cases - it really depends on what you use in your projects. It also goes without saying that the workaround can't handle any code you write in your own projects which uses variadic templates directly. Given all that however it does seem to work rather well (it even seems to make it practical to analyse Visual Studio 2013 projects with PC-lint 8.0, which is an unexpected bonus!) and as a result we've decided to build this into Visual Lint so that it can take care of it automatically (but optionally, of course) for you when it determines that you are using PC-lint 9.00L or earlier. For now we've limited it to using the system headers from a Visual Studio 2012 or 2010 installation on the same machine, but we can extend that if needed. This functionality should be out as part of Visual Lint 4.5.9.239 soon, but we are happy to release preliminary builds on a case by case basis if it will help other teams who are running into the same problem. Likewise if you have any questions about the specifics of this approach or are running into this issue (not necessarily just with Visual Studio) just let us know and we will be happy to help. Update: The build is now available. Download Visual Lint 4.5.9.239

Book review: Swift Essentials

Pete Barber from C#, C++, Windows &amp; other ramblings

Disclaimer


I was asked to review: Swift Essentials by Alex Blewitt from Packt Publishing (I'd previously reviewed another book of theirs for the ACCU) and ideally publicise the review. In return I was given a free copy of the eBook and offered another free eBook of my choice upon publication of this review. However, no pressure was exerted and nor was any editorial control requested or given.

In short


It's a good book that provides a more than basic introduction to iOS development using Swift. My major criticism is the title, it does not do the book justice. The sub-title 'Get up and running lightning fast with this practical guide to building applications with Swift' is a far better description. This book is ideal if you're already able to program but would like to learn about iOS development with Swift rather than with Objective-C. It's more about learning iOS app development with Swift rather than about Swift.

In long


The offer to review this book came at good time for me. I'd read quite a lot of the Swift Programming Language book, read many blog articles, attended most of the Swift London meet ups (which incidentally gets a mention in the resource section of the book; so I may have inadvertently met the author) and published my first iOS App written entirely in Swift, a game called Boingy Splat. Therefore I was interested to see what someone else made of the language itself, working with it to create iOS apps and importantly to see parts and techniques I'd missed.

The books takes you from doing mainly pure Swift using REPL on the command line and then introducing and using Playgrounds to implementing a full app, albeit without persisting any data. Smaller apps demonstrating features that will be used in the final app are created along the way. These are small and snappy and allow something concrete to be created along the way, quickly! There is a section on creating Playground packages and adding documentation that seems far from essential; interesting though.

Some of the first chapter introducing the fundamental types and constructs can get a bit dull if you've been there with other languages but it's information that needs presenting. Importantly as soon as possible the Swift idioms (iteration, containers, enums, let versus var etc.) are presented. This is the information that existing developers need.

The Playgrounds chapters introduces a little Cocoa Touch by the way of displaying images. Other than the choice of the author's face as the content (ironic rather than egomaniacal I hope :-)) it's good to be already manipulating the OS with Swift rather than just 'doing' Swift.

From chapter 3 onwards (there are 7 in total) the focus switches to creating apps. The most important concepts (that will allow you to search for and understand more detailed documentation and blogs) are introduced, i.e. Table Views, Master-Detail, Storyboards (and creating purely programmatic views), Custom Views, MVC architecture and accessing remote data. No time is spent on app signing etc. which is an understandable omission but a mention and a reference could prove useful for those very new to iOS development.

The later chapters tend to introduce a new iOS features and new Swift feature making use of one with the other. Even Unit Testing gets a mention when introducing classes and using mocking as example of sub-classing. Likewise full and practical use of Swift's enums and extension methods are given in the remote data chapter.

I was pleased to see Storyboards getting central billing for creating UIs as this is now more or less de rigueur and was always my issue with the Big Nerd Ranch book. The use of Segues is also covered along with how to create the UI using Interface Builder. In this chapter and the rest of the book a fair amount of time is spent showing how to pass data from from View to another. It's a shame the Singleton anti-pattern is presented as a way to share data in the final program especially given the coupling this causes which makes Unit Testing as advocated earlier in the book hard to accomplish.

As this is a new book it was good to see it tackle Auto Layout and not just from the Interface Builder perspective but go so far to explain and use the Visual Format Language. It's quite a feat to present this succinctly and not just cop out with a reference to the official documentation. It's this information that takes a somewhat scary area of iOS development and removes the fear.

The remote data chapter is good in that talks about synchronous versus asynchronous calls and makes use of Swift Closures for the callbacks. It covers useful details such as having to update the UI on the main thread versus performing work on others and shows the mechanisms to achieve this. A small library of useful methods that can be used outside of the book is created in the process. Again, this isn't super detailed information but it's setting new iOS developers on the right course allowing common areas of pain and confusion to be avoided.

Other than title the I have only a couple of criticisms. Firstly, I kept finding references to things either just before they were presented or to unhighlighted aspects of the code. This suggested that in order to keep the size of the book down that various pages had been chopped but less than perfect re-editing had occurred. I was able to reconcile all of these but it meant spending time flicking back through pages. Secondly, in a similar vein whilst the book contains screenshots there are sections where some intermediate screenshots or those of the final effect would aid the description. It's arguable as to whether the persistence of data is an 'essential'. I think it would have been worth taking the page count to 250 (from the current 228) to cover basic persistence; 2nd edition?

Formatting


I read the eBook on iPad mini 2 using the Kindle reader app (mobi format); I haven't seen the paper version.

For technical eBooks, especially to be read on anything smaller than a full size tablet means the formatting, especially of the code is very important. The text is laid out well and most of the code is split-up so the differences between text and code highlight the other which works well. There were a few times when I needed to switch to landscape mode to make the code more readable.

Towards the end where a full program in larger sections is presented it breaks down as there is little text on the same page. Different colours would have been useful for the comments and given the use of inline lambdas (for asynchronous calls) then some other formatting or again another colour would have helped separate these from the code consuming them; though I did notice some use of bold. The use of ANSI rather K&R style braces (though this seems preferred by Apple and is more compact) may have help readability.

Conclusion


When Swift was first released (June '14) a lot of people thought that learning Swift would make then iOS developers whereas the real challenge (other than learning how to program) is to learn how to program against iOS. At that time learning just Swift by itself as a first language had no real benefit especially as all the books and blog articles used Objective-C plus the Cocoa Touch APIs were still rather Swift unfriendly.

Whilst knowing Objective-C is probably essential for a full-time iOS developer today and a basic knowledge will be useful for a long time to come, 8 months down the line learning iOS development just with Swift is extremely viable. This book will allow you to do this. It's not as comprehensive at the de facto book for learning iOS development: Big Nerd Ranch's iOS Programming but it is more than sufficient, uses the latest language and covers features introduced with Xcode 6, e.g. Auto Layout and demonstrates app development along the lines of how Apple sees it, by using Storyboards and Auto Layout. It's also significantly shorter!

Whilst it doesn't cover everything and what it does cover doesn't go into great detail it introduces and uses most of the key concepts of both Swift and iOS. To write an app you'll still need to read and refer to the official documentation and read blogs etc. but after reading this book there will not be much that is alien to you.

I'd recommend this book if you can already program and would like to learn how to develop for iOS. If you already know iOS but would like to learn Swift with familiar examples and see how to access the Cocoa APIs using Swift then this is also a good book. Even if you can't program and aspire to iOS development then this is a book that you could pick up and get a long with pretty soon after you'd got to grips with the basics of programming.

I think it is possible for this to become the 'go to' book for starting iOS development.

Restoring user groups once no longer in sudoers

Tim Pizey from Tim Pizey

Ubuntu thinks it is neat not to have a password on root. Hmm.

It is easy to remove yourself from all groups in linux, I did it like this:

$ useradd -G docker timp

I thought that might add timp to the group docker, which indeed it does, but it also removes you from adm,cdrom,lpadmin,sudo,dip,plugdev,video,audio which you were previously in.

As you are no longer in sudoers you cannot add yourself back.

Getting a root shell using RefiT

What we now need to get to is a root shell. Googling did not help.

I have Ubuntu 14.04 LTS installed as a dual boot on my MacBookPro (2011). I installed it using rEFIt.

My normal boot is power up, select RefiT, select most recent Ubuntu, press Enter.

To change the grub boot command instead of Enter press F2 (or +). You now have three options, one of which is single user: this hangs for me. Move to the 'Standard Boot' and again press F2 rather than Enter. This enables you to edit the kernel string. I tried adding Single, single, s, init=/bin/bash, init=/bin/sh, 5, 3 and finally 1.

By adding 1 to the grub kernel line you are telling the machine to boot up only to run level one.

This will boot to a root prompt! Now to add yourself back to your groups:

$ usermod -G docker,adm,cdrom,lpadmin,sudo,dip,plugdev,video,audio timp

Whilst we are here:

$ passwd root

Hope this helps, I hope I don't need it again!

Never use useradd always use adduser

Call for Papers: C++ track at NDC Oslo 2015, June 17-19

olvemaudal from Geektalk

There was a lot of interest for the very strong C++ track that we did at the NDC conference in Oslo last summer. Here is a summary I wrote after the event, including links to the videos that we recorded.

We are repeating the success this year, June 17-19. A few big names has
already been signed up, but we also need your contribution. If you
would like to be part of the C++ track this year, please submit your
proposal soon. The CFP closes February 15. Feel free to contact me directly if you have any questions about the C++ track.