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