1 // terrasync.cxx -- "JIT" scenery fetcher
3 // Written by Curtis Olson, started November 2002.
5 // Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
6 // Copyright (C) 2008 Alexander R. Perry <alex.perry@ieee.org>
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
35 #elif defined(_MSC_VER)
37 # ifndef HAVE_SVN_CLIENT_H
43 #include <stdlib.h> // atoi() atof() abs() system()
44 #include <signal.h> // signal()
46 #include <simgear/compiler.h>
54 #include <simgear/io/raw_socket.hxx>
55 #include <simgear/bucket/newbucket.hxx>
56 #include <simgear/misc/sg_path.hxx>
58 #ifdef HAVE_SVN_CLIENT_H
59 # ifdef HAVE_LIBSVN_CLIENT_1
60 # include <svn_auth.h>
61 # include <svn_client.h>
62 # include <svn_cmdline.h>
63 # include <svn_pools.h>
65 # undef HAVE_SVN_CLIENT_H
71 const char* source_base = NULL;
72 const char* svn_base =
73 "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
74 const char* rsync_base = "scenery.flightgear.org::Scenery";
75 const char* dest_base = "terrasyncdir";
76 const char* rsync_cmd =
77 "rsync --verbose --archive --delete --perms --owner --group";
79 #ifdef HAVE_SVN_CLIENT_H
83 const char* svn_cmd = "svn checkout";
87 static void usage( const string& prog ) {
89 "Usage: terrasync [options]\n"
91 " -d <dest> destination directory [required]\n"
92 " -R transport using pipe to rsync\n"
93 " -S transport using built-in svn\n"
94 " -p <port> listen on UDP port [default: 5501]\n"
95 " -s <source> source base [default: '']\n"
96 " -pid <pidfile> write PID to file\n"
97 " -v be more verbose\n"
100 #ifdef HAVE_SVN_CLIENT_H
101 cout << " (defaults to the built in subversion)" << endl;
103 cout << " (defaults to rsync, using external commands)" << endl;
106 cout << "\nExample:\n"
107 "pid=$(cat $pidfile 2>/dev/null)\n"
108 "if test -n \"$pid\" && kill -0 $pid ; then\n"
109 " echo \"terrasync already running: $pid\"\n"
111 " nice /games/sport/fgs/utils/TerraSync/terrasync \\\n"
112 " -v -pid $pidfile -S -p 5500 -d /games/orig/terrasync &\n"
117 deque<string> waitingTiles;
118 typedef map<string,time_t> CompletedTiles;
119 CompletedTiles completedTiles;
120 simgear::Socket theSocket;
122 #ifdef HAVE_SVN_CLIENT_H
124 // Things we need for doing subversion checkout - often
125 apr_pool_t *mysvn_pool = NULL;
126 svn_client_ctx_t *mysvn_ctx = NULL;
127 svn_opt_revision_t *mysvn_rev = NULL;
128 svn_opt_revision_t *mysvn_rev_peg = NULL;
130 static const svn_version_checklist_t mysvn_checklist[] = {
131 { "svn_subr", svn_subr_version },
132 { "svn_client", svn_client_version },
136 // Configure our subversion session
137 int mysvn_setup(void) {
138 // Are we already prepared?
139 if (mysvn_pool) return EXIT_SUCCESS;
140 // No, so initialize svn internals generally
142 // there is a segfault when providing an error stream.
143 // Apparently, calling setvbuf with a nul buffer is
144 // not supported under msvc 7.1 ( code inside svn_cmdline_init )
145 if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
148 if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
152 apr_pool_create(&pool, NULL);
153 svn_error_t *err = NULL;
154 SVN_VERSION_DEFINE(mysvn_version);
155 err = svn_ver_check_list(&mysvn_version, mysvn_checklist);
157 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
158 err = svn_ra_initialize(pool);
160 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
161 char *config_dir = NULL;
162 err = svn_config_ensure(config_dir, pool);
164 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
165 err = svn_client_create_context(&mysvn_ctx, pool);
167 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
168 err = svn_config_get_config(&(mysvn_ctx->config),
171 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
173 cfg = ( svn_config_t*) apr_hash_get(
175 SVN_CONFIG_CATEGORY_CONFIG,
176 APR_HASH_KEY_STRING);
178 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
179 svn_auth_baton_t *ab;
180 err = svn_cmdline_setup_auth_baton(&ab,
181 TRUE, NULL, NULL, config_dir, TRUE, cfg,
182 mysvn_ctx->cancel_func, mysvn_ctx->cancel_baton, pool);
184 return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
185 mysvn_ctx->auth_baton = ab;
186 mysvn_ctx->conflict_func = NULL;
187 mysvn_ctx->conflict_baton = NULL;
188 // Now our magic revisions
189 mysvn_rev = (svn_opt_revision_t*) apr_palloc(pool,
190 sizeof(svn_opt_revision_t));
193 mysvn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool,
194 sizeof(svn_opt_revision_t));
197 mysvn_rev->kind = svn_opt_revision_head;
198 mysvn_rev_peg->kind = svn_opt_revision_unspecified;
199 // Success if we got this far
206 // sync one directory tree
207 void sync_tree(const char* dir) {
210 SGPath path( dest_base );
213 rc = path.create_dir( 0755 );
215 cout << "Return code = " << rc << endl;
220 #ifdef HAVE_SVN_CLIENT_H
221 cout << dir << " ... ";
223 char dest_base_dir[512];
224 snprintf( command, 512,
225 "%s/%s", source_base, dir);
226 snprintf( dest_base_dir, 512,
227 "%s/%s", dest_base, dir);
228 svn_error_t *err = NULL;
229 if (mysvn_setup() != EXIT_SUCCESS)
231 apr_pool_t *subpool = svn_pool_create(mysvn_pool);
232 err = svn_client_checkout3(NULL,
243 // Report errors from the checkout attempt
244 cout << "failed: " << endl
245 << err->message << endl;
246 svn_error_clear(err);
249 cout << "done" << endl;
251 svn_pool_destroy(subpool);
255 snprintf( command, 512,
256 "%s %s/%s %s/%s", svn_cmd,
261 snprintf( command, 512,
262 "%s %s/%s/ %s/%s/", rsync_cmd,
266 cout << command << endl;
267 rc = system( command );
269 cout << "Return code = " << rc << endl;
270 if (rc == 5120) exit(1);
274 #if defined(_MSC_VER) || defined(__MINGW32__)
275 typedef void (__cdecl * sighandler_t)(int);
276 #elif defined( __APPLE__ )
277 typedef sig_t sighandler_t;
280 bool terminating = false;
281 sighandler_t prior_signal_handlers[32];
282 int termination_triggering_signals[] = {
283 #if defined(_MSC_VER) || defined(__MINGW32__)
284 SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM, SIGBREAK, SIGABRT,
286 SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGTERM,
288 0}; // zero terminated
290 void terminate_request_handler(int param) {
291 char msg[] = "\nReceived signal XX, intend to exit soon.\n"
292 "repeat the signal to force immediate termination.\n";
293 msg[17] = '0' + param / 10;
294 msg[18] = '0' + param % 10;
295 write(1, msg, sizeof(msg) - 1);
297 signal(param, prior_signal_handlers[param]);
302 const int nowhere = -9999;
306 static void parse_message( const string &msg, int *lat, int *lon ) {
310 // find GGA string and advance to start of lat
311 string::size_type pos = text.find( "$GPGGA" );
312 if ( pos == string::npos )
318 string tmp = text.substr( pos + 7 );
319 pos = tmp.find( "," );
320 tmp = tmp.substr( pos + 1 );
321 // cout << "-> " << tmp << endl;
323 // find lat then advance to start of hemisphere
324 pos = tmp.find( "," );
325 string lats = tmp.substr( 0, pos );
326 dlat = atof( lats.c_str() ) / 100.0;
327 tmp = tmp.substr( pos + 1 );
329 // find N/S hemisphere and advance to start of lon
330 if ( tmp.substr( 0, 1 ) == "S" ) {
333 pos = tmp.find( "," );
334 tmp = tmp.substr( pos + 1 );
337 pos = tmp.find( "," );
338 string lons = tmp.substr( 0, pos );
339 dlon = atof( lons.c_str() ) / 100.0;
340 tmp = tmp.substr( pos + 1 );
342 // find E/W hemisphere and advance to start of lon
343 if ( tmp.substr( 0, 1 ) == "W" ) {
348 *lat = (int)dlat - 1;
354 *lon = (int)dlon - 1;
359 if ((dlon == 0) && (dlat == 0)) {
367 static void sync_area( int lat, int lon ) {
368 if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
371 int baselat, baselon;
374 int base = (int)(lat / 10);
375 if ( lat == base * 10 ) {
378 baselat = (base - 1) * 10;
382 baselat = (int)(lat / 10) * 10;
386 int base = (int)(lon / 10);
387 if ( lon == base * 10 ) {
390 baselon = (base - 1) * 10;
394 baselon = (int)(lon / 10) * 10;
398 const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
400 for (const char** tree = &terrainobjects[0]; *tree; tree++) {
402 snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
404 EW, abs(baselon), NS, abs(baselat),
405 EW, abs(lon), NS, abs(lat) );
406 waitingTiles.push_back( dir );
412 static void sync_areas( int lat, int lon, int lat_dir, int lon_dir ) {
413 // do current 1x1 degree area first
414 sync_area( lat, lon );
416 if ( lat_dir == 0 && lon_dir == 0 ) {
417 // now do surrounding 8 1x1 degree areas.
418 for ( int i = lat - 1; i <= lat + 1; ++i ) {
419 for ( int j = lon - 1; j <= lon + 1; ++j ) {
420 if ( i != lat || j != lon ) {
426 if ( lat_dir != 0 ) {
427 sync_area( lat + lat_dir, lon );
428 sync_area( lat + lat_dir, lon - 1 );
429 sync_area( lat + lat_dir, lon + 1 );
431 if ( lon_dir != 0 ) {
432 sync_area( lat, lon + lon_dir );
433 sync_area( lat - 1, lon + lon_dir );
434 sync_area( lat + 1, lon + lon_dir );
439 void getWaitingTile() {
440 while ( !waitingTiles.empty() ) {
441 CompletedTiles::iterator ii =
442 completedTiles.find( waitingTiles.front() );
443 time_t now = time(0);
444 if ( ii == completedTiles.end() || ii->second + 600 < now ) {
445 sync_tree(waitingTiles.front().c_str());
446 completedTiles[ waitingTiles.front() ] = now;
447 waitingTiles.pop_front();
450 waitingTiles.pop_front();
454 int main( int argc, char **argv ) {
456 char host[256] = "localhost";
457 bool testing = false;
458 bool do_checkout(true);
460 const char* pidfn = "";
465 if ( (string)argv[i] == "-p" ) {
467 port = atoi( argv[i] );
468 } else if ( string(argv[i]).find("-pid") == 0 ) {
471 cout << "pidfn: " << pidfn << endl;
472 } else if ( (string)argv[i] == "-s" ) {
474 source_base = argv[i];
475 } else if ( (string)argv[i] == "-d" ) {
478 } else if ( (string)argv[i] == "-R" ) {
480 } else if ( (string)argv[i] == "-S" ) {
482 } else if ( (string)argv[i] == "-v" ) {
484 } else if ( (string)argv[i] == "-T" ) {
486 } else if ( (string)argv[i] == "-h" ) {
490 cerr << "Unrecognized verbiage '" << argv[i] << "'" << endl;
499 pidstream.open(pidfn);
500 if (!pidstream.good()) {
501 cerr << "Cannot open pid file '" << pidfn << "': ";
505 pidstream << getpid() << endl;
509 // Use the appropriate default for the "-s" flag
510 if (source_base == NULL) {
512 source_base = svn_base;
514 source_base = rsync_base;
517 // Must call this before any other net stuff
518 simgear::Socket::initSockets();
520 if ( ! theSocket.open( false ) ) { // open a UDP socket
521 printf("error opening socket\n");
525 if ( theSocket.bind( host, port ) == -1 ) {
526 printf("error binding to port %d\n", port);
534 int last_lat = nowhere;
535 int last_lon = nowhere;
536 bool recv_msg = false;
540 for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ ) {
542 snprintf( dir, 512, "Airports/%c", synced_other );
543 waitingTiles.push_back( dir );
545 for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ ) {
547 snprintf( dir, 512, "Airports/%c", synced_other );
548 waitingTiles.push_back( dir );
551 waitingTiles.push_back( "Models" );
556 for (int* sigp=termination_triggering_signals; *sigp; sigp++) {
557 prior_signal_handlers[*sigp] =
558 signal(*sigp, *terminate_request_handler);
559 if (verbose) cout << "Intercepted signal " << *sigp << endl;
562 while ( !terminating ) {
566 // No FGFS communications
569 recv_msg = (lat != last_lat) || (lon != last_lon);
571 if (verbose && waitingTiles.empty()) {
572 cout << "Idle; waiting for FlightGear position\n";
574 theSocket.setBlocking(waitingTiles.empty());
575 len = theSocket.recv(msg, maxlen, 0);
579 if (verbose) cout << "recv length: " << len << endl;
580 parse_message( msg, &lat, &lon );
585 // Ignore messages where the location does not change
586 if ( lat != last_lat || lon != last_lon ) {
587 cout << "pos in msg = " << lat << "," << lon << endl;
588 deque<string> oldRequests;
589 oldRequests.swap( waitingTiles );
590 int lat_dir, lon_dir, dist;
591 if ( last_lat == nowhere || last_lon == nowhere ) {
592 lat_dir = lon_dir = 0;
594 dist = lat - last_lat;
596 lat_dir = dist / abs(dist);
600 dist = lon - last_lon;
602 lon_dir = dist / abs(dist);
607 cout << "lat = " << lat << " lon = " << lon << endl;
608 cout << "lat_dir = " << lat_dir << " "
609 << "lon_dir = " << lon_dir << endl;
610 sync_areas( lat, lon, lat_dir, lon_dir );
611 while ( !oldRequests.empty() ) {
612 waitingTiles.push_back( oldRequests.front() );
613 oldRequests.pop_front();
620 // No messages inbound, so process some pending work
621 else if ( !waitingTiles.empty() ) {
625 else if ( testing ) {
634 } // while !terminating