summaryrefslogtreecommitdiff
path: root/bin/bbackupquery/bbackupquery.cpp
blob: 342969c25c382f42461579fbd9c1b0e076a4681b (plain)
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
// --------------------------------------------------------------------------
//
// File
//		Name:    bbackupquery.cpp
//		Purpose: Backup query utility
//		Created: 2003/10/10
//
// --------------------------------------------------------------------------

#include "Box.h"

#ifdef HAVE_UNISTD_H
	#include <unistd.h>
#endif

#include <errno.h>
#include <stdio.h>

#ifdef HAVE_SYS_TYPES_H
	#include <sys/types.h>
#endif

#ifdef HAVE_LIBREADLINE
	#ifdef HAVE_READLINE_READLINE_H
		#include <readline/readline.h>
	#elif defined(HAVE_EDITLINE_READLINE_H)
		#include <editline/readline.h>
	#elif defined(HAVE_READLINE_H)
		#include <readline.h>
	#endif
#endif
#ifdef HAVE_READLINE_HISTORY
	#ifdef HAVE_READLINE_HISTORY_H
		#include <readline/history.h>
	#elif defined(HAVE_HISTORY_H)
		#include <history.h>
	#endif
#endif

#include "MainHelper.h"
#include "BoxPortsAndFiles.h"
#include "BackupDaemonConfigVerify.h"
#include "SocketStreamTLS.h"
#include "Socket.h"
#include "TLSContext.h"
#include "SSLLib.h"
#include "BackupStoreConstants.h"
#include "BackupStoreException.h"
#include "autogen_BackupProtocolClient.h"
#include "BackupQueries.h"
#include "FdGetLine.h"
#include "BackupClientCryptoKeys.h"
#include "BannerText.h"
#include "Logging.h"

#include "MemLeakFindOn.h"

void PrintUsageAndExit()
{
	printf("Usage: bbackupquery [-q] [-w] "
#ifdef WIN32
	"[-u] "
#endif
	"\n\t[-c config_file] [-l log_file] [commands]\n"
	"As many commands as you require.\n"
	"If commands are multiple words, remember to enclose the command in quotes.\n"
	"Remember to use quit command if you don't want to drop into interactive mode.\n");
	exit(1);
}

int main(int argc, const char *argv[])
{
	int returnCode = 0;

	MAINHELPER_SETUP_MEMORY_LEAK_EXIT_REPORT("bbackupquery.memleaks",
		"bbackupquery")
	MAINHELPER_START

#ifdef WIN32
	WSADATA info;
	
	// Under Win32 we must initialise the Winsock library
	// before using it.
	
	if (WSAStartup(0x0101, &info) == SOCKET_ERROR) 
	{
		// throw error? perhaps give it its own id in the future
		THROW_EXCEPTION(BackupStoreException, Internal)
	}
#endif

	// Really don't want trace statements happening, even in debug mode
	#ifndef NDEBUG
		BoxDebugTraceOn = false;
	#endif
	
	FILE *logFile = 0;

	// Filename for configuration file?
	std::string configFilename;

	#ifdef WIN32
		configFilename = BOX_GET_DEFAULT_BBACKUPD_CONFIG_FILE;
	#else
		configFilename = BOX_FILE_BBACKUPD_DEFAULT_CONFIG;
	#endif
	
	// Flags
	bool quiet = false;
	bool readWrite = false;

	Logging::SetProgramName("Box Backup (bbackupquery)");

	#ifdef NDEBUG
	int masterLevel = Log::NOTICE; // need an int to do math with
	#else
	int masterLevel = Log::INFO; // need an int to do math with
	#endif

#ifdef WIN32
	const char* validOpts = "qvwuc:l:";
	bool unicodeConsole = false;
#else
	const char* validOpts = "qvwc:l:";
#endif

	// See if there's another entry on the command line
	int c;
	while((c = getopt(argc, (char * const *)argv, validOpts)) != -1)
	{
		switch(c)
		{
			case 'q':
			{
				// Quiet mode
				quiet = true;

				if(masterLevel == Log::NOTHING)
				{
					BOX_FATAL("Too many '-q': "
						"Cannot reduce logging "
						"level any more");
					return 2;
				}
				masterLevel--;
			}
			break;

			case 'v':
			{
				if(masterLevel == Log::EVERYTHING)
				{
					BOX_FATAL("Too many '-v': "
						"Cannot increase logging "
						"level any more");
					return 2;
				}
				masterLevel++;
			}
			break;

		case 'w':
			// Read/write mode
			readWrite = true;
			break;
		
		case 'c':
			// store argument
			configFilename = optarg;
			break;
		
		case 'l':
			// open log file
			logFile = ::fopen(optarg, "w");
			if(logFile == 0)
			{
				BOX_LOG_SYS_ERROR("Failed to open log file "
					"'" << optarg << "'");
			}
			break;

#ifdef WIN32
		case 'u':
			unicodeConsole = true;
			break;
#endif
		
		case '?':
		default:
			PrintUsageAndExit();
		}
	}
	// Adjust arguments
	argc -= optind;
	argv += optind;
	
	Logging::SetGlobalLevel((Log::Level)masterLevel);

	// Print banner?
	if(!quiet)
	{
		const char *banner = BANNER_TEXT("Backup Query Tool");
		BOX_NOTICE(banner);
	}

#ifdef WIN32
	if (unicodeConsole)
	{
		if (!SetConsoleCP(CP_UTF8))
		{
			BOX_ERROR("Failed to set input codepage: " <<
				GetErrorMessage(GetLastError()));
		}

		if (!SetConsoleOutputCP(CP_UTF8))
		{
			BOX_ERROR("Failed to set output codepage: " <<
				GetErrorMessage(GetLastError()));
		}

		// enable input of Unicode characters
		if (_fileno(stdin) != -1 &&
			_setmode(_fileno(stdin), _O_TEXT) == -1)
		{
			perror("Failed to set the console input to "
				"binary mode");
		}
	}
#endif // WIN32

	// Read in the configuration file
	if(!quiet) BOX_INFO("Using configuration file " << configFilename);

	std::string errs;
	std::auto_ptr<Configuration> config(
		Configuration::LoadAndVerify
			(configFilename, &BackupDaemonConfigVerify, errs));

	if(config.get() == 0 || !errs.empty())
	{
		BOX_FATAL("Invalid configuration file: " << errs);
		return 1;
	}
	// Easier coding
	const Configuration &conf(*config);
	
	// Setup and connect
	// 1. TLS context
	SSLLib::Initialise();
	// Read in the certificates creating a TLS context
	TLSContext tlsContext;
	std::string certFile(conf.GetKeyValue("CertificateFile"));
	std::string keyFile(conf.GetKeyValue("PrivateKeyFile"));
	std::string caFile(conf.GetKeyValue("TrustedCAsFile"));
	tlsContext.Initialise(false /* as client */, certFile.c_str(), keyFile.c_str(), caFile.c_str());
	
	// Initialise keys
	BackupClientCryptoKeys_Setup(conf.GetKeyValue("KeysFile").c_str());

	// 2. Connect to server
	if(!quiet) BOX_INFO("Connecting to store...");
	SocketStreamTLS socket;
	socket.Open(tlsContext, Socket::TypeINET, conf.GetKeyValue("StoreHostname").c_str(), BOX_PORT_BBSTORED);
	
	// 3. Make a protocol, and handshake
	if(!quiet) BOX_INFO("Handshake with store...");
	BackupProtocolClient connection(socket);
	connection.Handshake();
	
	// logging?
	if(logFile != 0)
	{
		connection.SetLogToFile(logFile);
	}
	
	// 4. Log in to server
	if(!quiet) BOX_INFO("Login to store...");
	// Check the version of the server
	{
		std::auto_ptr<BackupProtocolClientVersion> serverVersion(connection.QueryVersion(BACKUP_STORE_SERVER_VERSION));
		if(serverVersion->GetVersion() != BACKUP_STORE_SERVER_VERSION)
		{
			THROW_EXCEPTION(BackupStoreException, WrongServerVersion)
		}
	}
	// Login -- if this fails, the Protocol will exception
	connection.QueryLogin(conf.GetKeyValueInt("AccountNumber"),
		(readWrite)?0:(BackupProtocolClientLogin::Flags_ReadOnly));

	// 5. Tell user.
	if(!quiet) printf("Login complete.\n\nType \"help\" for a list of commands.\n\n");
	
	// Set up a context for our work
	BackupQueries context(connection, conf);
	
	// Start running commands... first from the command line
	{
		int c = 0;
		while(c < argc && !context.Stop())
		{
			context.DoCommand(argv[c++], true);
		}
	}
	
	// Get commands from input

#ifdef HAVE_LIBREADLINE
	// Must initialise the locale before using editline's readline(),
	// otherwise cannot enter international characters.
	if (setlocale(LC_ALL, "") == NULL)
	{
		BOX_ERROR("Failed to initialise locale. International "
			"character support may not work.");
	}

#ifdef HAVE_READLINE_HISTORY
	using_history();
#endif
	char *last_cmd = 0;
	while(!context.Stop())
	{
		char *command = readline("query > ");
		if(command == NULL)
		{
			// Ctrl-D pressed -- terminate now
			break;
		}
		context.DoCommand(command, false);
		if(last_cmd != 0 && ::strcmp(last_cmd, command) == 0)
		{
			free(command);
		}
		else
		{
#ifdef HAVE_READLINE_HISTORY
			add_history(command);
#else
			free(last_cmd);
#endif
			last_cmd = command;
		}
	}
#ifndef HAVE_READLINE_HISTORY
	free(last_cmd);
	last_cmd = 0;
#endif
#else
	// Version for platforms which don't have readline by default
	if(fileno(stdin) >= 0)
	{
		FdGetLine getLine(fileno(stdin));
		while(!context.Stop())
		{
			printf("query > ");
			fflush(stdout);
			std::string command(getLine.GetLine());
			context.DoCommand(command.c_str(), false);
		}
	}
#endif
	
	// Done... stop nicely
	if(!quiet) BOX_INFO("Logging off...");
	connection.QueryFinished();
	if(!quiet) BOX_INFO("Session finished.");
	
	// Return code
	returnCode = context.GetReturnCode();
	
	// Close log file?
	if(logFile)
	{
		::fclose(logFile);
	}
	
	// Let everything be cleaned up on exit.
	
#ifdef WIN32
	// Clean up our sockets
	// FIXME we should do this, but I get an abort() when I try
	// WSACleanup();
#endif

	MAINHELPER_END
	
	return returnCode;
}