Category: Techniques

Hyper-V VMs are not all the same

Hyper-V VMs are not all the same

Hyper-V Ubuntu installOne of the big problems with Hyper-V and Ubuntu in particular is the clipboard or lack of it. I had 18.04 LTS installed with an X Org RDP login. This worked perfectly and I could have a full screen in my Monitor and could copy/paste.  Don’t underestimate copy/paste.

It’s a real PITA if you have to use say WinSCP to copy files over. I think WinSCP is excellent BTW but the amount of labour saving that copy/paste has done since some genius thought it up is immeasurable. That and allowing the full screen of the monitor are two highly important things.

Sadly the 20.04 LTS didn’t seem to allow it. Copy/paste didn’t work between my Windows PC (host) and Ubuntu (guest). There’s nothing worse than losing a feature you’ve grown fond of.

If you follow these instructions for creating a Hyper-V 18.04, you get the screen size popup but not with 20.04 LTS. For that you have to follow these instructions!

It’s things like this that suggest why Linux Desktop has never been that successful. You can waste many hours getting simple things working and sometimes like Copy/Paste they break between versions. And this is with Ubuntu, probably the biggest and best known and supported Distro.

 

Interesting looking Game Handheld device- Odroid-Go

Interesting looking Game Handheld device- Odroid-Go

Odroid-GoThe Odroid-go Game kit looks like a gameboy. It has a LCD, game controllers and the case. It has a CPU that runs between 80 and 240 MHZ, 4MB RAM, WiFi, Bluetooh, a Micro-SD slot, a rechargeable battery – charged through a Micro USB, a built-in speaker and a 320 x 240 LCD. That may not sound very much but all the CBM-64 games ran on that size of screen and it only had 64 KB of RAM.

There’s more information on the manufacturers website (it’s in English though it is Chinese made) and all the useful information is on a Wiki with info on emulators, downloadable games and how to write programs for it using the Arduino programming language which is very much like C/C++. You have to install Arduino for ESP32 first on a Pc (Windows, Linux or Mac) then can you write programs and run them on your Odroid-Go.

There’s a bit of assembling but the website includes instructions with photos. A quick search on Youtube found a video showing how to assemble it.

This is an example of Arduino code, taken from their online reference manual. The Ardunio has been around for several years so there is a lot of code around for it.

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
To brace or not to brace

To brace or not to brace

Abstract programming picture
Image by Gerd Altmann from Pixabay

This isn’t exactly confined to C, in fact it applies to many programming languages where braces or curly brackets {like this} are optional after an if. It even applies to Pascal with Begin ends which are optional after an if.

You can have the first or the second as shown below.

if (expressions) 
  DoSomething;

if (expression {
  DoSomething;
}

I saw a recent example where the DoSomething was a logging expression which the compiler optimised away so the if, which lacked braces applied to the next statement. As the if was only true on rare occasions. It meant that that statement which should have been run every time was only run on those rare occasions.

So the prevailing wisdom and one that I entirely agree with is that you should always use braces. If you don’t you risk accidentally introducing bugs like this.

Note. that link is to a discussion on the C programming Subreddit (on Reddit.com).

.

Adding Security to Web apps and Games

Adding Security to Web apps and Games

Security
Image by Darwin Laganzon from Pixabay

Because I’m developing a server game, data has to flow in both directions. That means it might be read (by ‘tapping’ e.g. using utilities like WireShark) or maybe even spoofed. Obviously this would be a bad thing.

Now I’m obviously not going to say how exactly I plan to protect it. Here are a few ideas.

  1. Encrypt all data. I already do this with an SSL certificate. Apple for example block network connections that aren’t secured.
  2. Include checksums and other ways of checking that the data originated from where it purported to. A poor way of doing this would be to always include a constant value and check for its presence. The idea is good but if someone managed to disassemble an app, they might spot it and it would be game over. The principle is sound but not a constant value.
  3. I like the idea of a time based constant but it needs careful implementation. The idea is that every hour say a new constant is calculated. Now there are several issues with this: how do you derive the constant so that the server and mobile apps know what constants should be? One way would be a pseudo random number generator and there are many algorithms. So long as both client and server (which are programmed in different languages) can manage this then that’ is not bad. Another issue is “time dislocation”. My mobile and server may not be exactly in sync. It might only be a fraction of a second or maybe longer if they are on different time zones.  One way round this is to keep the last say two or three values and check not jut the current one but the one before that as well.  We’re not bothered about the time so much as when the hour changes.
  4. Or a simpler method, just have a list of constant values. And an index which is incremented every hour. It wraps round at the end. This is virtually the same as 3. but without the pseudo random number generator.
  5. Include a secure hash of the main data. This is like a digital certificate created from a document. It guarantees that the document hasn’t been tampered with because the certificate is created from the contents of the document. The only thing here is, the data must include a value from 3 or 4 to verify the document so a spoofer doesn’t just send their own data and a secure hash of that!

 

Adding an SSL Cert

Adding an SSL Cert

SSL connectionThese days, if you have a website or even a game server then you probably should have an SSL (or TLS to be more precise) certificate. Have you heard of telnet? It’s an old protocol that allows you to connect to a remote computer and issue commands. Do you know why you don’t hear of it any more? Because it was designed for an era where hackers didn’t spend all their time attempting to compromise computers. Telnet, like FTP has a flaw. Passwords and login details are sent in the clear. Not hashed, or encrypted.

Why don’t I use SSH to connect to it? I do. SSH has more functionality than SSL and is very good for encrypting remote connections. SSL needs a certificate, whereas SSH doesn’t but many think you should use a SSH certificate as a substitute for username/password and I intend to. If you’re not sure of the technical differences between SSL and SSH, this article isn’t a bad place.

So today I paid for an SSL certificate. I’d pointed a domain I had handy to the vps a few days ago, to give DNS a chance to settle, (24 hours max but usually much less) paid £20 for five years of SSL cert and installed it today. Thankfully, virtualmin which I use for configuring the server makes it straightforward to request a SSL by generating the CSR (Certificate Request an Private Key) . This blog uses an SSL cert from the same place (CheapSSL). Despite the low price the certificates are very good.

Although the world won’t see what the cert is protecting, you almost have to have them nowadays. This is for the connection between smartphone and server. As I found today, Apple is ramping up security and Google is doing the same. I have iOS 14 on my iPhone (upgraded yesterday) and it refused to connect to WiFi in my local coffeeshop. Their certificate doesn’t expire for another month but I suspect it is now over 398 days old. As far as Apple is concerned, that certificate is past its use by date. This is Apple’s new policy since earlier this year. My wife’s iPhone, still on iOS 13 connected quite happily.

For those who have bought a multi-year certificate as I have today, it just means you have to generate another CSR and install a newer certificate once every 400 days or so. I’ve started taking screenshots of the details so I get them correct! I believe Google is moving to this 398 day maximum as well.

So the commands from smartphone to game server are now sent over https and encrypted in flight as are the results. It’s one less thing to worry about.

 

 

How to measure the area of a circle

How to measure the area of a circle

Odd ShapesWell if you remember maths (or math for US readers), you’ll know that the area of a circle is pi X r X r where r is the radius and pi is that 3.14159 number.

But what if you are given a weird shape instead of a circle? Like some of those in the picture.

There’s a method called Monte Carlo because of the casino there. In effect you simulate throwing darts at the shape (say printed out and stuck on the wall). You throw thousands or millions of darts and count how many hit the particular shape and how many darts were thrown in total. You only count those that hit the rectangular paper; those that miss it don’t count.

Then you divide the number of hits by the number thrown, multiply it by the width and height of the picture (which is rectangular or square) and that is a close approximation to the area. In more advanced ,maths/math, this method is sometimes used to calculate the integral of a function. The integral is the area under the function. Some complicated functions are particularly hard to integrate, so using a Monte Carlo method can solve it for you.

I’ll publish a C program to run Monte Carlo on an image in a day or two.

An alternative way of measuring the area is by using recursion. I discussed it in this article Using recursive fill to count maps.

How many riffles are needed to shuffle a deck?

How many riffles are needed to shuffle a deck?

card riffle photoIt fascinates me because 52! is such a large number.  Here it is in full 8.0658* 10^67 or 80,658,175,170,943,878,571,660, 636,856,403,766,975,289,505,440,883, 277,824,000,000,000,000. That is the possible number of ways of shuffling a pack of cards.

It means that when you shuffle a deck of cards, it’s possible that you are the first person on Earth to ever get that particular arrangement. It’s the kind of fact that amazes me. Another one is that it takes a very long time for particles emitted from the centre of the sun to reach the surface and blast into space. On the order of many many years. (Thousands of years!)

Playing cards have only been around maybe 500 years as we know it (52 card deck) though date back to 9th century China for their invention. If there had been a billion shuffles each day during that 500 years, that’s only 1.8 x 10^14 shuffles. That is a minuscule fraction of the possible number of arrangements so the chances are that any shuffled arrangement is new is pretty high.

It’s accepted that seven is the number of riffles needed to perfectly shuffle a pack of cards. A riffle is where you split the deck in two and then merge the two halves back into one deck as in the photo I took.

I proved this once by writing a program to simulate riffles  and looking how far cards have moved after seven. In fact a card at the top of the deck moved to the bottom after only six riffles. I’ll try and write that in C and will publish it here in a day or two.

Other shuffling techniques like smooshing (spreading out all the cards on the table with their backs face up and then pushing them together) are nowhere near as efficient. It’s estimated it can take thousands of smooshes to properly shuffle a pack. It’s not easy to simulate, though one of these days I’ll have a go and see if I can come up with a more accurate estimation.

How to install SDL2 in Visual Studio

How to install SDL2 in Visual Studio

Visual Studio IDEThis is the first of a number of longer-piece game related tutorials. You’ll see I’ve added a tutorials link to the top menu. That page will grow as I add tutorials, as each is added to it .

You’ll see I use the terms SDL and SDL2 mostly interchangeably. SDL is the name of the library but we don’t want the older SDL1 instead we want SDL2 which seems more or less permanently at version 2.0.12.

I’ve left the Visual Studio version off as the process is mostly the same whether it’s Visual Studio 2017, 2019 or future versions. Screenshots are from Visual Studio 2019.

You don’t have to do this on Linux as it takes three or four sudo apt installs to add the various SDL2 dev modules in, but with Windows you need to configure Visual Studio and it can be a somewhat confusing process if you are new to Visual Studio.

Also you need to download and fetch the various files. This is made slightly more complicated because there are 32-bit and 64-bit versions and you want to keep them both so you can switch between the two.

Here are the various steps we have to go through.

  1. Download the various files and unzip them
  2. Setup include and lib paths in Visual Studio
  3. Add the lib files into Visual Studio.
  4. Copy the dlls into the folder where the game will run.
  5. Compile and run it.

What you are downloading are basically three types of files.

  1. Header files., This is files like sdl.h.  Your program will #include these.
  2. Lib files. This is the bulk of the SDL code.
  3. Dll files (Dynamic Link Liobraries). Needed for runtime.

Download the various files and unzip them

The SDL website is libsdl.org and if you click the SDL Releases in the bottom right it will take you to the SDL downloads page. WE don’t need the source code (you are welcome to download it and take a look but it’s not needed to use SDL2.

We do however need the development libraries. These include the runtime binaries so we don’t need to download those. as well. Just the one file SDL2-devel-2.0.12-VC.zip

I suggest you create a folder SDL or SDL2 on your drive. My C: drive is for Windows so I use d: \SDL2

If you unzip the files into there you’ll end up with three folders and five .txt files. Just under 7 MB in total. Other than docs there are include and lib.  The lib folder is further split into x64 (64-bit) and x86 (32-bit) . It also includes the runtime dlls. These will have to be in the path for your program but we’ll leave that until later.

Sounds, Images and Truetype fonts

As well as these, you are probably going to want image file support, sounds and possibly truetype font support in your program. These are separate files in the SDL projects folder.

  1. Image file support. Download the development library file from the sdl_image page. As before you want development library file. SDL2_image-devel-2.0.5-VC.zip.
  2. Sounds file support. Download the development library from the sdl mixer page. It’s SDL2_mixer-devel-2.0.4-VC.zip.
  3. ttf file support. Once again a development library downloaded from the SDL_ttf project page. It’s SDL2_ttf-devel-2.0.15-VC.zip.

All three files have similar structure to the SDL2 dev library.  Unzip the include files into the SDL include folder and the lib files into the relevant X86 and X64 lib sub-folders. So all your SDL files that you need are in the same include and lib sub-folders.

I suggest you extract the file folders one by one, do the three include files first then the x64 files and then the x86. Do not get x86 and x64 mixed up. The only way to tell them apart is by size and it’s not always an accurate way.  Don’t worry if it complains about overwriting zlib1.dll. There’s a copy in both the images and sounds zip files.

Setup include and lib paths in Visual Studio

This can be a bit complicated, just follow these instructions exactly.

To configure a C/C++ project in Visual Studio, you have to specify where the compiler gets its include files, where it finds its lib files and which lib files you want to link to.

Solution ExplorerI’ve created a blank C++ project called sdltest in VS 2019.  Now I actually want it to be a C project so just rename the main file sdltest.cpp to sdltest.c. You need to delete all of the C++ code in that file as well.  After renaming the Solution Explorer should look something like this. We will have a sdltest program to run later so just save this for now. You can get the file from GitHub and overwrite sdltest.c.

Now click Project on the top menu then sdltest properties at the foot of the menu.  You should see this form (below).  This is how you specify properties for your project in Visual Studio.

You’ll see I have selected VC++ Directories on the left. This is where you specify some of the directories (folders and directories mean the same thing BTW) .

But the Platforms pull down probably shows Win32 on yours. Change it to All Platforms. Visual Studio lets you specify configurations for all things or for x86 or x64 separately. We’ll use the same include folders for both x86 and x64 but we’ll specify the paths to the lib files individually as the x64 lib files are in the x64 sub-folder and the x86 files in the x86 folder.

Property Pages
To specify the path click on Include Directories, you’ll see a down arrow appear on the right.  Click it and you’ll see <Edit…> appear, click it and a form like this below will popup.
Visual studio folder editClick on the blue area in the form and you’ll be able to paste or type in the path or click the … button to get a file browser appear. Type in, paste or select the folder then press Ok.  You should now see your path in the folders.

Here I typed in d:\SDL\Include. Be careful that you don’t get rid of $(VC_includePath);$(WindowsSDK_IncludePath); in the include path as I did as your program won’t compile!

folder paths

We now have to do the same for the lib paths.  But first we must change the Platform to specify x86 or x64.

If you change it, a popup will appear asking if you want to save your changes. Click the Yes button.

Confusingly the platform choices on mine are Win32 and x64, but Win32 is the same as x86.

You’ll see that the include path you added shows up in the x86/Win32 platforms because we changed it for all platforms.

Now add the path for Library Directories. Click the down arrow then <edit…> and put in the full path to the folder that matches the Platform. x86 for Win32 platform, x64 for x64 platform. After you’ve entered it will show up in the directories.

Visual studio all paths

If you want both x64 and x86 then change the platform and re-enter it. Don’t forget to save!

Add the lib files into Visual Studio

The last configuration to do is specify the lib files that are needed. We’ve specified the paths for include and lib files but the compiler linker doesn’t know what lib files to link.

As linking depends on 32-bit or 64-bit we have to specify this twice as we did for the lib paths. It’s in a different place in the property pages. Click Linker then Input.

Visual Studio Linker Configuration It’s the top line (Additional Dependencies) that we need to work with. Click into it to get the down arrow then click that and the <edit…> as before.

You’ll have noticed that it comes pre-populated with all the various library .lib files.  We’ll be adding some more. The ones we need are

SDl2.lib SDL2_mixer.lib SDL2_ttf.lib SDL2_image.lib and SDL2main.lib

Add these into the edit box one by one and press return after each one.

After you’ve added them and pressed Ok, you’ll see them in a list. Something like this though I’ve not added SDL2_ttf.lib in to it yet.

As before repeat for both x86 and x64.

 

We’re now ready to compile. Only we need a program to do that. I’m not going to list the whole sdltest as it’s 135 lines but you can download the VS project in the file sdltest.zip from GitHub. It should compile with no errors. If you get errors, please recheck the include folders and lib folders and make sure you have configured them correctly.

So it compiles, but it won’t run. If you look in the Debug folder under the x64 (or Win32 if you built that) , you’ll see a whole lot of files. but only sdltest.exe is important. You can delete the rest. Leave sdltest.pdb if you wish to debug.

We have to

Copy the dlls into the folder where the game will run

That folder is this the \sdltest\x64\Debug folder. We need several .dll files from the same lib folder that holds the x64 libs. (Again if you are on Win32 you need dlls from the x86 lib folder).

What files do we need?

Just SDL2.dll. If we were using images we’d also need sdl2_image.dll and zlib1.dll. We don’t currently need the SDL2_mixer.dll or the SDL2_ttf.dll but if you ever use sounds or Truetype then you’ll need those. For sounds you’ll also need some of the lib*.dll files such as libogg-0.dll or libvorbis-0.dll. For image we might need in the future libjpeg-9.dll (if we ever use jpg files).

So you’ve compiled it and should see something like this when you run sdltest.exe. It doesn’t do much except draw coloured rectangles. Press the esc key to close it. On my POC it draws 100,000 coloured rectangles each 120 x 120 pixels in about a second. That’s pretty fast!

The heart of the program is this function:

void DrawRandomRectangle() {
	char buff[20];
	SDL_Rect rect;
	SDL_SetRenderDrawColor(renderer, Random(256) - 1, Random(256) - 1, Random(256) - 1, 255);
	rect.h = 120;// Random(100) + 20;
	rect.w = 120;// Random(100) + 20;
	rect.y = Random(HEIGHT - rect.h - 1);
	rect.x = Random(WIDTH - rect.w - 1);
	SDL_RenderFillRect(renderer, &rect);

	rectCount++;
	if (rectCount % 100000 == 0) {
		SDL_RenderPresent(renderer);
		stopTimer(&s);
		sprintf_s(buff, sizeof(buff), "%10.6f", getElapsedTime(&s));
		SetCaption(buff);
		startTimer(&s);
	}
}

Uncomment the two lines with 120; // Random(100) + 20; to have it draw random sized rectangles. The figure in the caption is how long it takes to draw 100,000 rectangles.

Completely off-topic but how to tether an iPhone to Windows 10

Completely off-topic but how to tether an iPhone to Windows 10

A PC tethered by two phonesThanks to an apparent hardware failure in my internet modem (power light remains stubbornly off), I found myself without internet except on my iPhone which has 20 GB of 4G data allowance.

Normally in a month I use less that 0.25 GB of the 20 GB $G monthly allowance data because of fast WiFi at home and at work but I do use it for phones and messages.  It’s convenient on rare occasions when I’m out though to have internet access ability on a phone.

Unfortunately for reasons best known to Microsoft or Apple or both, iPhones no longer seem to tether with Windows 10.  They did for Windows 7 and it’s a real PITA.

But there is a way to manage it. Just use an Android phone as well. If the Android phone had mobile data then no problem but even if it doesn’t, it can tether to my iPhone over WiFi. And my PC can tether to the Android phone using a USB cable and that is how this is being brought to you.

How I track ideas

How I track ideas

About twelve years ago I came across WOAS (= Wiki on a Stick). It was a single HTML file notebook with built in JavaScript and you opened it in a browser. It showed a simple interface and you could switch it into edit mode and start adding in text in markdown format. It was very easy to create links to pages in the document and add new pages.

And it was all saved in the document. Also very easy to find the text. It had one excellent feature which I miss, You could have a page self-encrypt using AES-256. Great for holding passwords etc.

I used WOAS to deign software and had at least one very detailed design with several hundred pages each with links to other pages. Sadly WOAS was eventually killed by the browsers themselves, preventing files writing to disk. It’s not the only example of a single-file Wiki but they all suffered the same problem. I think someone came up with a Java shim that did the file writing but it was never the same.

Now I use WikidPad, it’s written in Python and I think just runbs on Windows, (though you wouldn’t know it) which works like WOAS but internally it uses SQLite to hold the Wiki pages.  You can even use their website WikidPad but you have to register first.  That picture is a screenshot of WikidPad.