Friday, September 22, 2006

Platform detection II: Is your app running on Smartphone or Pocket PC?

While both Smartphones and Pocket PCs are based on Windows Mobile, there are some very important differences for developers who are targeting both platforms.  Not the least of which are lack of LinkButtons and other clickable elements on Smartphones (since they have no touch screen).  In this post I show how to detect whether your app is running on a Smartphone or a Pocket PC style Windows Mobile device.

It is a simple call to SystemParametersInfo to find whether you are running on a Smartphone or a Pocket PC.  You need a few constants defined and the P/Invoke marshaling code to make it work from managed code however.

This post builds on the first post in the Platform Detection series.  You'll need to build on the code from that post for this post to compile and run.  Like the last post, this code uses partial classes, so you can copy and paste the previous post's code into one file and this code into another (removing the first post's Main method) and your project will compile and run.

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text;

namespace PlatformDetection
{
internal partial class PInvoke
{
public static string GetPlatformType()
{
StringBuilder platformType = new StringBuilder(50);
if (SystemParametersInfo4Strings((uint)SystemParametersInfoActions.SPI_GETPLATFORMTYPE,
(uint)platformType.Capacity, platformType, 0) == 0)
throw new Exception("Error getting platform type.");
return platformType.ToString();
}
}
internal partial class PlatformDetection
{
public static bool IsSmartphone()
{
return PInvoke.GetPlatformType() == "SmartPhone";
}
public static bool IsPocketPC()
{
return PInvoke.GetPlatformType() == "PocketPC";
}
}
class PlatformProgram
{
static void Main(string[] args)
{
string platform;
if (PlatformDetection.IsSmartphone())
platform = "Smartphone";
else if (PlatformDetection.IsPocketPC())
platform = "Pocket PC";
else
platform = "Other WinCE";
MessageBox.Show("Platform: " + platform);
}
}

}

This is the second post in a series of three on platform detection.  Coming up next: detecting the presence of a touch screen.

Monday, September 18, 2006

availability-management.com ripping off my blog

availability-management.com has been ripping off my blog and posting it as their own.  No credit is given (a tiny link to the original).  They are using it to boost their search results to a page of theirs that is nothing more than advertising to various pages.  They don't leave any contact info for themselves so that I contact them either.

They seem to be affiliated or sponsored by http://theartofservice.com.  Whatever.  Service?  More like... ripping off other people's copyrighted works in order to promote their own advertising.

So far I've found five entire blog posts that they host as their own.  Grrr.....

http://availability-management.com/how-i-find-performance-bottlenecks-in-my-aspnet-projects.htm
http://availability-management.com/microsoft-2005-launch-events-in-orem-and-slc-areas.htm
http://availability-management.com/enabling-log4net-in-net-20.htm
http://availability-management.com/betas-2005-unleashed.htm
http://availability-management.com/vp-of-ucnug.htm

I'm not making these hyperlinks to avoid boosting their page ranking.

Friday, September 15, 2006

Platform detection I: How to detect that your app is running in the emulator

When you develop your Windows CE or Windows Mobile application in .NET Compact Framework, you probably do a lot of testing on the Microsoft Device Emulators for Smartphone and Pocket PC.  Here I describe how to detect whether your program is running on an emulator or a physical device.

Microsoft's Device Emulator gives itself away through a WinCE API called SystemParametersInfo when you pass in the argument SPI_GETOEMINFO.  We'll use this to check for the emulator.  When we detect something other than the Microsoft value, we must be running on a physical device. 

I use partial classes because in later posts in the Platform Detection series I'll add more to these classes.

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text;

namespace PlatformDetection
{
internal partial class PInvoke
{
[DllImport("Coredll.dll", EntryPoint = "SystemParametersInfoW", CharSet = CharSet.Unicode)]
static extern int SystemParametersInfo4Strings(uint uiAction, uint uiParam, StringBuilder pvParam, uint fWinIni);

public enum SystemParametersInfoActions : uint
{
SPI_GETPLATFORMTYPE = 257, // this is used elsewhere for Smartphone/PocketPC detection
SPI_GETOEMINFO = 258,
}

public static string GetOemInfo()
{
StringBuilder oemInfo = new StringBuilder(50);
if (SystemParametersInfo4Strings((uint)SystemParametersInfoActions.SPI_GETOEMINFO,
(uint)oemInfo.Capacity, oemInfo, 0) == 0)
throw new Exception("Error getting OEM info.");
return oemInfo.ToString();
}

}
internal partial class PlatformDetection
{
private const string MicrosoftEmulatorOemValue = "Microsoft DeviceEmulator";
public static bool IsEmulator()
{
return PInvoke.GetOemInfo() == MicrosoftEmulatorOemValue;
}
}
class EmulatorProgram
{
static void Main(string[] args)
{
MessageBox.Show("Emulator: " + (PlatformDetection.IsEmulator() ? "Yes" : "No"));
}
}
}

This is the first post in a series of three on platform detection.  Coming up next: discerning between Smartphones and Pocket PCs.

Windows and Linux

This article is intended to be a store for some fair comparisons between the Windows and Linux operating systems.  It's not a Windows versus Linux document.  Comments are allowed, but if they contribute to or alter the facts in this article they may be removed after their suggestions have been applied to the body of the document. 

In the spirit of avoiding flamebait, I will write the facts (as I see them) and not my take on which approach is better.  I certainly have my opinions, but I want this to be more useful to others than just a rant.

Security

I won't cover individual security exploits here.  Instead I will cover common practices and security design and features of the platforms.

File system

Windows has one primary file system: NTFS.  Linux has many, but the security capabilities of the popular ones (ext2, ext3, reiserfs) are all the same (to my knowledge).  So this discussion will use ext2 wherever a specific file system needs mentioning, but I believe it applies to all Linux file systems.

Linux

Linux file system security allows for three individual permissions that can be set on a file or folder: read, write and execute.  Every file has an owner and an owning group.  The three permissions (which are abbreviated rwx) can be set individually for the owner, the owning group, and everyone else (called other).  In this way the owner can be given full control over a file, a group of individuals can have a different set of permissions, and everyone else still another. 

One of the quirks of this security model is that although a user may not have any permissions at all over a file, if a user has write permissions to parent directory he/she can still delete the file.  You also cannot give a user modify permission to a file while denying permission to delete the file.  Since execute is one of the permissions, security and linux' concept of an executable program become blurred.  Any file can be marked as executable by changing the permission set on it.  Thus granting "full control" to someone for a whole directory of files is a bad idea, as you mark them all as executables even if they are data files.

Recently support for ACLs have been added to the linux kernel to allow rwx permissions to be set for any combination of users and groups for any file or folder.  While you are still limited to the simple read, write, execute permissions, being able to allow some individual to read your file without allowing others to also is a very useful feature.  This feature isn't very visible in bash, and to use them the feature must be turned on and utilities to assist in setting the ACLs installed.

An NTFS partition mounted in Linux has only a single owning user and owning group, and as such only a single set of read/write/execute permissions can be applied to the entire drive.  The ACLs set on the partition from within Windows are ignored.

Windows

NTFS supports a very rich set of permissions for file and folder access: full control, traverse folder / execute file, list folder / read data, read attributes, read extended attributes, create files / write data, create folders / append data, write attributes, write extended attributes, delete, read permissions, change permissions, take ownership.  That's the advanced set.  The more common set are: full control, modify, read & execute, read, write, and special permissions. 

These permissions can be applied for individual users and groups, and as many of them as you need to share the file with exactly who you need to.  Uniquely, NTFS offers the "deny" setting for any of these permissions, allowing you to (for example) allow Everyone to Read your file except the user "Denny" with only two ACLs.

With the proper driver, a Windows computer can mount a linux partition.  Within Windows, all permissions on the linux partition are ignored and everything is freely accessible. 

User accounts

Windows

Windows is configured to encourage different user accounts for each administrator.  Although Windows comes preconfigured with a single Administrator account, it is easy, encouraged, and even automated (for XP) to create an individual administrator account for each person who needs one.  This helps ensure that system logs can accurately identify which admin did some action to the system.

Linux

In every Linux system I have encountered, it was normal and accepted that every admin knew the password to root.  Administrators would (hopefully) log in as regular users for most of the time, and then sudo just for those tasks that require admin privileges.  The way root is shared across the whole team seems to neutralize the benefit of log files that can identify who did what. 

Now I am looking for Linux user feedback here: I've been told that logs track who sudo's (from what account it was invoked), so that even though everyone does it, their actions are individually tracked.  I'm curious if this is true.  Also, if I'm a member of the wheel group, does that just mean I can sudo using the root password, or my own?

Protection for and from administrators

Linux

Once an admin logs in and sudos to root, some Linux distributions print a statement similar to "be good, respect privacy".  That simple request is the only thing between a root user on a *nix system and every file of any user's on that computer.  As root, no file system permission stands between you and reading, writing or deleting a file.

Linux encourages users to log in with normal, unprivileged accounts and sudo when necessary to install or run applications that require superuser privileges.  This lends to a secure system because admins are less likely to accidentally make system changes that affect other users or infect the whole system with a virus when they are logged in as a normal user.  Recently desktop managers make sudoing transparent by automatically popping up a password box when starting up system configuration applications. 

In addition, most Linux applications are designed to run with standard user privileges.  As a powerful example, User-mode Linux allows an ordinary user to emulate a self-contained Linux system (complete with internal admin privileges) without the overhead of a VM.

Windows

Administrators in Windows can't just read all files on the hard drive as root can on Linux.  If the NTFS permissions do not allow for Administrators to access files, an administrator must Take Ownership of the file (and reset permissions in the process) in order to access the file in any way.  The brilliance behind this is that while taking ownership of a file is possible for an administrator, giving ownership is not.  This means that while the admin may be able to read my files without my permission, I will definitely be able to find out by noticing that I am no longer the owner of my own files.  Besides the logs that can be kept for admin privileged actions like reading privileged files, this is a sure way that any user can be alerted to the prying eyes of administrators.

All the way through Windows XP and Windows Server 2003, almost everyone needs an administrator account on Windows to be able to get things done.  Whether that is installing applications or even running applications.  Running apps really shouldn't require admin privileges for most cases, and the fact that many do is the fault of the app developer.  The downside to Windows is that since it is a cold hard fact that these admin-requiring apps exist, everyone logs in as administrator all the time.  This leaves them open to virus attacks that can infect the whole system. 

Windows Vista changes this by introducing User Account Control, allowing anyone to log in with their administrator account, but you only have admin privileges when you need them and you explicitly approve each action.  Vista is not released yet, but early responses seem to agree that the popup boxes can be annoying.  It's all for the best though, right? :)

Patches

Some may point out that Windows has fewer or more patches than Linux, or that Linux delivers them faster, or that one's security exploits are more critical than others... yada yada.  Again, the point of this article is to describe design (read: potential) of each operating system.  Every complex system will have vulnerabilities.  And each will have seasons when a rash of exploits will be discovered.  So please don't post your comments on your opinions of which OS is more secure based on the individual patches it needs.

Windows

Windows is patched via the Microsoft Update site, which can patch both Windows and Office, and perhaps other Microsoft apps in the future.  These are made available on a fixed schedule (second Tuesday of each month), except for the occasional update that Microsoft deems critical enough to release in between these days.  Unless you are visiting Microsoft Update on that Tuesday, your copy of Windows will likely discover the update is available some days after it becomes available (probably to ease the download toll on Microsoft's servers).

Other apps can choose to implement their own automatic patch mechanisms.  Microsoft's .NET platform includes some great tools for software installation and patching, if your apps happen to use that platform and those features.  Most apps don't, however.

Linux

The linux patch mechanism varies with the distribution, but all the distros I've tried (Debian, Ubuntu, SuSE, Red Hat, Gentoo) have package managers that connect to some open source repository maintained by volunteers to get updates for just about any open source software you may be running on your computer.  This works as long as you used that package manager to download the software in the first place. 

These updates can vary from stale to bleeding edge depending on what server you choose to point at and the distro.  In my experience, for example, Gentoo tends to get new releases of software within a day or two of its release, whereas the others tend to be weeks or even months later.  There are system stability tradeoffs with being the first to accept updates, of course.

Administration

Background processes

Both Windows and Linux offers two ways for your application to be running in the background.  For an application with a UI, you can minimize the app (including to a small tray area icon).  This section will focus on the second kind--the one without an UI.  In Windows we call them services.  In Linux we call them daemons.

Windows Services

Windows services are written against a specific API and follow strict rules regarding UI, logging, handling system events (shutdown, restart, etc.) and security.  As a result, all services show up in a single management console where an admin can start, stop, pause, disable, and otherwise adjust each service. 

Linux Daemons

Linux daemons are just ordinary linux processes that happen to run in the background without a UI, and usually have a controlling script available in /etc/init.d (or wherever your particular distro chooses to put them).  Recently the desktop managers have been helping to consolidate management of these daemons by offering a tool that lists those services that play by their rules (or that the desktop manager is specifically written to handle).  Some services may not be listed though.

Configuration

Configuration can vary for any app on either operating system.  But each operating system tends to attract app developers who prefer a specific style for allowing their applications to be configured.  So this section necessarily generalizes the topic to overall feeling and common everyday experience.

Windows

At its core, Windows uses configuration files (mostly XML files now) and the Registry to control the operation of the OS and its applications.  Most apps leverage the registry's capability to store settings per machine and per user, and as a result one can predict where and in what format an applications settings will be fairly accurately.  But administrators and normal users will usually use the more user-friendly GUI interfaces that offer most or all of the same flexibility (as directly editing the registry) but at a faster pace. 

Windows has a reputation for needing to restart the whole OS for fairly common (though not regular routine) configuration changes.  On the other hand, most of your day-to-day configuration changes won't even require a process restart if you use the GUI to make the change.

Linux

Linux has a much more freestyle mode for configuration files.  User-specific settings are usually found in files starting with a period in the user's home directory, or in subdirectories that start with a period.  The starting period is a hint to command shells that these files should be "hidden" unless specifically asked for.  System-wide settings are usually found within the /etc directory.  Regardless of where they are found or whose settings they store, configuration file formats vary widely.  XML formats are not very common.  Plain text files with [headings] and key=value lines are very common.  Then you have the XML-text hybrid that (for example) Apache uses.  These files can be touchy, and a misplaced character can break parsing the entire file and keep your process from running at all until you fix the problem.

Changing configuration files in linux almost always requires restarting whatever process reads that configuration file in order for the changes to take effect.  Depending on the configuration file you change, you may have to restart a core OS process.  If you know the right commands, you can restart virtually everything except the kernel itself without restarting the computer.  This helps minimize downtime.

System and application logs

Linux

Linux applications log to text files.  Some of these logs include escape codes that allow these plain text files to colorize their text for easier human searching.  They are usually readable while the logged application is still running, and can even be deleted at runtime as well for some applications.  Cron scripts can be set up to automatically rotate and archive log files to keep them small, or even alert an administrator if interesting activity is logged.

I don't know anything about configuring security logging.  If anyone can educate me, I'll fill this paragraph in with something more interesting.

Windows

While any program can generate a log file anywhere, Windows does encourage app developers to leverage their Windows Event Log system.  These logs are centralized, can be protected, rotated, archived, backed up, programmatically parsed, and perused while the logged application is still running.  Any number of logs and applications can be set up with their own space within the Windows Event Log.   

Security logging is configurable all from one location, and allows a very high degree of control over what gets logged and what doesn't.