]> git.mxchange.org Git - flightgear.git/blob - utils/TerraSync/terrasync.cxx
Fix terrasync svn-library linkage - not perfect but now links against libsvn_subr...
[flightgear.git] / utils / TerraSync / terrasync.cxx
1 // terrasync.cxx -- "JIT" scenery fetcher
2 //
3 // Written by Curtis Olson, started November 2002.
4 //
5 // Copyright (C) 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 // Copyright (C) 2008  Alexander R. Perry <alex.perry@ieee.org>
7 //
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.
12 //
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.
17 //
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.
21 //
22 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31
32 #ifdef __MINGW32__
33 #include <time.h>
34 #include <unistd.h>
35 #elif defined(_MSC_VER)
36 #include <io.h>
37 #endif
38
39 #include <stdlib.h>             // atoi() atof() abs() system()
40 #include <signal.h>             // signal()
41
42 #include <simgear/compiler.h>
43
44 #include <iostream>
45 #include <fstream>
46 #include <string>
47 #include <deque>
48 #include <map>
49
50 #include <plib/netSocket.h>
51 #include <plib/ul.h>
52
53 #include <simgear/bucket/newbucket.hxx>
54 #include <simgear/misc/sg_path.hxx>
55
56 #ifdef HAVE_SVN_CLIENT_H
57 #  ifdef HAVE_LIBSVN_CLIENT_1
58 #    include <svn_auth.h>
59 #    include <svn_client.h>
60 #    include <svn_cmdline.h>
61 #    include <svn_pools.h>
62 #  else
63 #    undef HAVE_SVN_CLIENT_H
64 #  endif
65 #endif
66
67 using namespace std;
68
69 const char* source_base = NULL;
70 const char* svn_base =
71   "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
72 const char* rsync_base = "scenery.flightgear.org::Scenery";
73 const char* dest_base = "terrasyncdir";
74 const char* rsync_cmd = 
75     "rsync --verbose --archive --delete --perms --owner --group";
76
77 #ifdef HAVE_SVN_CLIENT_H
78 bool use_svn = true;
79 #else
80 bool use_svn = false;
81 const char* svn_cmd = "svn checkout";
82 #endif
83
84 // display usage
85 static void usage( const string& prog ) {
86     cout << 
87 "Usage:  terrasync [options]\n"
88 "Options:  \n"
89 " -d <dest>       destination directory [required]\n"
90 " -R              transport using pipe to rsync\n"
91 " -S              transport using built-in svn\n"
92 " -p <port>       listen on UDP port [default: 5501]\n"
93 " -s <source>     source base [default: '']\n"
94 " -pid <pidfile>  write PID to file\n"
95 " -v              be more verbose\n"
96 ;
97
98 #ifdef HAVE_SVN_CLIENT_H
99     cout << "    (defaults to the built in subversion)" << endl;
100 #else
101     cout << "    (defaults to rsync, using external commands)" << endl;
102 #endif
103
104   cout << "\nExample:\n"
105 "pid=$(cat $pidfile 2>/dev/null)\n"
106 "if test -n \"$pid\" && kill -0 $pid ; then\n"
107 "    echo \"terrasync already running: $pid\"\n"
108 "else\n"
109 "    nice /games/sport/fgs/utils/TerraSync/terrasync         \\\n"
110 "      -v -pid $pidfile -S -p 5500 -d /games/orig/terrasync &\n"
111 "fi" << endl;
112
113 }
114
115 deque<string> waitingTiles;
116 typedef map<string,time_t> CompletedTiles;
117 CompletedTiles completedTiles;
118 netSocket theSocket;
119
120 #ifdef HAVE_SVN_CLIENT_H
121
122 // Things we need for doing subversion checkout - often
123 apr_pool_t *mysvn_pool = NULL;
124 svn_client_ctx_t *mysvn_ctx = NULL;
125 svn_opt_revision_t *mysvn_rev = NULL;
126 svn_opt_revision_t *mysvn_rev_peg = NULL;
127
128 static const svn_version_checklist_t mysvn_checklist[] = {
129     { "svn_subr",   svn_subr_version },
130     { "svn_client", svn_client_version },
131     { NULL, NULL }
132 };
133
134 // Configure our subversion session
135 int mysvn_setup(void) {
136     // Are we already prepared?
137     if (mysvn_pool) return EXIT_SUCCESS;
138     // No, so initialize svn internals generally
139 #ifdef _MSC_VER
140     // there is a segfault when providing an error stream.
141     //  Apparently, calling setvbuf with a nul buffer is
142     //  not supported under msvc 7.1 ( code inside svn_cmdline_init )
143     if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
144         return EXIT_FAILURE;
145 #else
146     if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
147         return EXIT_FAILURE;
148 #endif
149     apr_pool_t *pool;
150     apr_pool_create(&pool, NULL);
151     svn_error_t *err = NULL;
152     SVN_VERSION_DEFINE(mysvn_version);
153     err = svn_ver_check_list(&mysvn_version, mysvn_checklist);
154     if (err)
155         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
156     err = svn_ra_initialize(pool);
157     if (err)
158         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
159     char *config_dir = NULL;
160     err = svn_config_ensure(config_dir, pool);
161     if (err)
162         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
163     err = svn_client_create_context(&mysvn_ctx, pool);
164     if (err)
165         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
166     err = svn_config_get_config(&(mysvn_ctx->config),
167         config_dir, pool);
168     if (err)
169         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
170     svn_config_t *cfg;
171     cfg = ( svn_config_t*) apr_hash_get(
172         mysvn_ctx->config,
173         SVN_CONFIG_CATEGORY_CONFIG,
174         APR_HASH_KEY_STRING);
175     if (err)
176         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
177     svn_auth_baton_t *ab;
178     err = svn_cmdline_setup_auth_baton(&ab,
179         TRUE, NULL, NULL, config_dir, TRUE, cfg,
180         mysvn_ctx->cancel_func, mysvn_ctx->cancel_baton, pool);
181     if (err)
182         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
183     mysvn_ctx->auth_baton = ab;
184     mysvn_ctx->conflict_func = NULL;
185     mysvn_ctx->conflict_baton = NULL;
186     // Now our magic revisions
187     mysvn_rev = (svn_opt_revision_t*) apr_palloc(pool, 
188         sizeof(svn_opt_revision_t));
189     if (!mysvn_rev)
190         return EXIT_FAILURE;
191     mysvn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool, 
192         sizeof(svn_opt_revision_t));
193     if (!mysvn_rev_peg)
194         return EXIT_FAILURE;
195     mysvn_rev->kind = svn_opt_revision_head;
196     mysvn_rev_peg->kind = svn_opt_revision_unspecified;
197     // Success if we got this far
198     mysvn_pool = pool;
199     return EXIT_SUCCESS;
200 }
201
202 #endif
203
204 // sync one directory tree
205 void sync_tree(const char* dir) {
206     int rc;
207     char command[512];
208     SGPath path( dest_base );
209
210     path.append( dir );
211     rc = path.create_dir( 0755 );
212     if (rc) {
213         cout << "Return code = " << rc << endl;
214         exit(1);
215     }
216
217     if (use_svn) {
218 #ifdef HAVE_SVN_CLIENT_H
219         cout << dir << " ... ";
220         cout.flush();
221         char dest_base_dir[512];
222         snprintf( command, 512,
223             "%s/%s", source_base, dir);
224         snprintf( dest_base_dir, 512,
225             "%s/%s", dest_base, dir);
226         svn_error_t *err = NULL;
227         if (mysvn_setup() != EXIT_SUCCESS)
228             exit(1);
229         apr_pool_t *subpool = svn_pool_create(mysvn_pool);
230         err = svn_client_checkout3(NULL,
231             command,
232             dest_base_dir,
233             mysvn_rev_peg,
234             mysvn_rev,
235             svn_depth_infinity,
236             0,
237             0,
238             mysvn_ctx,
239             subpool);
240         if (err) {
241             // Report errors from the checkout attempt
242             cout << "failed: " << endl
243                  << err->message << endl;
244             svn_error_clear(err);
245             return;
246         } else {
247             cout << "done" << endl;
248         }
249         svn_pool_destroy(subpool);
250         return;
251 #else
252
253         snprintf( command, 512,
254             "%s %s/%s %s/%s", svn_cmd,
255             source_base, dir,
256             dest_base, dir );
257 #endif
258     } else {
259         snprintf( command, 512,
260             "%s %s/%s/ %s/%s/", rsync_cmd,
261             source_base, dir,
262             dest_base, dir );
263     }
264     cout << command << endl;
265     rc = system( command );
266     if (rc) {
267         cout << "Return code = " << rc << endl;
268         if (rc == 5120) exit(1);
269     }
270 }
271
272 #ifdef _MSC_VER
273 typedef void (__cdecl * sighandler_t)(int);
274 #elif defined( __APPLE__ )
275 typedef sig_t sighandler_t;
276 #endif
277
278 bool terminating = false;
279 sighandler_t prior_signal_handlers[32];
280 int termination_triggering_signals[] = {
281 #ifndef _MSC_VER
282     SIGHUP, SIGINT, SIGQUIT, SIGKILL,
283 #else
284     SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM, SIGBREAK, SIGABRT,
285 #endif
286     0};  // zero terminated
287
288 void terminate_request_handler(int param) {
289     char msg[] = "\nReceived signal XX, intend to exit soon.\n"
290          "repeat the signal to force immediate termination.\n";
291     msg[17] = '0' + param / 10;
292     msg[18] = '0' + param % 10;
293     write(1, msg, sizeof(msg) - 1);
294     terminating = true;
295     signal(param, prior_signal_handlers[param]);
296     theSocket.close();
297 }
298
299
300 const int nowhere = -9999;
301
302
303 // parse message
304 static void parse_message( const string &msg, int *lat, int *lon ) {
305     double dlat, dlon;
306     string text = msg;
307
308     // find GGA string and advance to start of lat
309     string::size_type pos = text.find( "$GPGGA" );
310     if ( pos == string::npos )
311     {
312         *lat = nowhere;
313         *lon = nowhere;
314         return;
315     }
316     string tmp = text.substr( pos + 7 );
317     pos = tmp.find( "," );
318     tmp = tmp.substr( pos + 1 );
319     // cout << "-> " << tmp << endl;
320
321     // find lat then advance to start of hemisphere
322     pos = tmp.find( "," );
323     string lats = tmp.substr( 0, pos );
324     dlat = atof( lats.c_str() ) / 100.0;
325     tmp = tmp.substr( pos + 1 );
326
327     // find N/S hemisphere and advance to start of lon
328     if ( tmp.substr( 0, 1 ) == "S" ) {
329         dlat = -dlat;
330     }
331     pos = tmp.find( "," );
332     tmp = tmp.substr( pos + 1 );
333
334     // find lon
335     pos = tmp.find( "," );
336     string lons = tmp.substr( 0, pos );
337     dlon = atof( lons.c_str() ) / 100.0;
338     tmp = tmp.substr( pos + 1 );
339
340     // find E/W hemisphere and advance to start of lon
341     if ( tmp.substr( 0, 1 ) == "W" ) {
342         dlon = -dlon;
343     }
344
345     if ( dlat < 0 ) {
346         *lat = (int)dlat - 1;
347     } else {
348         *lat = (int)dlat;
349     }
350
351     if ( dlon < 0 ) {
352         *lon = (int)dlon - 1;
353     } else {
354         *lon = (int)dlon;
355     }
356
357     if ((dlon == 0) && (dlat == 0)) {
358       *lon = nowhere;
359       *lat = nowhere;
360     }
361 }
362
363
364 // sync area
365 static void sync_area( int lat, int lon ) {
366     if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
367         return;
368     char NS, EW;
369     int baselat, baselon;
370
371     if ( lat < 0 ) {
372         int base = (int)(lat / 10);
373         if ( lat == base * 10 ) {
374             baselat = base * 10;
375         } else {
376             baselat = (base - 1) * 10;
377         }
378         NS = 's';
379     } else {
380         baselat = (int)(lat / 10) * 10;
381         NS = 'n';
382     }
383     if ( lon < 0 ) {
384         int base = (int)(lon / 10);
385         if ( lon == base * 10 ) {
386             baselon = base * 10;
387         } else {
388             baselon = (base - 1) * 10;
389         }
390         EW = 'w';
391     } else {
392         baselon = (int)(lon / 10) * 10;
393         EW = 'e';
394     }
395
396     const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
397     
398     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
399         char dir[512];
400         snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
401                 *tree,
402                 EW, abs(baselon), NS, abs(baselat),
403                 EW, abs(lon), NS, abs(lat) );
404         waitingTiles.push_back( dir );
405     }
406 }
407
408
409 // sync areas
410 static void sync_areas( int lat, int lon, int lat_dir, int lon_dir ) {
411     // do current 1x1 degree area first
412     sync_area( lat, lon );
413
414     if ( lat_dir == 0 && lon_dir == 0 ) {
415         // now do surrounding 8 1x1 degree areas.
416         for ( int i = lat - 1; i <= lat + 1; ++i ) {
417             for ( int j = lon - 1; j <= lon + 1; ++j ) {
418                 if ( i != lat || j != lon ) {
419                     sync_area( i, j );
420                 }
421             }
422         }
423     } else {
424         if ( lat_dir != 0 ) {
425             sync_area( lat + lat_dir, lon );
426             sync_area( lat + lat_dir, lon - 1 );
427             sync_area( lat + lat_dir, lon + 1 );
428         }
429         if ( lon_dir != 0 ) {
430             sync_area( lat, lon + lon_dir );
431             sync_area( lat - 1, lon + lon_dir );
432             sync_area( lat + 1, lon + lon_dir );
433         }
434     }
435 }
436
437 void getWaitingTile() {
438     while ( !waitingTiles.empty() ) {
439         CompletedTiles::iterator ii =
440             completedTiles.find( waitingTiles.front() );
441         time_t now = time(0);
442         if ( ii == completedTiles.end() || ii->second + 600 < now ) {
443             sync_tree(waitingTiles.front().c_str());
444             completedTiles[ waitingTiles.front() ] = now;
445             waitingTiles.pop_front();
446             break;
447         }
448         waitingTiles.pop_front();
449     }
450 }
451
452 int main( int argc, char **argv ) {
453     int port = 5501;
454     char host[256] = "localhost";
455     bool testing = false;
456     bool do_checkout(true);
457     int verbose(0);
458     const char* pidfn = "";
459
460     // parse arguments
461     int i = 1;
462     while ( i < argc ) {
463         if ( (string)argv[i] == "-p" ) {
464             ++i;
465             port = atoi( argv[i] );
466         } else if ( string(argv[i]).find("-pid") == 0 ) {
467             ++i;
468             pidfn = argv[i];
469             cout << "pidfn: " << pidfn << endl;
470         } else if ( (string)argv[i] == "-s" ) {
471             ++i;
472             source_base = argv[i];
473         } else if ( (string)argv[i] == "-d" ) {
474             ++i;
475             dest_base = argv[i];
476         } else if ( (string)argv[i] == "-R" ) {
477             use_svn = false;
478         } else if ( (string)argv[i] == "-S" ) {
479             use_svn = true;
480         } else if ( (string)argv[i] == "-v" ) {
481             verbose++;
482         } else if ( (string)argv[i] == "-T" ) {
483             testing = true;
484         } else if ( (string)argv[i] == "-h" ) {
485             usage( argv[0] );
486             exit(0);
487         } else {
488             cerr << "Unrecognized verbiage '" << argv[i] << "'" << endl;
489             usage( argv[0] );
490             exit(-1);        
491         }
492         ++i;
493     }
494
495     if (*pidfn) {
496       ofstream pidstream;
497       pidstream.open(pidfn);
498       if (!pidstream.good()) {
499         cerr << "Cannot open pid file '" << pidfn << "': ";
500         perror(0);
501         exit(2);
502       }
503       pidstream << getpid() << endl;
504       pidstream.close();
505     }
506
507     // Use the appropriate default for the "-s" flag
508     if (source_base == NULL) {
509         if (use_svn)
510             source_base = svn_base;
511         else
512             source_base = rsync_base;
513     }
514     
515     // Must call this before any other net stuff
516     netInit( &argc,argv );
517
518     if ( ! theSocket.open( false ) ) {  // open a UDP socket
519         printf("error opening socket\n");
520         return -1;
521     }
522
523     if ( theSocket.bind( host, port ) == -1 ) {
524         printf("error binding to port %d\n", port);
525         return -1;
526     }
527
528     char msg[256];
529     int maxlen = 256;
530     int len;
531     int lat, lon;
532     int last_lat = nowhere;
533     int last_lon = nowhere;
534     bool recv_msg = false;
535
536     char synced_other;
537     if (do_checkout) {
538         for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ ) {
539             char dir[512];
540             snprintf( dir, 512, "Airports/%c", synced_other );
541             waitingTiles.push_back( dir );
542         }
543         for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ ) {
544             char dir[512];
545             snprintf( dir, 512, "Airports/%c", synced_other );
546             waitingTiles.push_back( dir );
547         }
548         if ( use_svn ) {
549             waitingTiles.push_back( "Models" );
550         }
551     }
552
553
554     for (int* sigp=termination_triggering_signals; *sigp; sigp++) {
555         prior_signal_handlers[*sigp] =
556             signal(*sigp, *terminate_request_handler);
557         if (verbose) cout << "Intercepted signal " << *sigp << endl;
558     }
559
560     while ( !terminating ) {
561         // main loop
562         recv_msg = false;
563         if ( testing ) {
564             // No FGFS communications
565             lat = 37;
566             lon = -123;
567             recv_msg = (lat != last_lat) || (lon != last_lon);
568         } else {
569             if (verbose && waitingTiles.empty()) {
570                 cout << "Idle; waiting for FlightGear position\n";
571             }
572             theSocket.setBlocking(waitingTiles.empty());
573             len = theSocket.recv(msg, maxlen, 0);
574             if (len >= 0) {
575                 msg[len] = '\0';
576                 recv_msg = true;
577                 if (verbose) cout << "recv length: " << len << endl;
578                 parse_message( msg, &lat, &lon );
579             }
580         }
581
582         if ( recv_msg ) {
583              // Ignore messages where the location does not change
584              if ( lat != last_lat || lon != last_lon ) {
585                 cout << "pos in msg = " << lat << "," << lon << endl;
586                 deque<string> oldRequests;
587                 oldRequests.swap( waitingTiles );
588                 int lat_dir, lon_dir, dist;
589                 if ( last_lat == nowhere || last_lon == nowhere ) {
590                     lat_dir = lon_dir = 0;
591                 } else {
592                     dist = lat - last_lat;
593                     if ( dist != 0 ) {
594                         lat_dir = dist / abs(dist);
595                     } else {
596                         lat_dir = 0;
597                     }
598                     dist = lon - last_lon;
599                     if ( dist != 0 ) {
600                         lon_dir = dist / abs(dist);
601                     } else {
602                         lon_dir = 0;
603                     }
604                 }
605                 cout << "lat = " << lat << " lon = " << lon << endl;
606                 cout << "lat_dir = " << lat_dir << "  "
607                      << "lon_dir = " << lon_dir << endl;
608                 sync_areas( lat, lon, lat_dir, lon_dir );
609                 while ( !oldRequests.empty() ) {
610                     waitingTiles.push_back( oldRequests.front() );
611                     oldRequests.pop_front();
612                 }
613                 last_lat = lat;
614                 last_lon = lon;
615             }
616         }
617
618         // No messages inbound, so process some pending work
619         else if ( !waitingTiles.empty() ) {
620             getWaitingTile();
621         }
622
623         else if ( testing ) {
624             terminating = true;
625         } else
626
627         ulSleep( 1 );
628     } // while !terminating
629         
630     return 0;
631 }