util  Check-in [ae8a97d783]

Overview
Comment:add tenki
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: ae8a97d78350b9ec4506826354c461e1d4aa9e1a0298912e6266fb01ce91cc30
User & Date: lexi on 2019-04-30 23:26:34
Other Links: manifest | tags
Context
2019-05-01
01:03
refactor tenki check-in: 70991b55c3 user: lexi tags: trunk
2019-04-30
23:26
add tenki check-in: ae8a97d783 user: lexi tags: trunk
2019-04-23
02:01
fix bug where bgrd also scooped stderr, thereby breaking my `surf` setup in neovim check-in: 7a21b1f19e user: lexi tags: trunk
Changes

Added tenki/makefile version [d561bb7339].





>
>
1
2
tenki: tenki.cc
	$(CC) -Ofast tenki.cc -o tenki -lssl

Added tenki/tenki.cc version [eaa2ec3cc1].

























































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdint.h>
#include <openssl/ssl.h>

#define ds_apikey "a6aa0337fafd8b8fcfafe84a403ed24f"
#define ds_lang "ja"
#define ds_exclude "minutely,hourly,daily,alerts,flags"

#define req "GET /forecast/"
#define http "?exclude=" ds_exclude "&lang=" ds_lang " HTTP/1.1\r\nHost: api.darksky.net\r\n\r\n"

#define len(x) (sizeof(x)/sizeof(*x))
#define start req ds_apikey "/"
#define min(x,y) (x>y?y:x)

SSL_CTX* sc;
bool head(size_t* len, char* txt, char** body) {
	char* hend = strstr(txt, "\r\n\r\n");
	if (hend == nullptr) return false;
	#define ctlhead "\r\nContent-Length:"
	char* ctl = strstr(txt, ctlhead);
	if (ctl == nullptr or ctl > hend) return false;
	ctl += len(ctlhead);
	*len = 0;
	while(*ctl != '\r') {
		if (*ctl >= '0' and *ctl <= '9') *len*=10,*len+=*ctl-'0';
		++ctl;
	}
	*len+=(hend-txt)+4;
	*body = hend+4;
	return true;
}
size_t get(char* resp, size_t max, const char* msg, size_t total, char** body){

	int port = 443;
	const char* host = "api.darksky.net";
	//printf("req: %s\n", msg);	
	struct hostent* api;
	struct sockaddr_in api_addr;
	int sockfd, bytes;
	size_t sent, recd;
	
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) exit(2);
	SSL *con = SSL_new(sc);
	SSL_set_fd(con, sockfd);

	//printf("getting host\n");
	api = gethostbyname(host);
	if (api == nullptr) exit(3);

	memset(&api_addr, 0, sizeof(api_addr));
	api_addr.sin_family = AF_INET;
	api_addr.sin_port = htons(port);
	memcpy(&api_addr.sin_addr.s_addr, api -> h_addr, api -> h_length);

	//printf("connecting\n");
	if (connect(sockfd,(struct sockaddr*)&api_addr,sizeof(api_addr)))
		exit(4);
	int err = SSL_connect(con);


	sent = 0;
//	printf("writing\n");
	do {
	//	printf("writing byte %x\n",*(msg+sent));
		bytes = SSL_write(con,msg+sent,total-sent);
		if (bytes < 0) exit (4);
		if (bytes == 0) break;
		++sent;
	} while (sent < total);
//	printf("receiving\n");
	recd = 0;
	size_t resplen = max;
	bool rhead = false;
	do {
	//	printf("\n\nreading - addr %x; max %d\n",resp+recd,resplen-recd);
		bytes = SSL_read(con,resp+recd,min(resplen-recd,15000));
		if (bytes < 0) exit (5);
		if (bytes == 0) break;
		if(!rhead)rhead=head(&resplen, resp, body);
		// printf("got %d bytes: %s", bytes, resp+recd);
		recd += bytes;
	} while (recd < resplen - 1);

	close(sockfd);
	SSL_shutdown(con);

	return recd;
}
size_t pos(char* msg, const char* lat, const char* lng) {
	char* cur = msg + len(start) - 1;
	size_t latl = strlen(lat);
	size_t longl = strlen(lng);
	strcpy(cur, lat); cur += latl;
	*cur++=','; 
	strcpy(cur, lng); cur += longl;
	strcpy(cur, http); cur += len(http);
	*cur--=0;
	return cur-msg;
}
bool estrc(size_t sz, const char* str1, const char* str2) {
	for(size_t i = 0;i<sz;++i) {
		if(*str1 == *str2) {
			++str1; ++str2;
		} else if (*str2 =='\\') {
			++str2;
			if(*str1 == *str2) {
				++str1; ++str2;
			} else return false;
		} else {
			return false;
		}
	}
	return true;
}
struct pstr {
	size_t sz;
	const char* a;
};
union jsv {
	float f;
	pstr s;
};
/* void printkey(const char* key) {
	size_t len = *key++;
	for (size_t i = 0; i<len; ++i) {
		printf("/%.*s",*key,key+1);
		key += *key + 1;
	};
	printf("\n");
} */
void pplt(const char* str, const char* const end, const char** keys, const char** const keyend, jsv* values) {
	// initialize parser state
	size_t depth = 0;
	const char* fld = nullptr;
	const char* path[32];
	path[0] = nullptr;
	
	while(*str++!='{'); //cheat
	init: {
		if (keys > keyend) return;
		if (str > end) return;
		/* print_path: {
			printf("current path: /");
			for (size_t i = 0; i < depth; ++i) {
				printf("%.*s/",strchr(path[i],'"')-path[i],path[i]);
			}
			printf("\n");
			printf("current key: ");
			printkey(*keys);
		} */
		parse_char: {
			switch(*str++) {
				case ' ': case '\t': case '\n':
					goto parse_char;
				case '"':
					path[depth] = str;
					goto path_find_quote_end;
				case '}':
					if (depth == 0) return;
					depth--;
					while(*str!=',') ++str; ++str;
					goto init;
				default:
					printf("found illegal char %c\n", *(str-1));
					exit(6);
			}
		}
		path_find_quote_end: {
			switch (*str++) {
				case '\\': ++str; goto path_find_quote_end;
				case '"': goto read_value;
				default: goto path_find_quote_end;
			}
		}
		read_value: {
			if (*str++!=':') {
				printf("illegal char\n");
				exit(6);
			}
			bool iskey;
			const char* key = *keys;
			jsv* value;
			if (depth + 1 != *key++) {
				iskey = false;
				goto comp;
			} else for (size_t i = 0; i <= depth; ++i) {
				if (estrc(*key, key+1, path[i])) {
					key += *key + 1;
				} else {
					iskey = false;
					goto comp;
				}
			}
			iskey = true;
			value = values;
			++keys; ++values;
			comp: if (*str == '{') {
				++depth; ++str;
				goto init;
			} else if (*str == '"') {
				goto copy_str_value;
			} else if (*str == '[') {
				goto skip_array;
			} else if ((*str >= '0' and *str <= '9') or *str=='-') {
				goto copy_int_value;
			} else {
				printf("illegal character found in value %c\n", *str);
				exit(6);
			}

			copy_str_value: {
				fld = ++str;
				while (*++str != '"') if (*str == '\\') { ++str; continue; }
				if (iskey) {
					value -> s.sz = str - fld;
					value -> s.a = fld;
				}
				while (*++str != ',');
				++str; goto init;
			}
			skip_array: {
				size_t ard = 0;
				skip_loop: switch (*++str) {
					case '{': case '[': ++ard; goto skip_loop;
					case '"': goto skip_str;
					case '}': if (ard == 0) {
								  printf("bad json\n");
								  exit(7);
							  } else { --ard; goto skip_loop; }
					case ']': if (ard == 0) {
							if (*++str == ',') { ++str; goto init; }
							else goto init;
						} else { --ard; }
					default: goto skip_loop;
				}
				skip_str: while (*str != '"') if (*str == '\\') { str += 2; continue; } else ++str; goto skip_loop;
			}
			copy_int_value: {
				if (!iskey) {
					while(*str++!=',') if (str > end) return;
					goto init;
				}
				value -> f = 0;
				bool neg;
				if (*str == '-') { neg=true; ++str; } else neg=false;
				while(*str >= '0' and *str <= '9') {
					value -> f *= 10;
					value -> f += *str - '0';
					++str;
				}
				if(*str == '.') {
					float fac = 0.1;
					float val = 0;
					while(*++str >= '0' and *str <= '9') {
						val += (((float)(*str - '0')) * fac);
						fac *= 0.1;
					}
					value -> f += val;
				}
				if(neg) value -> f *= -1;
				if (*str == ',') {
					++str; goto init;
				} else {
					printf("illegal character %.*s\n",15,str);
					exit(6);
				}
			}
		}
	}
}
int main(int argc, char** argv) {
	if (argc != 3) exit(1);
	SSL_load_error_strings();
	SSL_library_init();
	sc = SSL_CTX_new(SSLv23_client_method());

	char msg[256] = start;
	char resp[32368];
	char* body;

	// name the fields to extract from the json stream
	// note: MUST BE LISTED IN ORDER THEY APPEAR
	// paths are encoded as sequences of pstrings
	// initial value indicates depth of path
	// TODO: performance worth lack of flexibility?
	const char* paths[] = {
		"\2\x9""currently\7summary",
		"\2\x9""currently\xfprecipIntensity",
		"\2\x9""currently\xbtemperature",
		"\2\x9""currently\x9windspeed",
	};

	size_t msgsz = pos(msg, argv[1], argv[2]);
		//msgsz = size of transmit
	//for (;;) {
		size_t rspsz = get(resp, sizeof(resp), msg, msgsz, &body);
		// if paths contains the keys, this contains the values
		jsv values[len(paths)]; 
		
		parse: {
			pplt(body, body + (rspsz - (resp - body)), paths, paths+len(paths), values);
			
			pstr summary = values[0].s;
			float pcpint = values[1].f,
				temp = values[2].f,
				windspd = values[3].f;

			printf("%.1f°  %%{F#ff9bbb}%.*s\n",
					summary.sz,
					summary.a,
					temp);
		}
		// dark sky's API allows us to make 1000 free requests a day.
		// let's try not to get too near that.
		// hours in day 24 - minutes in day 24 * 60 = 1440
		// so once a minute is almost half again too many
		// 1440 / 2 = 720 leaving reasonable refresh time without
		// going too near the limit. so we aim for one update
		// every two minutes.
	//	sleep(60 * 2);
//	}

	return 0;
}