~drizzle-trunk/drizzle/development

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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/* Copyright (c) 2008 PrimeBase Technologies GmbH, Germany
 *
 * PrimeBase Media Stream for MySQL
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Original author: Paul McCullagh
 * Continued development: Barry Leslie
 *
 * 2007-05-25
 *
 * H&G2JCtL
 *
 * Network interface.
 *
 */

#include "cslib/CSConfig.h"
#include <inttypes.h>

#include "cslib/CSGlobal.h"
#include "cslib/CSSocket.h"
#include "cslib/CSStrUtil.h"
#include "cslib/CSHTTPStream.h"

#include "connection_handler_ms.h"
#include "network_ms.h"
#include "open_table_ms.h"
#include "engine_ms.h"
#include "version_ms.h"

//#include "mysql_ms.h"

u_long MSConnectionHandler::gMaxKeepAlive;

MSConnectionHandler::MSConnectionHandler(CSThreadList *list):
	CSDaemon(list),
	amWaitingToListen(false),
	shuttingDown(false),
	lastUse(0),
	replyPending(false),
	iInputStream(NULL),
	iOutputStream(NULL),
	iTableURI(NULL)
{
}

void MSConnectionHandler::close()
{
	closeStream();
	freeRequestURI();
}

MSConnectionHandler *MSConnectionHandler::newHandler(CSThreadList *list)
{
	return new MSConnectionHandler(list);
}

/* Return false if not connection was openned, and the thread must quit. */
bool MSConnectionHandler::openStream()
{
	CSSocket		*sock;
	CSInputStream	*in;
	CSOutputStream	*out;
	
	enter_();
	if (!(sock = MSNetwork::openConnection(this)))
		return_(false);
	push_(sock);
	in = sock->getInputStream();
	in = CSBufferedInputStream::newStream(in);
	iInputStream = CSHTTPInputStream::newStream(in);

	out = sock->getOutputStream();
	out = CSBufferedOutputStream::newStream(out);
	iOutputStream = CSHTTPOutputStream::newStream(out);
	release_(sock);
	return_(true);
}

int MSConnectionHandler::getHTTPStatus(int err)
{
	int code;

	switch (err) {
		case MS_OK:						code = 200; break;
		case MS_ERR_ENGINE:				code = 500; break;
		case MS_ERR_UNKNOWN_TABLE:		code = 404; break;
		case MS_ERR_UNKNOWN_DB:			code = 404; break;
		case MS_ERR_DATABASE_DELETED:	code = 404; break;
		case MS_ERR_NOT_FOUND:			code = 404; break;
		case MS_ERR_REMOVING_REPO:		code = 404; break;
		case MS_ERR_TABLE_LOCKED:		code = 412; break; // Precondition Failed
		case MS_ERR_INCORRECT_URL:		code = 404; break;
		case MS_ERR_AUTH_FAILED:		code = 403; break; // Forbidden
		default:						code = 500; break;
	}
	return code;
}

void MSConnectionHandler::writeException(const char *qualifier)
{
	int code;

	enter_();
	iOutputStream->clearHeaders();
	iOutputStream->clearBody();
	code = getHTTPStatus(myException.getErrorCode());
	iOutputStream->setStatus(code);
	iOutputStream->appendBody("<HTML><HEAD><TITLE>HTTP Error ");
	iOutputStream->appendBody(code);
	iOutputStream->appendBody(": ");
	iOutputStream->appendBody(CSHTTPOutputStream::getReasonPhrase(code));
	iOutputStream->appendBody("</TITLE></HEAD>");
	iOutputStream->appendBody("<BODY><H2>HTTP Error ");
	iOutputStream->appendBody(code);
	iOutputStream->appendBody(": ");
	iOutputStream->appendBody(CSHTTPOutputStream::getReasonPhrase(code));
	iOutputStream->appendBody("</H2>");
	if (qualifier)
		iOutputStream->appendBody(qualifier);
	iOutputStream->appendBody(EXCEPTION_REPLY_MESSAGE_PREFIX_TAG);
	iOutputStream->appendBody(myException.getMessage());
	iOutputStream->appendBody(EXCEPTION_REPLY_MESSAGE_SUFFIX_TAG);
	iOutputStream->appendBody(myException.getStackTrace());
	iOutputStream->appendBody(EXCEPTION_REPLY_STACK_TRACE_SUFFIX_TAG);
	iOutputStream->appendBody("MySQL ");
	iOutputStream->appendBody(PBMSVersion::getCString());
	iOutputStream->appendBody(", PBMS ");
	iOutputStream->appendBody(PBMSVersion::getCString());
	iOutputStream->appendBody("<br>Copyright &#169; 2009, PrimeBase Technologies GmbH</font></P></BODY></HTML>");

	replyPending = false;
	iOutputStream->writeHead();
	iOutputStream->writeBody();
	iOutputStream->flush();
	exit_();
}

void MSConnectionHandler::writeException()
{
	writeException(NULL);
}

void MSConnectionHandler::closeStream()
{
	enter_();
	if (iOutputStream) {
		if (replyPending) {
			try_(a) {
				writeException();
			}
			catch_(a) {
			}
			cont_(a);
		}
		iOutputStream->release();
		iOutputStream = NULL;
	}
	if (iInputStream) {
		iInputStream->release();
		iInputStream = NULL;
	}
	exit_();
}

void MSConnectionHandler::parseRequestURI()
{
	CSString	*uri = iInputStream->getRequestURI();
	uint32_t		pos = 0, end;
	enter_();
	
	freeRequestURI();
	pos = uri->locate(0, "://");
	if (pos < uri->length())
		pos += 3;
	else
		pos = uri->skip(0, '/');

	// Table URI
	end = uri->locate(pos, '/');
	//end = uri->locate(uri->nextPos(end), '/'); I am not sure why this was done.
	//iTableURI = uri->substr(pos, end - pos);
	iTableURI = uri->substr(pos);

	exit_();
}

void MSConnectionHandler::freeRequestURI()
{
	if (iTableURI)
		iTableURI->release();
	iTableURI = NULL;
}

void MSConnectionHandler::writeFile(CSString *file_path)
{
	CSPath			*path;
	CSFile			*file;

	enter_();
	push_(file_path);

	path = CSPath::newPath(RETAIN(file_path));
	pop_(file_path);
	push_(path);
	if (path->exists()) {
		file = path->openFile(CSFile::READONLY);
		push_(file);

		iOutputStream->setContentLength((uint64_t) path->getSize());
		replyPending = false;
		iOutputStream->writeHead();
		
		CSStream::pipe(RETAIN(iOutputStream), file->getInputStream());

		release_(file);
	}
	else {
		myException.initFileError(CS_CONTEXT, path->getCString(), ENOENT);
		writeException();
	}
	release_(path);

	exit_();
}

/*
 * Request URI: /<blob URL>
* OR
 * Request URI: /<database>/<blob alias>
 */
void MSConnectionHandler::handleGet(bool info_only)
{
	const char	*bad_url_comment = "Incorrect URL: ";
	MSOpenTable	*otab;
	CSString	*info_request;
	CSString	*ping_request;

	enter_();
	self->myException.setErrorCode(0);

	iOutputStream->clearHeaders();
	iOutputStream->clearBody();
	//iOutputStream->setStatus(200); This is done in the send now.
	
	parseRequestURI();

	ping_request = iInputStream->getHeaderValue(MS_PING_REQUEST);
	if (ping_request) {
		MSDatabase *db;
		
		db = MSDatabase::getDatabase(ping_request, false);
		if (db) {
			push_(db);
			if (db->myBlobCloud->cl_getDefaultCloudRef()) {
				MSCloudInfo *info = db->myBlobCloud->cl_getCloudInfo();
				push_(info);
				iOutputStream->addHeader(MS_CLOUD_SERVER, info->getServer());
				release_(info);
			}
			release_(db);
		}
		
		iOutputStream->setStatus(200); 
		iOutputStream->writeHead();
		iOutputStream->flush();
		exit_();

	}
	
	info_request = iInputStream->getHeaderValue(MS_BLOB_INFO_REQUEST);
	if (info_request) {
		info_only = (info_request->compare("yes") == 0);
		info_request->release();
	}
	
  
	
	if (iTableURI->length() == 0)
		goto bad_url;
	

	MSBlobURLRec blob;

	if (iTableURI->equals("favicon.ico")) {
		iOutputStream->setStatus(200); 
		writeFile(iTableURI);
	} else if (PBMSBlobURLTools::couldBeURL(iTableURI->getCString(), &blob)) {  
		uint64_t size, offset;
    
		if ((! info_only) && iInputStream->getRange(&size, &offset)) { 
			if (offset >= blob.bu_blob_size) {
				iOutputStream->setStatus(416); // Requested range not satisfiable.
				iOutputStream->writeHead();
				iOutputStream->flush();
				exit_();
			}
			
			if (size > (blob.bu_blob_size - offset))
				size = blob.bu_blob_size - offset;				

			iOutputStream->setRange(size, offset, blob.bu_blob_size);
		} else {
			size = blob.bu_blob_size;
			offset = 0;
		}
 
		if (blob.bu_type == MS_URL_TYPE_BLOB) {
			otab = MSTableList::getOpenTableByID(blob.bu_db_id, blob.bu_tab_id);
			frompool_(otab);
			otab->sendRepoBlob(blob.bu_blob_id, offset, size, blob.bu_auth_code, info_only, iOutputStream);
			backtopool_(otab);
		} else {
			MSRepoFile	*repo_file;

			if (!(otab = MSTableList::getOpenTableForDB(blob.bu_db_id))) {
				char buffer[CS_EXC_MESSAGE_SIZE];
				char id_str[12];
				
				snprintf(id_str, 12, "%"PRIu32"", blob.bu_db_id);

				cs_strcpy(CS_EXC_MESSAGE_SIZE, buffer, "Unknown database ID # ");
				cs_strcat(CS_EXC_MESSAGE_SIZE, buffer, id_str);
				CSException::throwException(CS_CONTEXT, MS_ERR_UNKNOWN_DB, buffer);
			}
			frompool_(otab);
			repo_file = otab->getDB()->getRepoFileFromPool(blob.bu_tab_id, false);
			frompool_(repo_file);
			repo_file->sendBlob(otab, blob.bu_blob_id, offset, size, blob.bu_auth_code, true, info_only, iOutputStream);
			backtopool_(repo_file);
			backtopool_(otab);
		}
	} 
	else { 
#ifdef HAVE_ALIAS_SUPPORT

		CSString	*db_name;
		CSString	*alias;
		MSDatabase * db;
		uint32_t repo_id;
		uint64_t blob_id;
		
		db_name = iTableURI->left("/");
		push_(db_name);
		alias = iTableURI->right("/");
		push_(alias);

		if (db_name->length() == 0 || alias->length() == 0 || alias->length() > BLOB_ALIAS_LENGTH) 
			goto bad_url;
		
		if (!(otab = MSTableList::getOpenTableForDB(MSDatabase::getDatabaseID(db_name->getCString(), true)))) {
			char buffer[CS_EXC_MESSAGE_SIZE];

			cs_strcpy(CS_EXC_MESSAGE_SIZE, buffer, "Unknown database: ");
			cs_strcat(CS_EXC_MESSAGE_SIZE, buffer, db_name->getCString());
			CSException::throwException(CS_CONTEXT, MS_ERR_UNKNOWN_DB, buffer);
		}
		frompool_(otab);

		db = otab->getDB();
		
		// lookup the blob alias in the database.
		if (!db->findBlobWithAlias(alias->getCString(), &repo_id, &blob_id)) {
			char buffer[CS_EXC_MESSAGE_SIZE];

			cs_strcpy(CS_EXC_MESSAGE_SIZE, buffer, "Unknown alias: ");
			cs_strcat(CS_EXC_MESSAGE_SIZE, buffer, alias->getCString());
			CSException::throwException(CS_CONTEXT, MS_ERR_NOT_FOUND, buffer);
		}
			
		MSRepoFile *repo_file = db->getRepoFileFromPool(repo_id, false);
		
		frompool_(repo_file);
		repo_file->sendBlob(otab, blob_id, 0, false, info_only, iOutputStream);
		backtopool_(repo_file);	
			
		backtopool_(otab);		
		
		release_(alias);
		release_(db_name);

#else
		char buffer[CS_EXC_MESSAGE_SIZE];

		cs_strcpy(CS_EXC_MESSAGE_SIZE, buffer, "Bad PBMS BLOB URL: ");
		cs_strcat(CS_EXC_MESSAGE_SIZE, buffer, iTableURI->getCString());
		CSException::throwException(CS_CONTEXT, MS_ERR_NOT_FOUND, buffer);
#endif
	}
	

	exit_();

	bad_url:
	char buffer[CS_EXC_MESSAGE_SIZE];

	cs_strcpy(CS_EXC_MESSAGE_SIZE, buffer, bad_url_comment);
	cs_strcat(CS_EXC_MESSAGE_SIZE, buffer, iInputStream->getRequestURI()->getCString());
	CSException::throwException(CS_CONTEXT, MS_ERR_INCORRECT_URL, buffer);
	exit_();
}

void MSConnectionHandler::handlePut()
{
	MSOpenTable *otab = NULL;
	uint32_t	db_id = 0, tab_id;

	enter_();
	self->myException.setErrorCode(0);

	iOutputStream->clearHeaders();
	iOutputStream->clearBody();
	iOutputStream->setStatus(200);
	
	parseRequestURI();
	if (iTableURI->length() != 0)
		MSDatabase::convertTablePathToIDs(iTableURI->getCString(), &db_id, &tab_id, true);


	if ((!db_id) || !(otab = MSTableList::getOpenTableByID(db_id, tab_id))) {
		char buffer[CS_EXC_MESSAGE_SIZE];

		cs_strcpy(CS_EXC_MESSAGE_SIZE, buffer, "Incorrect URL: ");
		cs_strcat(CS_EXC_MESSAGE_SIZE, buffer, iInputStream->getRequestURI()->getCString());
		CSException::throwException(CS_CONTEXT, MS_ERR_INCORRECT_URL, buffer);
	}
	frompool_(otab);
	
	uint64_t			blob_len, cloud_blob_len = 0;
	PBMSBlobURLRec	bh;
	size_t			handle_len;
	uint16_t			metadata_size = 0; 
	CSStringBuffer	*metadata;
	
	new_(metadata, CSStringBuffer(80));
	push_(metadata);
	
	blob_len = iInputStream->getContentLength();
	
	// Collect the meta data.
	for (uint32_t i = 0; i < iInputStream->numHeaders(); i++) {
		CSHeader *header = iInputStream->getHeader(i);
		const char *name = header->getNameCString();
		
		push_(header);
		
		if (!strcmp(name, MS_BLOB_SIZE)) { // The actual BLOB data size if it is being stored in a cloud.
			sscanf(header->getValueCString(), "%"PRIu64"", &cloud_blob_len);
		}
			
		if (name && otab->getDB()->isValidHeaderField(name)) {
			uint16_t rec_size, name_size, value_size;
			const char *value = header->getValueCString();
			char *buf;
			if (!value)
				value = "";
				
			name_size = strlen(name);
			value_size = strlen(value);
			
			rec_size = name_size + value_size + 2;
			metadata->setLength(metadata_size + rec_size);
			
			buf = metadata->getBuffer(metadata_size);
			metadata_size += rec_size;
			
			memcpy(buf, name, name_size);
			buf += name_size;
			*buf = 0; buf++;
			
			memcpy(buf, value, value_size);
			buf += value_size;
			*buf = 0;
		}
		
		release_(header);
	}
	
	if (blob_len) {
		char hex_checksum[33];
		Md5Digest checksum;
		
		otab->createBlob(&bh, blob_len, metadata->getBuffer(0), metadata_size, RETAIN(iInputStream), NULL, &checksum);

		cs_bin_to_hex(33, hex_checksum, 16, checksum.val);
		hex_checksum[32] = 0;
		iOutputStream->addHeader(MS_CHECKSUM_TAG, hex_checksum);
	} else { // If there is no BLOB data then the client will send it to the cloud server themselves.
		if (!cloud_blob_len)
			CSException::throwException(CS_CONTEXT, CS_ERR_MISSING_HTTP_HEADER, "Missing BLOB length header for cloud BLOB.");
		if (otab->getDB()->myBlobType == MS_CLOUD_STORAGE) {
			CloudKeyRec cloud_key;
			uint32_t signature_time;
			char time_str[20];
			CloudDB *cloud = otab->getDB()->myBlobCloud;
			MSCloudInfo *info;
			
			
			cloud->cl_getNewKey(&cloud_key);
			otab->createBlob(&bh, cloud_blob_len, metadata->getBuffer(0), metadata_size, NULL, &cloud_key);
			
			CSString *signature;
			signature = cloud->cl_getSignature(&cloud_key, iInputStream->getHeaderValue("Content-Type"), &signature_time);
			push_(signature);
			
			info = cloud->cl_getCloudInfo(cloud_key.cloud_ref);
			push_(info);
			iOutputStream->addHeader(MS_CLOUD_SERVER, info->getServer());
			iOutputStream->addHeader(MS_CLOUD_BUCKET, info->getBucket());
			iOutputStream->addHeader(MS_CLOUD_KEY, info->getPublicKey());
			iOutputStream->addHeader(MS_CLOUD_OBJECT_KEY, cloud->cl_getObjectKey(&cloud_key));
			iOutputStream->addHeader(MS_BLOB_SIGNATURE, signature->getCString());
			release_(info);
			
			release_(signature);
			snprintf(time_str, 20, "%"PRIu32"", signature_time);
			iOutputStream->addHeader(MS_BLOB_DATE, time_str);
			
		} else {
			// If the database is not using cloud storage then the client will
			// resend the BLOB data as a normal BLOB when it fails to get the
			// expected cloud server infor headers back.
			bh.bu_data[0] = 0;
		}
	}
	handle_len = strlen(bh.bu_data);
	iOutputStream->setContentLength(handle_len);

	replyPending = false;
	iOutputStream->writeHead();
	iOutputStream->write(bh.bu_data, handle_len);
	iOutputStream->flush();

	release_(metadata);

	backtopool_(otab);

	exit_();
}

void MSConnectionHandler::serviceConnection()
{
	const char	*method;
	bool		threadStarted = false;

	for (;;) {
		iInputStream->readHead();
		if (iInputStream->expect100Continue()) {			
			iOutputStream->clearHeaders();
			iOutputStream->clearBody();
			iOutputStream->setStatus(100);
			iOutputStream->setContentLength(0);
			iOutputStream->writeHead();
			iOutputStream->flush();
		}
		
		if (!(method = iInputStream->getMethod()))
			break;
		if (!threadStarted /* && iInputStream->keepAlive() */) { // Ignore keepalive: Never trust the client!
			/* Start another service handler if no threads
			 * are waiting to listen!
			 */
			threadStarted = true;
			if (!MSNetwork::gWaitingToListen)
				MSNetwork::startConnectionHandler();
		}
		replyPending = true;
		if (strcmp(method, "GET") == 0)
			handleGet(false);
		else if (strcmp(method, "PUT") == 0 ||
			strcmp(method, "POST") == 0)
			handlePut();
		else if (strcmp(method, "HEAD"))
			handleGet(true);
		else
			CSException::throwCoreError(CS_CONTEXT, CS_ERR_UNKNOWN_METHOD, method);
	}
}

bool MSConnectionHandler::initializeWork()
{
	return true;
}

/*
 * Return false if no connection this thread should quit!
 */
bool MSConnectionHandler::doWork()
{
	enter_();

	/* Open a connection: */
	if (!openStream()) {
		myMustQuit = true;
		return_(false);
	}

	/* Do the work for the connection: */
	serviceConnection();

	/* Close the connection: */
	close();

	return_(false);
}

void *MSConnectionHandler::completeWork()
{
	shuttingDown = true;
	/* Close the stream, if it was openned. */
	close();

	return NULL;
}

bool MSConnectionHandler::handleException()
{
	if (!myMustQuit) {
		/* Start another handler if required: */
		if (!MSNetwork::gWaitingToListen)
			MSNetwork::startConnectionHandler();
	}
	close();
	if (!shuttingDown)
		CSDaemon::handleException();
	return false;
}