summaryrefslogtreecommitdiffstats
path: root/windows/bootpgm/win32/computername.cpp
blob: 19d5bdeb953a56f78ad1636bb38a50cdb867c214 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/* The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * The Initial Developer of the Original Code is Johannes Rudolph.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 * 
 * Contributor(s): 
 *    Johannes Rudolph <johannes_rudolph@gmx.de>
 */ 

/*
File: computername.cpp
functions to change the computer name in the Windows registry
*/

#include "stdafx.h"
#include "io.h"
#include "main.h"

WCHAR KeyNameBuffer[]        = L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName";
WCHAR KeyNameBuffer2[]        = L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName";
WCHAR Tcpip[]        = L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters";
WCHAR ComputerNameBuffer[]    = L"ComputerName";

/*
Function: setRegistryValue

Parameters:
io: reference to <IO>-Controller
*/
void setRegistryValue(IO &io,WCHAR *keyName,WCHAR *valueName,WCHAR *value)
{
	Indenter i(io);
	UNICODE_STRING KeyName, ValueName;
	HANDLE SoftwareKeyHandle;
	ULONG Status;
	OBJECT_ATTRIBUTES ObjectAttributes;
	ULONG Disposition;

	//io.print("Schreibe Registry-Key ");

	//DbgBreakPoint();
	//
	// Open the Software key
	//
	NT::RtlInitUnicodeString(&KeyName,keyName);
	InitializeObjectAttributes(
		&ObjectAttributes,
		&KeyName,
		OBJ_CASE_INSENSITIVE,
		NULL,
		NULL);
	Status = ZwCreateKey(
		&SoftwareKeyHandle,
		KEY_ALL_ACCESS,
		&ObjectAttributes,
		0,
		NULL,
		REG_OPTION_NON_VOLATILE,
		&Disposition);

	CHECK_STATUS(Status,Öffnen des Schlüssels)

	NT::RtlInitUnicodeString(&ValueName,valueName);

	Status = ZwSetValueKey(
		SoftwareKeyHandle,
		&ValueName,
		0,
		REG_SZ,
		value,
		(wcslen( value )+1) * sizeof(WCHAR));

	CHECK_STATUSA(Status,Setzen des Schlüssels);

	Status = ZwClose(SoftwareKeyHandle);

	CHECK_STATUS(Status,Schließen des Schlüssels);
}

/*
Function: setComputerName
sets the computer name in the registry to the specified one

Parameters:
io - reference to the <IO>-Controller
computerName - the designated computer name as UNICODE string
*/
void setComputerName(IO &io,WCHAR *computerName)
{
	Indenter i(io);
	io.println("Setze Computernamen ");
    setRegistryValue(io,KeyNameBuffer,ComputerNameBuffer,computerName);
    setRegistryValue(io,KeyNameBuffer2,ComputerNameBuffer,computerName);
    setRegistryValue(io,Tcpip,L"Hostname",computerName);
    setRegistryValue(io,Tcpip,L"NV Hostname",computerName);
}
/*
Function: setComputerNameCmd
command line command for setting the computer name manually

Parameters:
io - <IO>-Controller
args - command line argument string
*/
void setComputerNameCmd(IO &io,char *args)
{
	Indenter i(io);
	if (strlen(args)<2)
	{
		io.println("Syntax: setComputerName <newComputerName>");
		return;
	}
	io.print("Setting Computer Name to: ");
	io.println(args+1);
	setComputerName(io,io.char2wchar(args+1));
}

#define RETURN_NULL_IF_STATUS_UNSUCCESSFULL if (Status!=STATUS_SUCCESS) return 0;

/*
Constant: whitespaces
defines whitespace character group, each char of this array
designates one white space character
*/
const char whitespaces[]=" \t\n\x0B\f\r";

/*
Function: isWhitespace
Helper function for regexp parser. Tests if c is white space.

Parameters:
c - character to test

Returns: 
true if character is white space as defined in <whitespaces>
*/
bool isWhitespace(char c)
{
	for (int i=0;i<sizeof(whitespaces);i++)
		if (whitespaces[i]==c)
			return true;

	return false;
}
/*
Function: isCapitalLetter
Helper function for regexp parser. Tests if c is a capital letter.

Parameters:
c - character to test
*/
bool isCapitalLetter(char c)
{
	return c>='A'&&c<='Z';
}
bool isDigit(char c)
{
	return c>='0'&&c<='9';
}
bool isSmallLetter(char c)
{
	return c>='a'&&c<='z';
}

bool isWordCharacter(char c)
{
	return isDigit(c)||isCapitalLetter(c)||isSmallLetter(c)||c=='-';
}
bool char_matcher(char c,char d)
{
	return c==d;
}
//const char pattern[]="Computername:\\s+(\\w+)";
/*
Constant: pattern
regular expression pattern which defines the place in a file
to read the computer name from.

The computer name will be the match for the first bracketed expression.

Example:
: <computername\\s+param=\"(\\w+)\"
will match *test* in *<computername param="test" />*
*/
const char pattern[]="<computername\\s+param=\"(\\w+)\"";

/*
Function: parseComputerNameFile
uses <pattern> to find a match in the buffer

Parameters:
io - <IO>-Controller
buffer - source buffer
length - length of source buffer

Returns:
a string containing the match or 0 otherwise
*/
char *parseComputerNameFile(IO &io,char *buffer,unsigned int length)
{
	int patternpos=0;
	int capture_start=-1;
	int capture_end=-1;
	void *matcher=0;
	char lastData=0;
	for (unsigned int i=0;i<length;i++)
	{
		bool matched=true;
		switch (pattern[patternpos])
		{
		case '\\':
			patternpos++;
			switch(pattern[patternpos])
			{
			case 's':
				matcher=isWhitespace;
				lastData=0;
				break;
			case 'w':
				matcher=isWordCharacter;
				lastData=0;
				break;
			}
			break;
		case '(':
			capture_start=i;
			patternpos++;
			matcher=0;
			continue;
		case ')':
			capture_end=i;
			patternpos++;
			matcher=0;
			continue;
		case '+':
			matched=true;
			while (matched)
			{
				if (lastData!=0)
					// use binary matcher
					matched=((bool(*)(char,char))matcher)(buffer[i],lastData);
				else
					// use unary matcher
					matched=((bool(*)(char))matcher)(buffer[i]);

				if (matched&&i<length)
					i++;
			}
			if (i>0)
				i--;
			patternpos++;
			continue;
		default:
			lastData=pattern[patternpos];
			matcher=char_matcher;
			break;
		}

		matched=false;
		if (lastData!=0)
			matched=((bool(*)(char,char))matcher)(buffer[i],lastData);
		else
			matched=((bool(*)(char))matcher)(buffer[i]);

		if (matched)
			patternpos++;
		else
			patternpos=0;
	}
	if (pattern[patternpos]==')')
		capture_end=length;

	if (capture_start!=-1&&capture_end!=-1)
	{
		int matchlength=capture_end-capture_start;
		char *returnBuffer=(char*)io.malloc(matchlength+1);
		memcpy(returnBuffer,buffer+capture_start,matchlength);
		returnBuffer[matchlength]=0;
		return returnBuffer;
	}
	else
		return 0;
}

void testMatcher(IO &io,char *args)
{
	char string[]="Computername:      ";
	char *return0=parseComputerNameFile(io,string,sizeof(string));
}

/*
Function: readComputerNameFromFile
reads the computer name from the specified file, uses <pattern> to 
find computer name in it

Parameters:
io - <IO>-Controller
fileName - reads computer name from this file

Returns:
UNICODE string containing the new computer name, 0 in case of error or if 
the name couldn't be found
*/
wchar_t *readComputerNameFromFile(IO &io,wchar_t *fileName)
{
	Indenter i(io);
	NTSTATUS Status;
	UNICODE_STRING UnicodeFilespec;
	OBJECT_ATTRIBUTES ObjectAttributes;
	HANDLE FileHandle;
	IO_STATUS_BLOCK Iosb;
	char *buffer;
	PWCHAR buffer2;
	ULONG converted;

	RtlInitUnicodeString(&UnicodeFilespec,fileName);

	InitializeObjectAttributes(
		&ObjectAttributes,           // ptr to structure
		&UnicodeFilespec,            // ptr to file spec
		OBJ_CASE_INSENSITIVE,        // attributes
		NULL,                        // root directory handle
		NULL );                      // ptr to security descriptor

	Status = ZwCreateFile(
		&FileHandle,					// returned file handle
		(GENERIC_READ | SYNCHRONIZE),   // desired access
		&ObjectAttributes,              // ptr to object attributes
		&Iosb,                          // ptr to I/O status block
		0,                              // allocation size
		FILE_ATTRIBUTE_NORMAL,          // file attributes
		0,                              // share access
		FILE_OPEN,						// create disposition
		FILE_SYNCHRONOUS_IO_NONALERT,   // create options
		NULL,                           // ptr to extended attributes
		0);                             // length of ea buffer

	CHECK_STATUSA(Status,Öffnen der Computernamensdatei)
	RETURN_NULL_IF_STATUS_UNSUCCESSFULL

	buffer = (char*)io.malloc(256);//RtlAllocateHeap( Heap, 0, 256 );
	Status = ZwReadFile(FileHandle,0,NULL,NULL,&Iosb,buffer,256,0,NULL);
	((char*)buffer)[Iosb.Information]=0;

	CHECK_STATUSA(Status,Lesen des Computernamens);
	RETURN_NULL_IF_STATUS_UNSUCCESSFULL

	io.print("Trying to parse file ... ");
	char *parsed=parseComputerNameFile(io,buffer,Iosb.Information);

	if (parsed!=0)
	{
		io.print("successful: ");
		io.println(parsed);
	}
	else
	{
		io.println("failed.");
		io.free(buffer);
		io.free(parsed);
		return 0;
	}

	buffer2 = (PWCHAR)io.malloc(500);
    
    mbstowcs(buffer2,(char*)parsed,strlen(parsed));
    
    Status = ZwClose(FileHandle);

	CHECK_STATUS(Status,Schließen der Datei);

	io.free(buffer);
	io.free(parsed);

	return buffer2;
}

/*
Function: setCompnameFromFile
command line command to set computer name from file.

Uses a list of files to find computer name. List consists of 
command line parameters and hard coded *\\device\\floppy0\\compname.txt*.

Tries to read each file and extract the computer name in the list till a 
valid one is found. This is set as computer name afterwards.

Parameters:
io - <IO>-Controller
args - command line
*/
void setCompnameFromFile(IO &io,char *args)
{
	Indenter i(io);
	int numFiles=mainSingleton->getArgc();
	char **valueNames=(char**)io.malloc(4*numFiles);
	char **cmdargs=mainSingleton->getArgs();

	io.print("Computername file pipe: ");

	for (int i=1;i<numFiles;i++)
	{
		io.print(cmdargs[i]);
		io.print(", ");
		valueNames[i-1]=cmdargs[i];
	}
	
	valueNames[numFiles-1]="\\device\\floppy0\\compname.txt";
	io.println(valueNames[numFiles-1]);

	io.println("Reading computer-name from ...");

	for (int i=0;i<numFiles;i++)
	{
		io.println(valueNames[i]);
		wchar_t *buffer2=readComputerNameFromFile(io,io.char2wchar(valueNames[i]));
		if (buffer2!=0)
		{
			setComputerName(io,buffer2);
			io.free(buffer2);
			io.free(valueNames);
			return;
		}
	}
	io.free(valueNames);
}