summaryrefslogtreecommitdiff
path: root/src/quotprint.c
blob: 9e1caff7a799e88ab2b99a5e8b3522ddceb0ccee (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
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


#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>


#define FLG_isEnc (1<<0)
#define FLG_isDec (1<<1)
#define FLG_isError (1<<2)

#ifndef BUF_CAP  /* aka "buffer capacity" */
#	define BUF_CAP 0x10000
#endif

#ifndef INLINE
#	define INLINE(T) /*TODO static inline*/ T
#endif
#ifndef PRIVATE
#	define PRIVATE(T) static T
#endif

#ifndef REGISTER
#	define REGISTER /*no-op*/
#endif

#if 0
#	define LOGD(...) fprintf(stderr, __VA_ARGS__)
#else
#	define LOGD(...)
#endif

#define STR_QUOT_(S) #S
#define STR_QUOT(S) STR_QUOT_(S)


typedef struct FalseSharingBarrier { void* _[64/sizeof(void*)]; } FalseSharingBarrier;


typedef struct Buf {
	int len;
	char buf[BUF_CAP];
} Buf;


#define App_mAGIC 0x9C344C73
#define DEFINE_App(D, S) struct App*const D=(void*)S; do{ \
	assert(D); assert(D->mAGIC == App_mAGIC); }while(0)
typedef struct App {
	int mAGIC;
	int flg;
	pthread_t thrdWr, thrdRd;
	FalseSharingBarrier _IQExiA5MsnEuw7eW;
	/*
	 * shared in between processing and destination thread */
	char *dstBufReadyToFill;
	char *dstBufReadyToFlush;
	pthread_mutex_t mutxDst;
	pthread_cond_t condDst;
	FalseSharingBarrier _EY0zt7tDeaLkpOmA;
	/*
	 * shared in between source and processing thread */
	char *srcBufReadyToConsume;
	char *srcBufReadyToFill;
	pthread_mutex_t mutxSrc;
	pthread_cond_t condSrc;
	FalseSharingBarrier _yZYEomgBwCcRRKws;
	/*
	 * double-buffering for each (read/write) side. */
	FalseSharingBarrier _8mjY6g2I7tL3wQDE;
	Buf dstBufOne;
	FalseSharingBarrier _FkFIIpC2JzIaKuJe;
	Buf dstBufTwo;
	FalseSharingBarrier _d3xluckkcebLiGzO;
	Buf srcBufOne;
	FalseSharingBarrier _y629LZsTzNbe2rka;
	Buf srcBufTwo;
} App;


PRIVATE(char) endOfFile;


INLINE(void)
printHelp( void ){
	printf("\n"
		"  quotprint - QuotedPrintable codec\n"
		"  Version: " STR_QUOT(PROJECT_VERSION) "\n"
		"  \n"
		"  -e    `encode` to QuotedPrintable\n"
		"  -d    `decode` from QuotedPrintable\n"
		"  \n"
		"\n");
}


INLINE(int)
parseArgs( int argc, char**argv, App*this ){
	int err;
	assert(argv[0]);  assert(this);
	/* 1st prime config based on filename. Eg to support `quotprintenc` and
	 * `quotprintdec`. */
	char *basename = strrchr(argv[0], '/');
	basename = (basename) ? basename +1 : argv[0];
	if( !strcasecmp(basename, "quotprintenc") )
		{ this->flg |= FLG_isEnc; }
	if( !strcasecmp(basename, "quotprintdec") )
		{ this->flg |= FLG_isDec; }
	/* then handle regular args */
	int iA = 0;
nextArg:
	iA += 1;
	char *arg = argv[iA];
	if( !arg ){
		goto verify;
	}else if( !strcmp(arg, "--help") ){
		return -2;
	}else if( !strcmp(arg, "-e") ){
		this->flg |= FLG_isEnc;
	}else if( !strcmp(arg, "-d") ){
		this->flg |= FLG_isDec;
	}else{
		fprintf(stderr, "EINVAL: %s\n", arg);
		return -1;
	}
	goto nextArg;
verify:
	err = FLG_isEnc | FLG_isDec;
	if( (this->flg & err) == err || (this->flg & err) == 0 ){
		fprintf(stderr, "EINVAL: Choose exactly ONE of `encode` XOR `decode`.\n");
		return -1;
	}
	return 0;
}


PRIVATE(void*)
mainOfOutputThread( void*_ ){
	/* TODO shutdown if error on other thread */
	int err;
	#define BUF (this->dstBufReadyToFlush)
	#define LEN (*(int*)(((uintptr_t)0) \
		+ ((uintptr_t)(BUF == this->dstBufOne.buf) * (uintptr_t)&this->dstBufOne.len) \
		+ ((uintptr_t)(BUF == this->dstBufTwo.buf) * (uintptr_t)&this->dstBufTwo.len) \
	))
	DEFINE_App(this, _);
	{
		err = pthread_mutex_lock(&this->mutxDst);  assert(!err);
	}awaitBuffer:{
		LOGD("output - await BUF ...\n");
		while( !BUF )
			pthread_cond_wait(&this->condDst, &this->mutxDst);
		if( BUF == &endOfFile )
			{ goto onSrcEof; }
		LOGD("output - BUF ready\n");
		goto writeChunk;
	}writeChunk:{
		assert(LEN > 0);  assert(BUF);
		err = fprintf(stdout, "%.*s", LEN, BUF);
		if( err < 0 ){
			err = -errno;
			/*TODO maybe handle closed sink gracefully*/
			this->flg |= FLG_isError;
			fprintf(stderr, "ERRNO_%d: fprintf(stdout)\n", -err);
		}
		/*clear buf and set unassigned to inidicate we're ready for another one*/
		LOGD("output - wrote %d bytes from dstBuf%s to the world\n",
			err, (BUF==this->dstBufOne.buf)?"One":"Two");
		LEN = 0;
		BUF = NULL;
		err = pthread_cond_broadcast(&this->condDst);  assert(!err);
		goto awaitBuffer;
	}onSrcEof:{
		LOGD("output - EOF received\n");
		err = 0; goto resolveWithErr;
	}resolveWithErr:{
		assert(err == 0);
		LOGD("RETURN from %s()\n", __func__);
		err = pthread_mutex_unlock(&this->mutxDst);  assert(!err);
		return NULL;
	}
	#undef BUF
	#undef LEN
}


PRIVATE(void*)
mainOfInputThread( void*_ ){
	/* TODO shutdown if error on other thread */
	int err;
	DEFINE_App(this, _);
	#define BUF (this->srcBufReadyToFill)
	/*TODO branchless*/
	#define LEN (*((BUF == this->srcBufOne.buf) ? (&this->srcBufOne.len) : (&this->srcBufTwo.len)))
	{
		err = pthread_mutex_lock(&this->mutxSrc);  assert(!err);
		goto awaitBuffer;
	}awaitBuffer:{
		LOGD("innput - await BUF ...\n");
		while( !BUF )
			pthread_cond_wait(&this->condSrc, &this->mutxSrc);
		LOGD("innput - BUF ready\n");
		goto readNextChunk;
	}readNextChunk:{
		#define SRC stdin
		assert(BUF); assert(LEN == 0);
		err = fread(BUF, 1, BUF_CAP, SRC);
		if( err == 0 && ferror(SRC) ){
			err = -errno;
			/*TODO maybe handle closed sink gracefully*/
			this->flg |= FLG_isError;
			fprintf(stderr, "ERRNO_%d: " STR_QUOT(PROJECT_NAME) ": fread()\n", -err);
			goto resolveVoid;
		}
		if( err == 0 && feof(SRC) )
			{ goto onSrcEof; }
		assert(err > 0);
		/* mark buffer filled and unassing to indicate we're ready for another
		 * one to fill */
		LOGD("Filled %d bytes into srcBuf%s\n", err, (BUF==this->srcBufOne.buf)?"One":"Two");
		LEN = err;
		/*make sure slot is free for assignment*/
		while( this->srcBufReadyToConsume ){
			err = pthread_cond_wait(&this->condSrc, &this->mutxSrc);  assert(!err);
		}
		this->srcBufReadyToConsume = BUF;
		BUF = NULL;
		err = pthread_cond_broadcast(&this->condSrc);  assert(!err);
		goto awaitBuffer;
		#undef SRC
	}onSrcEof:{
		LOGD("innput - EOF\n");
		this->srcBufReadyToConsume = &endOfFile;
		err = pthread_cond_broadcast(&this->condSrc);  assert(!err);
		goto resolveVoid;
	}resolveVoid:{
		LOGD("RETURN from %s()\n", __func__);
		err = pthread_mutex_unlock(&this->mutxSrc);  assert(!err);
		return NULL;
	}
	#undef BUF
	#undef LEN
}


INLINE(void*)
mainOfEncode( void*_ ){
	DEFINE_App(this, _);
	int err, iSrc = 0, iDst = 0, lineBeg = 0;
	{
		#define BUF_DST (this->dstBufReadyToFill)
		#define DST_CAP BUF_CAP
		#define LEN_DST (*(int*)(((uintptr_t)0) \
			+ ((uintptr_t)(BUF_DST == this->dstBufOne.buf) * (uintptr_t)&this->dstBufOne.len) \
			+ ((uintptr_t)(BUF_DST != this->dstBufOne.buf) * (uintptr_t)&this->dstBufTwo.len) \
		))
		#define BUF_SRC (this->srcBufReadyToConsume)
		#define SRC_CAP BUF_CAP
		#define LEN_SRC (*(int*)(((uintptr_t)0) \
			+ ((uintptr_t)(BUF_SRC == this->srcBufOne.buf) * (uintptr_t)&this->srcBufOne.len) \
			+ ((uintptr_t)(BUF_SRC == this->srcBufTwo.buf) * (uintptr_t)&this->srcBufTwo.len) \
		))
	}awaitBuffers:{
		LOGD("encoder - await DST buf\n");
		err = pthread_mutex_lock(&this->mutxDst);  assert(!err);
		while( !BUF_DST )
			pthread_cond_wait(&this->condDst, &this->mutxDst);
		err = pthread_mutex_unlock(&this->mutxDst);  assert(!err);
	}{
		LOGD("encoder - await SRC buf\n");
		err = pthread_mutex_lock(&this->mutxSrc);  assert(!err);
		while( !BUF_SRC )
			pthread_cond_wait(&this->condSrc, &this->mutxSrc);
		err = pthread_mutex_unlock(&this->mutxSrc);  assert(!err);
	}{
		LOGD("encoder - both buffers ready\n");
		if( BUF_SRC == &endOfFile ){
			/* input has ended. we MUST ensure that we really flush what
			 * we maybe still have in dst. So assert dst is full and handle it
			 * there. */
			/* TODO should we ensure that output always ends with CRLF? */
			goto onDstBufFull;
		}
		for(;;){
			if( iDst + 3 >= DST_CAP )
				{ goto onDstBufFull; }
			if( iSrc >= LEN_SRC )
				{ goto onSrcBufDrained; }
			uint_fast8_t c = BUF_SRC[iSrc++];
			switch( c ){

			/*these are allowed to be raw*/
			case 0x20: /*space*/
			case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28:
			case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: /*!"#$%&'()*+,-./ */
			case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
			case 0x38: case 0x39: /* 0-9 */
			case 0x3A: case 0x3B: case 0x3C: /* :;< */
			case 0x3E: case 0x3F: case 0x40: /* >?@ */
			case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48:
			case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50:
			case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58:
			case 0x59: case 0x5A: /* A-Z */
			case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: case 0x60: /* [\]^_` */
			case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68:
			case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70:
			case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78:
			case 0x79: case 0x7A: /* a-z */
			case 0x7B: case 0x7C: case 0x7D: case 0x7E: /* {|}~ */
				if( iDst - lineBeg >= 76 - 1 ){
					BUF_DST[iDst++] = '=';
					BUF_DST[iDst++] = '\r';
					BUF_DST[iDst++] = '\n';
					lineBeg = iDst;
				}
				BUF_DST[iDst++] = c;
				break;
			/* The CrLf sequence if a special case, as it CAN be printed raw. So lets
			 * try if we have enough context (eg the next byte) to do it. */
			case 0x0D:;
				int const isNxtChrPresent = (iSrc + 1 < LEN_SRC);
				int const isDstHasSpace = (iDst + 2 < DST_CAP);
				if( isNxtChrPresent && isDstHasSpace && BUF_SRC[iSrc] == 0x0A ){
					/* we CAN print raw, as we know it IS a CrLf sequence! */
					BUF_DST[iDst++] = c;
					BUF_DST[iDst++] = BUF_SRC[iSrc++];
					lineBeg = iDst;
					break;
				}else{
					/* fall, to escape them the same way */
				}
			/* everything else has to go through escaping */
			default:
				if( iDst - lineBeg >= (76-3) ){
					BUF_DST[iDst++] = '=';
					BUF_DST[iDst++] = '\r';
					BUF_DST[iDst++] = '\n';
					lineBeg = iDst;
				}
				char const hx[] = "0123456789ABCDEF";
				BUF_DST[iDst++] = '=';
				BUF_DST[iDst++] = hx[c >> 4];
				BUF_DST[iDst++] = hx[c & 0xF];
				break;

			}
		}
		assert(!"unreachable");
	}onDstBufFull:{
		/* hand over dst buf as soon consumer is ready to take it */
		err = pthread_mutex_lock(&this->mutxDst);  assert(!err);
		while( this->dstBufReadyToFlush )
			{ err = pthread_cond_wait(&this->condDst, &this->mutxDst);  assert(!err); }
		LOGD("encoder - dstBufReadyToFlush := dstBuf%s\n",
			(BUF_DST==this->dstBufOne.buf)?"One":"Two");
		LOGD("encoder - dstBuf%s.len := %d\n", (BUF_DST==this->dstBufOne.buf)?"One":"Two", iDst);
		LOGD("encoder - dstBuf%s := NULL\n", (BUF_DST==this->dstBufOne.buf)?"One":"Two");
		this->dstBufReadyToFlush = BUF_DST;
		LEN_DST = iDst;
		BUF_DST = NULL;
		err = pthread_cond_broadcast(&this->condDst);  assert(!err);
		if( BUF_SRC == &endOfFile ){
			/* src eof, so mark our eof too (as soon prev buffer is consumed) */
			while( this->dstBufReadyToFlush )
				{ err = pthread_cond_wait(&this->condDst, &this->mutxDst);  assert(!err); }
			LOGD("encoder - src did report EOF. Therefore report EOF too\n");
			this->dstBufReadyToFlush = &endOfFile;
			err = pthread_cond_broadcast(&this->condDst);  assert(!err);
			err = pthread_mutex_unlock(&this->mutxDst);  assert(!err);
			err = 0; goto resolveWithErr;
		}else{
			err = pthread_mutex_unlock(&this->mutxDst);  assert(!err);
		}
		goto awaitBuffers;
	}onSrcBufDrained:{
		err = pthread_mutex_lock(&this->mutxSrc);  assert(!err);
		while( this->srcBufReadyToFill )
			{ pthread_cond_wait(&this->condSrc, &this->mutxSrc); }
		this->srcBufReadyToFill = BUF_SRC;
		LEN_SRC = 0;
		BUF_SRC = NULL;
		err = pthread_cond_broadcast(&this->condSrc);  assert(!err);
		err = pthread_mutex_unlock(&this->mutxSrc);  assert(!err);
		goto awaitBuffers;
	}/*update buffer states*/{
		err = pthread_mutex_lock(&this->mutxDst);  assert(!err);
		LEN_DST = iDst;
		BUF_DST = NULL;
		err = pthread_mutex_unlock(&this->mutxDst);  assert(!err);
	}{
		err = pthread_mutex_lock(&this->mutxSrc);  assert(!err);
		LEN_SRC = 0;
		BUF_SRC = NULL;
		err = pthread_mutex_unlock(&this->mutxSrc);  assert(!err);
		goto awaitBuffers;
	}resolveWithErr:{
		assert(err == 0);
		LOGD("RETURN from %s()\n", __func__);
		pthread_mutex_unlock(&this->mutxSrc);
		return NULL;
		#undef BUF_DST
		#undef DST_CAP
		#undef LEN_DST
		#undef BUF_SRC
		#undef SRC_CAP
		#undef LEN_SRC
	}
}


INLINE(int)
quotPrintDecode( App*this ){
	assert(!"TODO_i5TKHBVqBa0lRhqy");
}


INLINE(int)
run( App*this ){
	int err;
	/*assign initial buffers BEFORE we lanch threads, so we dont need mutx*/{
		LOGD("Initial buffer assignments\n");
		LOGD("srcBufReadyToFill := srcBufOne.buf\n");
		LOGD("dstBufReadyToFill := dstBufOne.buf\n");
		this->srcBufReadyToFill = this->srcBufOne.buf;
		this->dstBufReadyToFill = this->dstBufOne.buf;
	}/*launch a thread for processing*/{
		void *(*processor)(void*) = (this->flg & FLG_isEnc)
			? mainOfEncode
			: NULL //TODO mainOfDecode
		;
		err = pthread_create(&this->thrdWr, NULL, processor, this);
		if( err ){
			assert(err > 0);
			err = -err; goto resolveWithErr;
		}
	}/*launch a thread for reading*/{
		err = pthread_create(&this->thrdRd, NULL, mainOfInputThread, this);
		if( err ){
			assert(err > 0);
			err = -err; goto resolveWithErr;
		}
	}/*use main thread to do the output writing*/{
		mainOfOutputThread(this);
		err = 0;
	}resolveWithErr:{
		/* TODO make sure to error out if ANY of the threads had an error*/
		return err;
	}
}


int
main( int argc, char**argv ){
	int err;
	int isThreadingIsInit = 0;
	static App app_ = {
		.mAGIC = App_mAGIC,
	};
	static App*const this = &app_;
	{
		switch( parseArgs(argc, argv, this) ){
		case 0: break; /*OK*/
		case -1: err = 1; goto resolveWithErr;
		case -2: printHelp(); err = 0; goto resolveWithErr;
		default: assert(!"unreachable");
		}
	}{
		#define Buf_init(BUF) do{ (BUF)->len = 0; }while(0)
		#define Buf_fini(BUF) do{ }while(0)
		Buf_init(&this->dstBufOne);
		Buf_init(&this->dstBufTwo);
		Buf_init(&this->srcBufOne);
		Buf_init(&this->srcBufTwo);
		isThreadingIsInit = 1;
		#undef Buf_init
	}{
		err = (run(this) != 0) * 1;
		goto resolveWithErr;
	}resolveWithErr:{
		int const errBk = err;
		if( isThreadingIsInit ){
			Buf_fini(this->dstBufOne);
			Buf_fini(this->dstBufTwo);
			Buf_fini(this->srcBufOne);
			Buf_fini(this->srcBufTwo);
		}
		err = errBk;
		assert(err == 0 || err == 1);
		return err;
		#undef Buf_fini
	}
}