Exemplo n.º 1
0
con_vec Turtle5(situation &s)
{
  con_vec result = { 0.0f, 0.0f, 0.0f, 0, 0 }; // This is what is returned.
  static int firstcall = 1;

  if (firstcall)
  {                               //  this is the very first call
    my_name_is("Turtle5");        //  this lets everyone know who we are.
    firstcall = 0;                //  theres only one first call
    return result;                //  must return an answer
  }

  if(s.starting) 
  {
    result.fuel_amount = MAX_FUEL;
  }

  double width = s.to_lft + s.to_rgt;
  double track_middle = (s.to_lft+s.to_rgt)/2;
  double directionoftravel = asin(s.vn/s.v);
  double to_end = curvelength(s.to_end, s.cur_rad);

  if (to_end < width)
  {
	  to_end = width;
  }
  
  double ideal_alpha =  atan((s.to_lft - track_middle)  / to_end);

  if (s.cur_rad != 0)  // in other words, we are in a curve
  {
    ideal_alpha =  atan((s.to_lft - track_middle)  / to_end);
  }
  result.alpha = ideal_alpha - directionoftravel;


  result.vc = curvespeed(s.cur_rad);
  if (s.to_end < distancetobraketo(s.v, curvespeed(s.nex_rad)))
  {
    result.vc = 0;
  }

  result.request_pit=0;
  if (s.stage != QUALIFYING && (s.damage > 25000 || s.fuel < 10))
  {
    result.request_pit=1;
    result.repair_amount=s.damage;
    result.fuel_amount=MAX_FUEL;
  }
  return result;                    // here too.
}
Exemplo n.º 2
0
con_vec O1(situation& s){con_vec r;double 
e,v,c,n,x;my_name_is("O1");e=s.to_end;x=s.nex_rad;n=k(x);c=s.cur_rad;if(c){v=k(c);if(x)if(n
<s.v)if(e*55*(20+(c<0?-c:c))<s.v*s.v-n*n)v=n;}else{v=250;if(n<s.v)if(72*e<s.v*s.v-
n*n)v=n;}r.vc=v;r.alpha=((c?(c<0?-50:50):(x<0?-50:50))+s.to_lft-
s.to_rgt)*.0075+(s.dead_ahead?0.1:0)-2*s.vn/s.v;

if(s.starting) r.fuel_amount = MAX_FUEL;
r.request_pit = 0;
if (s.stage != QUALIFYING && (s.damage > 25000 || s.fuel < 10))
  {
  r.request_pit = 1;
  r.repair_amount=s.damage;
  r.fuel_amount = MAX_FUEL;
  }
return r;}
Exemplo n.º 3
0
int main (int argc, char *argv[])
{
   int ch;
#if defined(HAVE_DYNAMIC_CATS_BACKENDS)
   alist *backend_directories = NULL;
#endif
   char *jobids = (char *)"1";
   char *path=NULL, *client=NULL;
   uint64_t limit=0;
   bool clean=false;
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();

   Dmsg0(0, "Starting bvfs_test tool\n");

   my_name_is(argc, argv, "bvfs_test");
   init_msg(NULL, NULL);

   OSDependentInit();

   while ((ch = getopt(argc, argv, "h:c:l:d:D:n:P:Su:vf:w:?j:p:f:T")) != -1) {
      switch (ch) {
      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'D':
         db_driver = optarg;
         break;

      case 'l':
         limit = str_to_int64(optarg);
         break;

      case 'c':
         client = optarg;
         break;

      case 'h':
         db_host = optarg;
         break;

      case 'n':
         db_name = optarg;
         break;

      case 'w':
         working_directory = optarg;
         break;

      case 'u':
         db_user = optarg;
         break;

      case 'P':
         db_password = optarg;
         break;

      case 'v':
         verbose++;
         break;

      case 'p':
         path = optarg;
         break;

      case 'f':
         file = optarg;
         break;

      case 'j':
         jobids = optarg;
         break;

      case 'T':
         clean = true;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 0) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }
   JCR *bjcr = new_jcr(sizeof(JCR), NULL);
   bjcr->JobId = getpid();
   bjcr->setJobType(JT_CONSOLE);
   bjcr->setJobLevel(L_FULL);
   bjcr->JobStatus = JS_Running;
   bjcr->client_name = get_pool_memory(PM_FNAME);
   pm_strcpy(bjcr->client_name, "Dummy.Client.Name");
   bstrncpy(bjcr->Job, "bvfs_test", sizeof(bjcr->Job));

#if defined(HAVE_DYNAMIC_CATS_BACKENDS)
   backend_directories = New(alist(10, owned_by_alist));
   backend_directories->append((char *)backend_directory);

   db_set_backend_dirs(backend_directories);
#endif

   if ((db = db_init_database(NULL, NULL, db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
      Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
   }
   Dmsg1(0, "db_type=%s\n", db_get_type(db));

   if (!db_open_database(NULL, db)) {
      Emsg0(M_ERROR_TERM, 0, db_strerror(db));
   }
   Dmsg0(200, "Database opened\n");
   if (verbose) {
      Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
   }

   bjcr->db = db;

   if (clean) {
      Pmsg0(0, "Clean old table\n");
      db_sql_query(db, "DELETE FROM PathHierarchy", NULL, NULL);
      db_sql_query(db, "UPDATE Job SET HasCache=0", NULL, NULL);
      db_sql_query(db, "DELETE FROM PathVisibility", NULL, NULL);
      bvfs_update_cache(bjcr, db);
   }

   Bvfs fs(bjcr, db);
   fs.set_handler(result_handler, &fs);

   fs.set_jobids(jobids);
   fs.update_cache();
   if (limit)
      fs.set_limit(limit);

   if (path) {
      fs.ch_dir(path);
      fs.ls_special_dirs();
      fs.ls_dirs();
      while (fs.ls_files()) {
         fs.next_offset();
      }

      if (fnid && client) {
         Pmsg0(0, "---------------------------------------------\n");
         Pmsg1(0, "Getting file version for %s\n", file);
         fs.get_all_file_versions(fs.get_pwd(), fnid, client);
      }

      exit (0);
   }


   Pmsg0(0, "list /\n");
   fs.ch_dir("/");
   fs.ls_special_dirs();
   fs.ls_dirs();
   fs.ls_files();

   Pmsg0(0, "list /tmp/\n");
   fs.ch_dir("/tmp/");
   fs.ls_special_dirs();
   fs.ls_dirs();
   fs.ls_files();

   Pmsg0(0, "list /tmp/regress/\n");
   fs.ch_dir("/tmp/regress/");
   fs.ls_special_dirs();
   fs.ls_files();
   fs.ls_dirs();

   Pmsg0(0, "list /tmp/regress/build/\n");
   fs.ch_dir("/tmp/regress/build/");
   fs.ls_special_dirs();
   fs.ls_dirs();
   fs.ls_files();

   fs.get_all_file_versions(1, 347, "zog4-fd");

   char p[200];
   strcpy(p, "/tmp/toto/rep/");
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "/tmp/toto/")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "/tmp/")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "/")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }

   return 0;
}
Exemplo n.º 4
0
int main (int argc, char *argv[])
{
   int ch;
   FILE *fd;
   char line[1000];
   bool got_inc = false;

   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();
   lmgr_init_thread();

   working_directory = "/tmp";
   my_name_is(argc, argv, "bextract");
   init_msg(NULL, NULL);              /* setup message handler */

   OSDependentInit();

   ff = init_find_files();
   binit(&bfd);

   while ((ch = getopt(argc, argv, "b:c:D:d:e:i:pvV:?")) != -1) {
      switch (ch) {
      case 'b':                    /* bootstrap file */
         bsr = parse_bsr(NULL, optarg);
//       dump_bsr(bsr, true);
         break;

      case 'c':                    /* specify config file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'D':                    /* specify director name */
         if (DirectorName != NULL) {
            free(DirectorName);
         }
         DirectorName = bstrdup(optarg);
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'e':                    /* exclude list */
         if ((fd = fopen(optarg, "rb")) == NULL) {
            berrno be;
            Pmsg2(0, _("Could not open exclude file: %s, ERR=%s\n"),
               optarg, be.bstrerror());
            exit(1);
         }
         while (fgets(line, sizeof(line), fd) != NULL) {
            strip_trailing_junk(line);
            Dmsg1(900, "add_exclude %s\n", line);
            add_fname_to_exclude_list(ff, line);
         }
         fclose(fd);
         break;

      case 'i':                    /* include list */
         if ((fd = fopen(optarg, "rb")) == NULL) {
            berrno be;
            Pmsg2(0, _("Could not open include file: %s, ERR=%s\n"),
               optarg, be.bstrerror());
            exit(1);
         }
         while (fgets(line, sizeof(line), fd) != NULL) {
            strip_trailing_junk(line);
            Dmsg1(900, "add_include %s\n", line);
            add_fname_to_include_list(ff, 0, line);
         }
         fclose(fd);
         got_inc = true;
         break;

      case 'p':
         forge_on = true;
         break;

      case 'v':
         verbose++;
         break;

      case 'V':                    /* Volume name */
         VolumeName = optarg;
         break;

      case '?':
      default:
         usage();

      } /* end switch */
   } /* end while */
   argc -= optind;
   argv += optind;

   if (argc != 2) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   config = new_config_parser();
   parse_sd_config(config, configfile, M_ERROR_TERM);

   LockRes();
   me = (STORES *)GetNextRes(R_STORAGE, NULL);
   if (!me) {
      UnlockRes();
      Emsg1(M_ERROR_TERM, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
         configfile);
   }
   UnlockRes();

  if (DirectorName) {
      foreach_res(director, R_DIRECTOR) {
         if (bstrcmp(director->hdr.name, DirectorName)) {
            break;
         }
      }
      if (!director) {
         Emsg2(M_ERROR_TERM, 0, _("No Director resource named %s defined in %s. Cannot continue.\n"),
               DirectorName, configfile);
      }
   }

   load_sd_plugins(me->plugin_directory);

   read_crypto_cache(me->working_directory, "bareos-sd",
                     get_first_port_host_order(me->sdaddrs));

   if (!got_inc) {                            /* If no include file, */
      add_fname_to_include_list(ff, 0, "/");  /*   include everything */
   }

   where = argv[1];
   do_extract(argv[0]);

   if (bsr) {
      free_bsr(bsr);
   }
   if (prog_name_msg) {
      Pmsg1(000, _("%d Program Name and/or Program Data Stream records ignored.\n"),
         prog_name_msg);
   }
   if (win32_data_msg) {
      Pmsg1(000, _("%d Win32 data or Win32 gzip data stream records. Ignored.\n"),
         win32_data_msg);
   }
   term_include_exclude_files(ff);
   term_find_files(ff);
   return 0;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
   int ch;
   bool no_signals = true;
   bool test_config = false;


   app = new QApplication(argc, argv);        
   app->setQuitOnLastWindowClosed(true);
   QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
     
   QTranslator qtTranslator;
   qtTranslator.load(QString("qt_") + QLocale::system().name());
   app->installTranslator(&qtTranslator);

   QTranslator batTranslator;
   batTranslator.load(QString("bat_") + QLocale::system().name());
   app->installTranslator(&batTranslator);



#ifdef xENABLE_NLS
   setlocale(LC_ALL, "");
   bindtextdomain("bacula", LOCALEDIR);
   textdomain("bacula");
#endif

   init_stack_dump();
   my_name_is(argc, argv, "bat");
   init_msg(NULL, NULL);
   working_directory  = "/tmp";

   struct sigaction sigignore;
   sigignore.sa_flags = 0;
   sigignore.sa_handler = SIG_IGN;
   sigfillset(&sigignore.sa_mask);
   sigaction(SIGPIPE, &sigignore, NULL);
   sigaction(SIGUSR2, &sigignore, NULL);


   while ((ch = getopt(argc, argv, "bc:d:r:st?")) != -1) {
      switch (ch) {
      case 'c':                    /* configuration file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':
         debug_level = atoi(optarg);
         if (debug_level <= 0)
            debug_level = 1;
         break;

      case 's':                    /* turn off signals */
         no_signals = true;
         break;

      case 't':
         test_config = true;
         break;

      case '?':
      default:
         usage();
      }
   }
   argc -= optind;
   argv += optind;


   if (!no_signals) {
      init_signals(terminate_console);
   }

   if (argc) {
      usage();
   }

   OSDependentInit();
#ifdef HAVE_WIN32
   WSA_Init();                        /* Initialize Windows sockets */
#endif

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   config = new_config_parser();
   parse_bat_config(config, configfile, M_ERROR_TERM);

   if (init_crypto() != 0) {
      Emsg0(M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
   }

   if (!check_resources()) {
      Emsg1(M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
   }

   mainWin = new MainWin;
   mainWin->show();

   return app->exec();
}
Exemplo n.º 6
0
int main (int argc, char *argv[])
{
   int ch;
   char *jobids = (char *)"1";
   char *path=NULL, *client=NULL;
   uint64_t limit=0;
   bool clean=false;
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();

   Dmsg0(0, "Starting ing_test tool\n");

   my_name_is(argc, argv, "ing_test");
   init_msg(NULL, NULL);

   OSDependentInit();

   while ((ch = getopt(argc, argv, "h:c:l:d:n:P:Su:vf:w:?j:p:f:T")) != -1) {
      switch (ch) {
      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;
      case 'l':
         limit = str_to_int64(optarg);
         break;

      case 'c':
         client = optarg;
         break;

      case 'h':
         db_host = optarg;
         break;

      case 'n':
         db_name = optarg;
         break;

      case 'w':
         working_directory = optarg;
         break;

      case 'u':
         db_user = optarg;
         break;

      case 'P':
         db_password = optarg;
         break;

      case 'v':
         verbose++;
         break;

      case 'p':
         path = optarg;
         break;

      case 'f':
         file = optarg;
         break;

      case 'j':
         jobids = optarg;
         break;

      case 'T':
         clean = true;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 0) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   if ((db = db_init_database(NULL, "ingres", db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
      Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
   }
   Dmsg1(0, "db_type=%s\n", db_get_type(db));

   if (!db_open_database(NULL, db)) {
      Emsg0(M_ERROR_TERM, 0, db_strerror(db));
   }
   Dmsg0(200, "Database opened\n");
   if (verbose) {
      Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
   }

   /*
    * simple CRUD test including create/drop table
    */
   Pmsg0(0, "\nsimple CRUD test...\n\n");
   const char *stmt1[8] = {
      "CREATE TABLE t1 ( c1 integer, c2 varchar(29))",
      "INSERT INTO t1 VALUES (1, 'foo')",
      "SELECT c1,c2 FROM t1",
      "UPDATE t1 SET c2='bar' WHERE c1=1",
      "SELECT * FROM t1",
      "DELETE FROM t1 WHERE c2 LIKE '\%r'",
      "SELECT * FROM t1",
      "DROP TABLE t1"
   };
   int (*hndl1[8])(void*,int,char**) = {
      NULL,
      NULL,
      test_handler,
      NULL,
      test_handler,
      NULL,
      test_handler,
      NULL
   };

   for (int i=0; i<8; ++i) {
      Pmsg1(0, "DB-Statement: %s\n",stmt1[i]);
      if (!db_sql_query(db, stmt1[i], hndl1[i], NULL)) {
         Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n"));
      }
   }


   /*
    * simple SELECT tests without tables
    */
   Pmsg0(0, "\nsimple SELECT tests without tables...\n\n");
   const char *stmt2[8] = {
      "SELECT 'Test of simple SELECT!'",
      "SELECT 'Test of simple SELECT!' as Text",
      "SELECT VARCHAR(LENGTH('Test of simple SELECT!'))",
      "SELECT DBMSINFO('_version')",
      "SELECT 'This is a ''quoting'' test with single quotes'",
      "SELECT 'This is a \"quoting\" test with double quotes'",
      "SELECT null",
      "SELECT ''"
   };
   int (*hndl2[8])(void*,int,char**) = {
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler
   };

   for (int i=0; i<8; ++i) {
      Pmsg1(0, "DB-Statement: %s\n",stmt2[i]);
      if (!db_sql_query(db, stmt2[i], hndl2[i], NULL)) {
         Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n"));
      }
   }

   /*
    * testing aggregates like avg, max, sum
    */
   Pmsg0(0, "\ntesting aggregates...\n\n");
   const char *stmt[11] = {
      "CREATE TABLE t1 (c1 integer, c2 varchar(29))",
      "INSERT INTO t1 VALUES (1,'foo')",
      "INSERT INTO t1 VALUES (2,'bar')",
      "INSERT INTO t1 VALUES (3,'fun')",
      "INSERT INTO t1 VALUES (4,'egg')",
      "SELECT max(c1) from t1",
      "SELECT sum(c1) from t1",
      "INSERT INTO t1 VALUES (5,NULL)",
      "SELECT count(*) from t1",
      "SELECT count(c2) from t1",
      "DROP TABLE t1"
   };
   int (*hndl[11])(void*,int,char**) = {
      NULL,
      NULL,
      NULL,
      NULL,
      NULL,
      string_handler,
      string_handler,
      NULL,
      string_handler,
      string_handler,
      NULL
   };

   for (int i=0; i<11; ++i) {
      Pmsg1(0, "DB-Statement: %s\n",stmt[i]);
      if (!db_sql_query(db, stmt[i], hndl[i], NULL)) {
         Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n"));
      }
   }


   /*
    * datatypes test
    */
   Pmsg0(0, "\ndatatypes test... (TODO)\n\n");


   Dmsg0(200, "DB-Statement: CREATE TABLE for datatypes\n");
   if (!db_sql_query(db, "CREATE TABLE t2 ("
     "c1        integer,"
     "c2        varchar(255),"
     "c3        char(255)"
     /* some more datatypes... "c4      ," */
     ")" , NULL, NULL)) {
      Emsg0(M_ERROR_TERM, 0, _("CREATE-Stmt went wrong\n"));
   }

   Dmsg0(200, "DB-Statement: DROP TABLE for datatypes\n");
   if (!db_sql_query(db, "DROP TABLE t2", NULL, NULL)) {
      Emsg0(M_ERROR_TERM, 0, _("DROP-Stmt went wrong\n"));
   }


   db_close_database(NULL, db);
   db_flush_backends();
   Dmsg0(200, "Database closed\n");

   return 0;
}
Exemplo n.º 7
0
con_vec Ralph2(situation &s)
{
static int firstcall = 1;
con_vec result = CON_VEC_EMPTY;   // This is what is returned.
double ideal_alpha;
int segnum, nxtseg, nxtnxtseg;


if (firstcall)
  {                               //  this is the very first call
  my_name_is("Ralph2");            //  this lets everyone know who
                                  //  we are.

  firstcall = 0;                  //  theres only one first call

  return result;                  //  must return an answer
  }

if (s.starting)
  {
  track = get_track_description();
  }

if(stuck(s.backward, s.v,s.vn, s.to_lft,s.to_rgt,
&result.alpha,&result.vc))
  return result;

getabsxy(s.seg_ID, s.to_lft, s.to_rgt, s.to_end);

// point A
segnum = s.seg_ID;
nxtseg = (segnum+1)%track.NSEG;
nxtnxtseg = (nxtseg+1)%track.NSEG;

if (s.cur_rad == 0.0)
  ideal_alpha = angleforcurve(nxtseg, s.v);
 else
  {
  // look for either an s curve or a situation where we have
  // an  s curve with a straight in the middle
  ideal_alpha = angleforcurve(segnum, s.v);

  if (curveradiuslow(nxtseg) != 0)
    {  // one curve following another.
  
    //  now we look to see if we have an s-curve situation
    if (curveradiuslow(segnum) * curveradiuslow(nxtseg)  < 0)
      {
      double nextcurvealpha = angleforcurve(nxtseg, s.v);

      // can we see next curve
      if (
          (curveradiuslow(segnum) > 0 &&  nextcurvealpha < ideal_alpha)
          ||
          (curveradiuslow(segnum) < 0 &&  nextcurvealpha > ideal_alpha)
         )
        ideal_alpha = nextcurvealpha;
      }
    }
   else
    {
       // not an s curve, check for opposite direction curves with
       // an intervening straight

    if (curveradiuslow(segnum) * curveradiuslow(nxtnxtseg)  < 0)
      {
      double nextcurvealpha = angleforcurve(nxtnxtseg, s.v);

      // can we see next curve
      if (
          (curveradiuslow(segnum) > 0 &&  nextcurvealpha < ideal_alpha)
          ||
          (curveradiuslow(segnum) < 0 &&  nextcurvealpha > ideal_alpha)
         )
        ideal_alpha = nextcurvealpha;
      }

    }

  }

result.alpha = ideal_alpha - gc_dot;
// point B

getspeed(s, result);
link_alpha_and_vc(s, result);
avoidcars2(s, result);

if(s.starting) result.fuel_amount = MAX_FUEL;
result.request_pit = 0;
 if (s.stage != QUALIFYING && (s.damage > 25000 || s.fuel < 10))
     {
     result.request_pit = 1;
     result.repair_amount=s.damage;
     result.fuel_amount = MAX_FUEL;
     }
	
return result;
}
Exemplo n.º 8
0
Arquivo: dird.c Projeto: AlD/bareos
int main (int argc, char *argv[])
{
   int ch;
   JCR *jcr;
   cat_op mode;
   bool no_signals = false;
   bool test_config = false;
   char *uid = NULL;
   char *gid = NULL;

   start_heap = sbrk(0);
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");

   init_stack_dump();
   my_name_is(argc, argv, "bareos-dir");
   init_msg(NULL, NULL);              /* initialize message handler */
   init_reload();
   daemon_start_time = time(NULL);

   console_command = run_console_command;

   while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?")) != -1) {
      switch (ch) {
      case 'c':                    /* specify config file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':                    /* set debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         Dmsg1(10, "Debug level = %d\n", debug_level);
         break;

      case 'f':                    /* run in foreground */
         background = false;
         break;

      case 'g':                    /* set group id */
         gid = optarg;
         break;

      case 'm':                    /* print kaboom output */
         prt_kaboom = true;
         break;

      case 'r':                    /* run job */
         if (runjob != NULL) {
            free(runjob);
         }
         if (optarg) {
            runjob = bstrdup(optarg);
         }
         break;

      case 's':                    /* turn off signals */
         no_signals = true;
         break;

      case 't':                    /* test config */
         test_config = true;
         break;

      case 'u':                    /* set uid */
         uid = optarg;
         break;

      case 'v':                    /* verbose */
         verbose++;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (!no_signals) {
      init_signals(terminate_dird);
   }

   if (argc) {
      if (configfile != NULL) {
         free(configfile);
      }
      configfile = bstrdup(*argv);
      argc--;
      argv++;
   }
   if (argc) {
      usage();
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   /*
    * See if we want to drop privs.
    */
   if (geteuid() == 0) {
      drop(uid, gid, false);                    /* reduce privileges if requested */
   }

   my_config = new_config_parser();
   parse_dir_config(my_config, configfile, M_ERROR_TERM);

   if (init_crypto() != 0) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
      goto bail_out;
   }

   if (!check_resources()) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
      goto bail_out;
   }

   if (!test_config) {                /* we don't need to do this block in test mode */
      if (background) {
         daemon_start();
         init_stack_dump();              /* grab new pid */
      }
      /* Create pid must come after we are a daemon -- so we have our final pid */
      create_pid_file(me->pid_directory, "bareos-dir",
                      get_first_port_host_order(me->DIRaddrs));
      read_state_file(me->working_directory, "bareos-dir",
                      get_first_port_host_order(me->DIRaddrs));
   }

   set_jcr_in_tsd(INVALID_JCR);
   set_thread_concurrency(me->MaxConcurrentJobs * 2 +
                          4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
   lmgr_init_thread(); /* initialize the lockmanager stack */

   load_dir_plugins(me->plugin_directory, me->plugin_names);

   /*
    * If we are in testing mode, we don't try to fix the catalog
    */
   mode = (test_config) ? CHECK_CONNECTION : UPDATE_AND_FIX;

   if (!check_catalog(mode)) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
      goto bail_out;
   }

   if (test_config) {
      terminate_dird(0);
   }

   if (!initialize_sql_pooling()) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
      goto bail_out;
   }

   my_name_is(0, NULL, me->name());    /* set user defined name */

   cleanup_old_files();

   p_db_log_insert = (db_log_insert_func)dir_db_log_insert;

#if !defined(HAVE_WIN32)
   signal(SIGHUP, reload_config);
#endif

   init_console_msg(working_directory);

   Dmsg0(200, "Start UA server\n");
   start_UA_server(me->DIRaddrs);

   start_watchdog();                  /* start network watchdog thread */

   if (me->jcr_watchdog_time) {
      init_jcr_subsystem(me->jcr_watchdog_time); /* start JCR watchdogs etc. */
   }

   init_job_server(me->MaxConcurrentJobs);

   dbg_jcr_add_hook(db_debug_print); /* used to debug B_DB connexion after fatal signal */

//   init_device_resources();

   Dmsg0(200, "wait for next job\n");
   /* Main loop -- call scheduler to get next job to run */
   while ( (jcr = wait_for_next_job(runjob)) ) {
      run_job(jcr);                   /* run job */
      free_jcr(jcr);                  /* release jcr */
      set_jcr_in_tsd(INVALID_JCR);
      if (runjob) {                   /* command line, run a single job? */
         break;                       /* yes, terminate */
      }
   }

   terminate_dird(0);

bail_out:
   return 0;
}
Exemplo n.º 9
0
int main (int argc, char *argv[])
{
   int ch;
   bool disable_batch = false;
   char *restore_list=NULL;
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();
   lmgr_init_thread();

   char **files = (char **) malloc (10 * sizeof(char *));
   int i;
   my_name_is(argc, argv, "bbatch");
   init_msg(NULL, NULL);

   OSDependentInit();

   while ((ch = getopt(argc, argv, "bBh:c:d:D:n:P:Su:vf:w:r:?")) != -1) {
      switch (ch) {
      case 'r':
         restore_list=bstrdup(optarg);
         break;

      case 'B':
         disable_batch = true;
         break;

      case 'b':
         disable_batch = false;
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'D':
         db_driver = optarg;
         break;

      case 'h':
         db_host = optarg;
         break;

      case 'n':
         db_name = optarg;
         break;

      case 'w':
         working_directory = optarg;
         break;

      case 'u':
         db_user = optarg;
         break;

      case 'P':
         db_password = optarg;
         break;

      case 'v':
         verbose++;
         break;

      case 'f':
         if (nb < 10 ) {
            files[nb++] = optarg;
         }
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 0) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   if (restore_list) {
      uint64_t nb_file=0;
      btime_t start, end;
      /* To use the -r option, the catalog should already contains records */

      if ((db = db_init_database(NULL, db_driver, db_name, db_user, db_password,
                                 db_host, 0, NULL, false, disable_batch)) == NULL) {
         Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
      }
      if (!db_open_database(NULL, db)) {
         Emsg0(M_ERROR_TERM, 0, db_strerror(db));
      }

      start = get_current_btime();
      db_get_file_list(NULL, db, restore_list, false, false, list_handler, &nb_file);
      end = get_current_btime();

      Pmsg3(0, _("Computing file list for jobid=%s files=%lld secs=%d\n"),
            restore_list, nb_file, (uint32_t)btime_to_unix(end-start));

      free(restore_list);
      return 0;
   }

   if (disable_batch) {
      printf("Without new Batch mode\n");
   } else {
      printf("With new Batch mode\n");
   }

   i = nb;
   while (--i >= 0) {
      pthread_t thid;
      JCR *bjcr = new_jcr(sizeof(JCR), NULL);
      bjcr->bsr = NULL;
      bjcr->VolSessionId = 1;
      bjcr->VolSessionTime = (uint32_t)time(NULL);
      bjcr->NumReadVolumes = 0;
      bjcr->NumWriteVolumes = 0;
      bjcr->JobId = getpid();
      bjcr->setJobType(JT_CONSOLE);
      bjcr->setJobLevel(L_FULL);
      bjcr->JobStatus = JS_Running;
      bjcr->where = bstrdup(files[i]);
      bjcr->job_name = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->job_name, "Dummy.Job.Name");
      bjcr->client_name = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->client_name, "Dummy.Client.Name");
      bstrncpy(bjcr->Job, "bbatch", sizeof(bjcr->Job));
      bjcr->fileset_name = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->fileset_name, "Dummy.fileset.name");
      bjcr->fileset_md5 = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->fileset_md5, "Dummy.fileset.md5");

      if ((db = db_init_database(NULL, db_driver, db_name, db_user, db_password,
                                 db_host, 0, NULL, false, false)) == NULL) {
         Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
      }
      if (!db_open_database(NULL, db)) {
         Emsg0(M_ERROR_TERM, 0, db_strerror(db));
      }
      Dmsg0(200, "Database opened\n");
      if (verbose) {
         Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
      }

      bjcr->db = db;

      pthread_create(&thid, NULL, do_batch, bjcr);
   }

   while (nb > 0) {
      bmicrosleep(1,0);
   }

   return 0;
}
Exemplo n.º 10
0
int main (int argc, char *argv[])
{
   int ch;
   char *iVolumeName = NULL;
   char *oVolumeName = NULL;
   bool ignore_label_errors = false;
   bool ok;

   setlocale(LC_ALL, "");
   bindtextdomain("bacula", LOCALEDIR);
   textdomain("bacula");
   init_stack_dump();

   my_name_is(argc, argv, "bcopy");
   init_msg(NULL, NULL);

   while ((ch = getopt(argc, argv, "b:c:d:i:o:pvw:?")) != -1) {
      switch (ch) {
      case 'b':
         bsr = parse_bsr(NULL, optarg);
         break;

      case 'c':                    /* specify config file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'i':                    /* input Volume name */
         iVolumeName = optarg;
         break;

      case 'o':                    /* output Volume name */
         oVolumeName = optarg;
         break;

      case 'p':
         ignore_label_errors = true;
         forge_on = true;
         break;

      case 'v':
         verbose++;
         break;

      case 'w':
         wd = optarg;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 2) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   OSDependentInit();

   working_directory = wd;

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   config = new_config_parser();
   parse_sd_config(config, configfile, M_ERROR_TERM);

   /* Setup and acquire input device for reading */
   Dmsg0(100, "About to setup input jcr\n");
   in_jcr = setup_jcr("bcopy", argv[0], bsr, iVolumeName, 1); /* read device */
   if (!in_jcr) {
      exit(1);
   }
   in_jcr->ignore_label_errors = ignore_label_errors;
   in_dev = in_jcr->dcr->dev;
   if (!in_dev) {
      exit(1);
   }

   /* Setup output device for writing */
   Dmsg0(100, "About to setup output jcr\n");
   out_jcr = setup_jcr("bcopy", argv[1], bsr, oVolumeName, 0); /* no acquire */
   if (!out_jcr) {
      exit(1);
   }
   out_dev = out_jcr->dcr->dev;
   if (!out_dev) {
      exit(1);
   }
   Dmsg0(100, "About to acquire device for writing\n");
   /* For we must now acquire the device for writing */
   out_dev->r_dlock();
   if (out_dev->open(out_jcr->dcr, OPEN_READ_WRITE) < 0) {
      Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), out_dev->errmsg);
      out_dev->dunlock();
      exit(1);
   }
   out_dev->dunlock();
   if (!acquire_device_for_append(out_jcr->dcr)) {
      free_jcr(in_jcr);
      exit(1);
   }
   out_block = out_jcr->dcr->block;

   ok = read_records(in_jcr->dcr, record_cb, mount_next_read_volume);

   if (ok || out_dev->can_write()) {
      if (!write_block_to_device(out_jcr->dcr)) {
         Pmsg0(000, _("Write of last block failed.\n"));
      }
   }

   Pmsg2(000, _("%u Jobs copied. %u records copied.\n"), jobs, records);

   free_jcr(in_jcr);
   free_jcr(out_jcr);

   in_dev->term();
   out_dev->term();
   return 0;
}
Exemplo n.º 11
0
/*********************************************************************
 *
 *         Main Bacula Tray Monitor -- User Interface Program
 *
 */
int main(int argc, char *argv[])
{   
   int ch, i, dir_index=-1;
   bool test_config = false;
   DIRRES* dird;
   CLIENT* filed;
   STORE* stored;

   setlocale(LC_ALL, "");
   bindtextdomain("bacula", LOCALEDIR);
   textdomain("bacula");

   init_stack_dump();
   my_name_is(argc, argv, "tray-monitor");
   lmgr_init_thread();
   init_msg(NULL, NULL, NULL);
   working_directory = "/tmp";

#ifndef HAVE_WIN32
   struct sigaction sigignore;
   sigignore.sa_flags = 0;
   sigignore.sa_handler = SIG_IGN;
   sigfillset(&sigignore.sa_mask);
   sigaction(SIGPIPE, &sigignore, NULL);
#endif

   while ((ch = getopt(argc, argv, "bc:d:th?f:s:")) != -1) {
      switch (ch) {
      case 'c':                    /* configuration file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 't':
         test_config = true;
         break;

      case 'h':
      case '?':
      default:
         usage();
         exit(1);
      }
   }
   argc -= optind;
   //argv += optind;

   if (argc) {
      usage();
      exit(1);
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   config = new_config_parser();
   parse_tmon_config(config, configfile, M_ERROR_TERM);

   LockRes();
   nitems = 0;
   foreach_res(monitor, R_MONITOR) {
      nitems++;
   }

   if (nitems != 1) {
      Emsg2(M_ERROR_TERM, 0,
         _("Error: %d Monitor resources defined in %s. You must define one and only one Monitor resource.\n"), nitems, configfile);
   }

   nitems = 0;
   foreach_res(dird, R_DIRECTOR) {
      dir_index=nitems;
      items[nitems].type = R_DIRECTOR;
      items[nitems].resource = dird;
      items[nitems].D_sock = NULL;
      items[nitems].state = warn;
      items[nitems].oldstate = warn;
      nitems++;
   }
Exemplo n.º 12
0
int main (int argc, char *argv[])
{
   int ch;
   bool ok;
   char *iVolumeName = NULL;
   char *oVolumeName = NULL;
   char *DirectorName = NULL;
   DIRRES *director = NULL;
   bool ignore_label_errors = false;
   DCR *in_dcr, *out_dcr;

   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();

   my_name_is(argc, argv, "bcopy");
   lmgr_init_thread();
   init_msg(NULL, NULL);

   while ((ch = getopt(argc, argv, "b:c:D:d:i:o:pvw:?")) != -1) {
      switch (ch) {
      case 'b':
         bsr = parse_bsr(NULL, optarg);
         break;

      case 'c':                    /* specify config file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'D':                    /* specify director name */
         if (DirectorName != NULL) {
            free(DirectorName);
         }
         DirectorName = bstrdup(optarg);
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'i':                    /* input Volume name */
         iVolumeName = optarg;
         break;

      case 'o':                    /* output Volume name */
         oVolumeName = optarg;
         break;

      case 'p':
         ignore_label_errors = true;
         forge_on = true;
         break;

      case 'v':
         verbose++;
         break;

      case 'w':
         wd = optarg;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 2) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   OSDependentInit();

   working_directory = wd;

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   my_config = new_config_parser();
   parse_sd_config(my_config, configfile, M_ERROR_TERM);

   if (DirectorName) {
      foreach_res(director, R_DIRECTOR) {
         if (bstrcmp(director->hdr.name, DirectorName)) {
            break;
         }
      }
      if (!director) {
         Emsg2(M_ERROR_TERM, 0, _("No Director resource named %s defined in %s. Cannot continue.\n"),
               DirectorName, configfile);
      }
   }

   load_sd_plugins(me->plugin_directory, me->plugin_names);

   read_crypto_cache(me->working_directory, "bareos-sd",
                     get_first_port_host_order(me->SDaddrs));

   /*
    * Setup and acquire input device for reading
    */
   Dmsg0(100, "About to setup input jcr\n");

   in_dcr = New(DCR);
   in_jcr = setup_jcr("bcopy", argv[0], bsr, director, in_dcr, iVolumeName, true); /* read device */
   if (!in_jcr) {
      exit(1);
   }

   in_jcr->ignore_label_errors = ignore_label_errors;

   in_dev = in_jcr->dcr->dev;
   if (!in_dev) {
      exit(1);
   }

   /*
    * Setup output device for writing
    */
   Dmsg0(100, "About to setup output jcr\n");

   out_dcr = New(DCR);
   out_jcr = setup_jcr("bcopy", argv[1], bsr, director, out_dcr, oVolumeName, false); /* write device */
   if (!out_jcr) {
      exit(1);
   }

   out_dev = out_jcr->dcr->dev;
   if (!out_dev) {
      exit(1);
   }

   Dmsg0(100, "About to acquire device for writing\n");

   /*
    * For we must now acquire the device for writing
    */
   out_dev->rLock(false);
   if (!out_dev->open(out_jcr->dcr, OPEN_READ_WRITE)) {
      Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), out_dev->errmsg);
      out_dev->Unlock();
      exit(1);
   }
   out_dev->Unlock();
   if (!acquire_device_for_append(out_jcr->dcr)) {
      free_jcr(in_jcr);
      exit(1);
   }
   out_block = out_jcr->dcr->block;

   ok = read_records(in_jcr->dcr, record_cb, mount_next_read_volume);

   if (ok || out_dev->can_write()) {
      if (!out_jcr->dcr->write_block_to_device()) {
         Pmsg0(000, _("Write of last block failed.\n"));
      }
   }

   Pmsg2(000, _("%u Jobs copied. %u records copied.\n"), jobs, records);

   in_dev->term();
   out_dev->term();

   free_jcr(in_jcr);
   free_jcr(out_jcr);

   return 0;
}
Exemplo n.º 13
0
/*********************************************************************
 *
 *         Main Bacula Tray Monitor -- User Interface Program
 *
 */
int main(int argc, char *argv[])
{
   int ch;
   DIRRES s_dird;
   CLIENT s_filed;
   STORE s_stored;

   char host[250];
   char daemon[20];
   char monitorname[100];
   char pw[200];
   int port = 0;

   char answer[1024];
   int retcode = STATE_UNKNOWN;

   unsigned int i, j;
   struct MD5Context md5c;
   unsigned char signature[16];


   struct sigaction sigignore;
   sigignore.sa_flags = 0;
   sigignore.sa_handler = SIG_IGN;
   sigfillset(&sigignore.sa_mask);
   sigaction(SIGPIPE, &sigignore, NULL);

   strcpy (pw, "");

   init_stack_dump();
   my_name_is(argc, argv, "check_bacula");
   textdomain("bacula");
   init_msg(NULL, NULL);

   while ((ch = getopt(argc, argv, "H:D:M:P:K:d:h?")) != -1) {

      switch (ch) {

                  case 'H':
                        strcpy (host, optarg);
                        break;

                  case 'D':
                        strcpy (daemon, optarg);
                        break;

                  case 'M':
                        strcpy (monitorname, optarg);
                        break;

                  case 'P':
                        port = atoi(optarg);
                        break;

                  case 'K':
                        strcpy (pw, optarg);
                        break;

                  case 'd':
                        debug_level = atoi(optarg);
                        if (debug_level <= 0) {
                           debug_level = 1;
                        }
                        break;

          case 'h':
          case '?':
          default:
                         usage();
                         exit(1);
      }
   }
   argc -= optind;
   //argv += optind;

   if (argc) {
      usage();
      exit(STATE_UNKNOWN);
   }

   lmgr_init_thread();

   char sig[100];
   MD5Init(&md5c);
   MD5Update(&md5c, (unsigned char *) pw, strlen(pw));
   MD5Final(signature, &md5c);
   for (i = j = 0; i < sizeof(signature); i++) {
      sprintf(&sig[j], "%02x", signature[i]);
      j += 2;
   }


   /* director ?  */
   if (strcmp (daemon, "dir") == 0) {

           if (port != 0)
                 s_dird.DIRport = port;
           else
                 s_dird.DIRport = 9101;

           s_dird.address  = host;
           s_dird.password = sig;
           s_dird.hdr.name = monitorname;

           mitem.type = R_DIRECTOR;
           mitem.resource = &s_dird;
           mitem.D_sock = NULL;

   } else if (strcmp (daemon, "sd") == 0) {

           if (port != 0)
                 s_stored.SDport = port;
           else
                 s_stored.SDport = 9103;

           s_stored.address = host;
           s_stored.password = sig;
           s_stored.hdr.name = monitorname;

           mitem.type = R_STORAGE;
           mitem.resource = &s_stored;
           mitem.D_sock = NULL;

   } else if (strcmp (daemon, "fd") == 0) {

           if (port != 0)
                 s_filed.FDport = port;
           else
                 s_filed.FDport = 9102;

           s_filed.address = host;
           s_filed.password = sig;
           s_filed.hdr.name = monitorname;

           mitem.type = R_CLIENT;
           mitem.resource = &s_filed;
           mitem.D_sock = NULL;

   } else {

           usage();
           exit(1);
   }


   if (mitem.type == R_DIRECTOR)
           retcode = docmd(&mitem, ".status dir current\n", answer);
   else
           retcode = docmd(&mitem, ".status current\n", answer);


   if (mitem.D_sock) {
         mitem.D_sock->signal(BNET_TERMINATE); /* send EOF */
         mitem.D_sock->close();
   }

   printf ("%s\n", answer);
   return retcode;
}
Exemplo n.º 14
0
Arquivo: bls.c Projeto: AlD/bareos
int main (int argc, char *argv[])
{
   int i, ch;
   FILE *fd;
   char line[1000];
   char *VolumeName = NULL;
   char *bsrName = NULL;
   char *DirectorName = NULL;
   bool ignore_label_errors = false;
   DIRRES *director = NULL;

   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();
   lmgr_init_thread();

   working_directory = "/tmp";
   my_name_is(argc, argv, "bls");
   init_msg(NULL, NULL);              /* initialize message handler */

   OSDependentInit();

   ff = init_find_files();

   while ((ch = getopt(argc, argv, "b:c:D:d:e:i:jkLpvV:?")) != -1) {
      switch (ch) {
      case 'b':
         bsrName = optarg;
         break;

      case 'c':                    /* specify config file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'D':                    /* specify director name */
         if (DirectorName != NULL) {
            free(DirectorName);
         }
         DirectorName = bstrdup(optarg);
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'e':                    /* exclude list */
         if ((fd = fopen(optarg, "rb")) == NULL) {
            berrno be;
            Pmsg2(0, _("Could not open exclude file: %s, ERR=%s\n"),
               optarg, be.bstrerror());
            exit(1);
         }
         while (fgets(line, sizeof(line), fd) != NULL) {
            strip_trailing_junk(line);
            Dmsg1(100, "add_exclude %s\n", line);
            add_fname_to_exclude_list(ff, line);
         }
         fclose(fd);
         break;

      case 'i':                    /* include list */
         if ((fd = fopen(optarg, "rb")) == NULL) {
            berrno be;
            Pmsg2(0, _("Could not open include file: %s, ERR=%s\n"),
               optarg, be.bstrerror());
            exit(1);
         }
         while (fgets(line, sizeof(line), fd) != NULL) {
            strip_trailing_junk(line);
            Dmsg1(100, "add_include %s\n", line);
            add_fname_to_include_list(ff, 0, line);
         }
         fclose(fd);
         break;

      case 'j':
         list_jobs = true;
         break;

      case 'k':
         list_blocks = true;
         break;

      case 'L':
         dump_label = true;
         break;

      case 'p':
         ignore_label_errors = true;
         forge_on = true;
         break;

      case 'v':
         verbose++;
         break;

      case 'V':                    /* Volume name */
         VolumeName = optarg;
         break;

      case '?':
      default:
         usage();

      } /* end switch */
   } /* end while */
   argc -= optind;
   argv += optind;

   if (!argc) {
      Pmsg0(0, _("No archive name specified\n"));
      usage();
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   my_config = new_config_parser();
   parse_sd_config(my_config, configfile, M_ERROR_TERM);

   LockRes();
   me = (STORES *)GetNextRes(R_STORAGE, NULL);
   if (!me) {
      UnlockRes();
      Emsg1(M_ERROR_TERM, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
            configfile);
   }
   UnlockRes();

  if (DirectorName) {
      foreach_res(director, R_DIRECTOR) {
         if (bstrcmp(director->hdr.name, DirectorName)) {
            break;
         }
      }
      if (!director) {
         Emsg2(M_ERROR_TERM, 0, _("No Director resource named %s defined in %s. Cannot continue.\n"),
               DirectorName, configfile);
      }
   }

   load_sd_plugins(me->plugin_directory, me->plugin_names);

   read_crypto_cache(me->working_directory, "bareos-sd",
                     get_first_port_host_order(me->SDaddrs));

   if (ff->included_files_list == NULL) {
      add_fname_to_include_list(ff, 0, "/");
   }

   for (i=0; i < argc; i++) {
      if (bsrName) {
         bsr = parse_bsr(NULL, bsrName);
      }
      jcr = setup_jcr("bls", argv[i], bsr, director, VolumeName, 1); /* acquire for read */
      if (!jcr) {
         exit(1);
      }
      jcr->ignore_label_errors = ignore_label_errors;
      dev = jcr->dcr->dev;
      if (!dev) {
         exit(1);
      }
      dcr = jcr->dcr;
      rec = new_record();
      attr = new_attr(jcr);
      /*
       * Assume that we have already read the volume label.
       * If on second or subsequent volume, adjust buffer pointer
       */
      if (dev->VolHdr.PrevVolumeName[0] != 0) { /* second volume */
         Pmsg1(0, _("\n"
                    "Warning, this Volume is a continuation of Volume %s\n"),
                dev->VolHdr.PrevVolumeName);
      }

      if (list_blocks) {
         do_blocks(argv[i]);
      } else if (list_jobs) {
         do_jobs(argv[i]);
      } else {
         do_ls(argv[i]);
      }
      do_close(jcr);
   }
   if (bsr) {
      free_bsr(bsr);
   }
   term_include_exclude_files(ff);
   term_find_files(ff);
   return 0;
}
Exemplo n.º 15
0
/*********************************************************************
 *
 *  Program to send email
 */
int main (int argc, char *argv[])
{
   char buf[1000];
   int i, ch;
   unsigned long maxlines, lines;
#if defined(HAVE_WIN32)
   SOCKET s;
#else
   int s, r;
   struct passwd *pwd;
#endif
   char *cp, *p;
#ifdef HAVE_GETADDRINFO
   int res;
   struct addrinfo hints;
   struct addrinfo *ai, *rp;
   char mail_port[10];
#else
   struct hostent *hp;
   struct sockaddr_in sin;
#endif
#ifdef HAVE_IPV6
   const char *options = "468ac:d:f:h:r:s:l:?";
#else
   const char *options = "48ac:d:f:h:r:s:l:?";
#endif

   setlocale(LC_ALL, "en_US");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");

   my_name_is(argc, argv, "bsmtp");
   maxlines = 0;

   while ((ch = getopt(argc, argv, options)) != -1) {
      switch (ch) {
      case '4':
         default_resolv_type = RESOLV_PROTO_IPV4;
         break;

#ifdef HAVE_IPV6
      case '6':
         default_resolv_type = RESOLV_PROTO_IPV6;
         break;
#endif

      case '8':
         content_utf8 = true;
         break;

      case 'a':
         default_resolv_type = RESOLV_PROTO_ANY;
         break;

      case 'c':
         Dmsg1(20, "cc=%s\n", optarg);
         cc_addr = optarg;
         break;

      case 'd':                    /* set debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         Dmsg1(20, "Debug level = %d\n", debug_level);
         break;

      case 'f':                    /* from */
         from_addr = optarg;
         break;

      case 'h':                    /* smtp host */
         Dmsg1(20, "host=%s\n", optarg);
         p = strchr(optarg, ':');
         if (p) {
            *p++ = 0;
            mailport = atoi(p);
         }
         mailhost = optarg;
         break;

      case 's':                    /* subject */
         Dmsg1(20, "subject=%s\n", optarg);
         subject = optarg;
         break;

      case 'r':                    /* reply address */
         reply_addr = optarg;
         break;

      case 'l':
         Dmsg1(20, "maxlines=%s\n", optarg);
         maxlines = (unsigned long) atol(optarg);
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc < 1) {
      Pmsg0(0, _("Fatal error: no recipient given.\n"));
      usage();
      exit(1);
   }

   /*
    *  Determine SMTP server
    */
   if (mailhost == NULL) {
      if ((cp = getenv("SMTPSERVER")) != NULL) {
         mailhost = cp;
      } else {
         mailhost = "localhost";
      }
   }

#if defined(HAVE_WIN32)
   WSADATA  wsaData;

   _setmode(0, _O_BINARY);
   WSAStartup(MAKEWORD(2,2), &wsaData);
#endif

   /*
    *  Find out my own host name for HELO;
    *  if possible, get the fully qualified domain name
    */
   if (gethostname(my_hostname, sizeof(my_hostname) - 1) < 0) {
      Pmsg1(0, _("Fatal gethostname error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
#ifdef HAVE_GETADDRINFO
   memset(&hints, 0, sizeof(struct addrinfo));
   hints.ai_family = AF_UNSPEC;
   hints.ai_socktype = 0;
   hints.ai_protocol = 0;
   hints.ai_flags = AI_CANONNAME;

   if ((res = getaddrinfo(my_hostname, NULL, &hints, &ai)) != 0) {
      Pmsg2(0, _("Fatal getaddrinfo for myself failed \"%s\": ERR=%s\n"),
            my_hostname, gai_strerror(res));
      exit(1);
   }
   strncpy(my_hostname, ai->ai_canonname, sizeof(my_hostname) - 1);
   my_hostname[sizeof(my_hostname) - 1] = '\0';
   freeaddrinfo(ai);
#else
   if ((hp = gethostbyname(my_hostname)) == NULL) {
      Pmsg2(0, _("Fatal gethostbyname for myself failed \"%s\": ERR=%s\n"),
            my_hostname, strerror(errno));
      exit(1);
   }
   strncpy(my_hostname, hp->h_name, sizeof(my_hostname) - 1);
   my_hostname[sizeof(my_hostname) - 1] = '\0';
#endif
   Dmsg1(20, "My hostname is: %s\n", my_hostname);

   /*
    *  Determine from address.
    */
   if (from_addr == NULL) {
#if defined(HAVE_WIN32)
      DWORD dwSize = UNLEN + 1;
      LPSTR lpszBuffer = (LPSTR)alloca(dwSize);

      if (GetUserName(lpszBuffer, &dwSize)) {
         snprintf(buf, sizeof(buf), "%s@%s", lpszBuffer, my_hostname);
      } else {
         snprintf(buf, sizeof(buf), "unknown-user@%s", my_hostname);
      }
#else
      if ((pwd = getpwuid(getuid())) == 0) {
         snprintf(buf, sizeof(buf), "userid-%d@%s", (int)getuid(), my_hostname);
      } else {
         snprintf(buf, sizeof(buf), "%s@%s", pwd->pw_name, my_hostname);
      }
#endif
      from_addr = bstrdup(buf);
   }
   Dmsg1(20, "From addr=%s\n", from_addr);

   /*
    *  Connect to smtp daemon on mailhost.
    */
lookup_host:
#ifdef HAVE_GETADDRINFO
   memset(&hints, 0, sizeof(struct addrinfo));
   switch (default_resolv_type) {
   case RESOLV_PROTO_ANY:
      hints.ai_family = AF_UNSPEC;
      break;
   case RESOLV_PROTO_IPV4:
      hints.ai_family = AF_INET;
      break;
#ifdef HAVE_IPV6
   case RESOLV_PROTO_IPV6:
      hints.ai_family = AF_INET6;
      break;
#endif
   default:
      hints.ai_family = AF_UNSPEC;
      break;
   }
   hints.ai_socktype = SOCK_STREAM;
   hints.ai_protocol = 0;
   hints.ai_flags = 0;
   snprintf(mail_port, sizeof(mail_port), "%d", mailport);

   if ((res = getaddrinfo(mailhost, mail_port, &hints, &ai)) != 0) {
      Pmsg2(0, _("Error unknown mail host \"%s\": ERR=%s\n"),
            mailhost, gai_strerror(res));
      if (!bstrcasecmp(mailhost, "localhost")) {
         Pmsg0(0, _("Retrying connection using \"localhost\".\n"));
         mailhost = "localhost";
         goto lookup_host;
      }
      exit(1);
   }

   for (rp = ai; rp != NULL; rp = rp->ai_next) {
#if defined(HAVE_WIN32)
      s = WSASocket(rp->ai_family, rp->ai_socktype, rp->ai_protocol, NULL, 0, 0);
#else
      s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
#endif
      if (s < 0) {
         continue;
      }

      if (connect(s, rp->ai_addr, rp->ai_addrlen) != -1) {
         break;
      }

      close(s);
   }

   if (!rp) {
      Pmsg1(0, _("Failed to connect to mailhost %s\n"), mailhost);
      exit(1);
   }

   freeaddrinfo(ai);
#else
   if ((hp = gethostbyname(mailhost)) == NULL) {
      Pmsg2(0, _("Error unknown mail host \"%s\": ERR=%s\n"),
            mailhost, strerror(errno));
      if (!bstrcasecmp(mailhost, "localhost")) {
         Pmsg0(0, _("Retrying connection using \"localhost\".\n"));
         mailhost = "localhost";
         goto lookup_host;
      }
      exit(1);
   }

   if (hp->h_addrtype != AF_INET) {
      Pmsg1(0, _("Fatal error: Unknown address family for smtp host: %d\n"), hp->h_addrtype);
      exit(1);
   }
   memset((char *)&sin, 0, sizeof(sin));
   memcpy((char *)&sin.sin_addr, hp->h_addr, hp->h_length);
   sin.sin_family = hp->h_addrtype;
   sin.sin_port = htons(mailport);
#if defined(HAVE_WIN32)
   if ((s = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0)) < 0) {
      Pmsg1(0, _("Fatal socket error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
#else
   if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
      Pmsg1(0, _("Fatal socket error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
#endif
   if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
      Pmsg2(0, _("Fatal connect error to %s: ERR=%s\n"), mailhost, strerror(errno));
      exit(1);
   }
   Dmsg0(20, "Connected\n");
#endif

#if defined(HAVE_WIN32)
   int fdSocket = _open_osfhandle(s, _O_RDWR | _O_BINARY);
   if (fdSocket == -1) {
      Pmsg1(0, _("Fatal _open_osfhandle error: ERR=%s\n"), strerror(errno));
      exit(1);
   }

   int fdSocket2 = dup(fdSocket);

   if ((sfp = fdopen(fdSocket, "wb")) == NULL) {
      Pmsg1(0, _("Fatal fdopen error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
   if ((rfp = fdopen(fdSocket2, "rb")) == NULL) {
      Pmsg1(0, _("Fatal fdopen error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
#else
   if ((r = dup(s)) < 0) {
      Pmsg1(0, _("Fatal dup error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
   if ((sfp = fdopen(s, "w")) == 0) {
      Pmsg1(0, _("Fatal fdopen error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
   if ((rfp = fdopen(r, "r")) == 0) {
      Pmsg1(0, _("Fatal fdopen error: ERR=%s\n"), strerror(errno));
      exit(1);
   }
#endif

   /*
    *  Send SMTP headers.  Note, if any of the strings have a <
    *   in them already, we do not enclose the string in < >, otherwise
    *   we do.
    */
   get_response(); /* banner */
   chat("HELO %s\r\n", my_hostname);
   chat("MAIL FROM:%s\r\n", cleanup_addr(from_addr, buf, sizeof(buf)));

   for (i = 0; i < argc; i++) {
      Dmsg1(20, "rcpt to: %s\n", argv[i]);
      chat("RCPT TO:%s\r\n", cleanup_addr(argv[i], buf, sizeof(buf)));
   }

   if (cc_addr) {
      chat("RCPT TO:%s\r\n", cleanup_addr(cc_addr, buf, sizeof(buf)));
   }
   Dmsg0(20, "Data\n");
   chat("DATA\r\n");

   /*
    *  Send message header
    */
   fprintf(sfp, "From: %s\r\n", from_addr);
   Dmsg1(10, "From: %s\r\n", from_addr);
   if (subject) {
      fprintf(sfp, "Subject: %s\r\n", subject);
      Dmsg1(10, "Subject: %s\r\n", subject);
   }
   if (reply_addr) {
      fprintf(sfp, "Reply-To: %s\r\n", reply_addr);
      Dmsg1(10, "Reply-To: %s\r\n", reply_addr);
   }
   if (err_addr) {
      fprintf(sfp, "Errors-To: %s\r\n", err_addr);
      Dmsg1(10, "Errors-To: %s\r\n", err_addr);
   }

#if defined(HAVE_WIN32)
   DWORD dwSize = UNLEN + 1;
   LPSTR lpszBuffer = (LPSTR)alloca(dwSize);

   if (GetUserName(lpszBuffer, &dwSize)) {
      fprintf(sfp, "Sender: %s@%s\r\n", lpszBuffer, my_hostname);
      Dmsg2(10, "Sender: %s@%s\r\n", lpszBuffer, my_hostname);
   } else {
      fprintf(sfp, "Sender: unknown-user@%s\r\n", my_hostname);
      Dmsg1(10, "Sender: unknown-user@%s\r\n", my_hostname);
   }
#else
   if ((pwd = getpwuid(getuid())) == 0) {
      fprintf(sfp, "Sender: userid-%d@%s\r\n", (int)getuid(), my_hostname);
      Dmsg2(10, "Sender: userid-%d@%s\r\n", (int)getuid(), my_hostname);
   } else {
      fprintf(sfp, "Sender: %s@%s\r\n", pwd->pw_name, my_hostname);
      Dmsg2(10, "Sender: %s@%s\r\n", pwd->pw_name, my_hostname);
   }
#endif

   fprintf(sfp, "To: %s", argv[0]);
   Dmsg1(10, "To: %s", argv[0]);
   for (i = 1; i < argc; i++) {
      fprintf(sfp, ",%s", argv[i]);
      Dmsg1(10, ",%s", argv[i]);
   }

   fprintf(sfp, "\r\n");
   Dmsg0(10, "\r\n");
   if (cc_addr) {
      fprintf(sfp, "Cc: %s\r\n", cc_addr);
      Dmsg1(10, "Cc: %s\r\n", cc_addr);
   }

   if (content_utf8) {
      fprintf(sfp, "Content-Type: text/plain; charset=UTF-8\r\n");
      Dmsg0(10, "Content-Type: text/plain; charset=UTF-8\r\n");
   }

   get_date_string(buf, sizeof(buf));
   fprintf(sfp, "Date: %s\r\n", buf);
   Dmsg1(10, "Date: %s\r\n", buf);

   fprintf(sfp, "\r\n");

   /*
    *  Send message body
    */
   lines = 0;
   while (fgets(buf, sizeof(buf), stdin)) {
      if (maxlines > 0 && ++lines > maxlines) {
         Dmsg1(20, "skip line because of maxlines limit: %lu\n", maxlines);
         while (fgets(buf, sizeof(buf), stdin)) {
            ++lines;
         }
         break;
      }
      buf[sizeof(buf)-1] = '\0';
      buf[strlen(buf)-1] = '\0';
      if (buf[0] == '.') {         /* add extra . see RFC 2821 4.5.2 */
         fputs(".", sfp);
      }
      fputs(buf, sfp);
      fputs("\r\n", sfp);
   }

   if (lines > maxlines) {
      Dmsg1(10, "hit maxlines limit: %lu\n", maxlines);
      fprintf(sfp, "\r\n\r\n[maximum of %lu lines exceeded, skipped %lu lines of output]\r\n", maxlines, lines-maxlines);
   }

   /*
    *  Send SMTP quit command
    */
   chat(".\r\n");
   chat("QUIT\r\n");

   /*
    *  Go away gracefully ...
    */
   exit(0);
}
Exemplo n.º 16
0
Arquivo: stored.c Projeto: AlD/bareos
int main (int argc, char *argv[])
{
   int ch;
   bool no_signals = false;
   bool test_config = false;
   pthread_t thid;
   char *uid = NULL;
   char *gid = NULL;

   start_heap = sbrk(0);
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");

   init_stack_dump();
   my_name_is(argc, argv, "bareos-sd");
   init_msg(NULL, NULL);
   daemon_start_time = time(NULL);

   /* Sanity checks */
   if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
      Emsg2(M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
         TAPE_BSIZE, B_DEV_BSIZE);
   }
   if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
      Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
   }

   while ((ch = getopt(argc, argv, "c:d:fg:mpstu:v?")) != -1) {
      switch (ch) {
      case 'c':                    /* configuration file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'f':                    /* run in foreground */
         foreground = true;
         break;

      case 'g':                    /* set group id */
         gid = optarg;
         break;

      case 'm':                    /* print kaboom output */
         prt_kaboom = true;
         break;

      case 'p':                    /* proceed in spite of I/O errors */
         forge_on = true;
         break;

      case 's':                    /* no signals */
         no_signals = true;
         break;

      case 't':
         test_config = true;
         break;

      case 'u':                    /* set uid */
         uid = optarg;
         break;

      case 'v':                    /* verbose */
         verbose++;
         break;

      case '?':
      default:
         usage();
         break;
      }
   }
   argc -= optind;
   argv += optind;

   if (argc) {
      if (configfile != NULL) {
         free(configfile);
      }
      configfile = bstrdup(*argv);
      argc--;
      argv++;
   }
   if (argc)
      usage();

   /*
    * See if we want to drop privs.
    */
   if (geteuid() == 0) {
      drop(uid, gid, false);
   }

   if (!no_signals) {
      init_signals(terminate_stored);
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   my_config = new_config_parser();
   parse_sd_config(my_config, configfile, M_ERROR_TERM);

   if (init_crypto() != 0) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
   }

   if (!check_resources()) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
   }

   init_reservations_lock();

   if (test_config) {
      terminate_stored(0);
   }

   my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */

   if (!foreground) {
      daemon_start();                 /* become daemon */
      init_stack_dump();              /* pick up new pid */
   }

   create_pid_file(me->pid_directory, "bareos-sd",
                   get_first_port_host_order(me->SDaddrs));
   read_state_file(me->working_directory, "bareos-sd",
                   get_first_port_host_order(me->SDaddrs));
   read_crypto_cache(me->working_directory, "bareos-sd",
                     get_first_port_host_order(me->SDaddrs));

   set_jcr_in_tsd(INVALID_JCR);

   /*
    * Make sure on Solaris we can run concurrent, watch dog + servers + misc
    */
   set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
   lmgr_init_thread(); /* initialize the lockmanager stack */

   load_sd_plugins(me->plugin_directory, me->plugin_names);

   cleanup_old_files();

   /* Ensure that Volume Session Time and Id are both
    * set and are both non-zero.
    */
   VolSessionTime = (uint32_t)daemon_start_time;
   if (VolSessionTime == 0) { /* paranoid */
      Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
   }

   /*
    * Start the device allocation thread
    */
   create_volume_lists();             /* do before device_init */
   if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
      berrno be;
      Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
   }

   start_watchdog();                  /* start watchdog thread */
   if (me->jcr_watchdog_time) {
      init_jcr_subsystem(me->jcr_watchdog_time); /* start JCR watchdogs etc. */
   }

#if HAVE_NDMP
   /* Seperate thread that handles NDMP connections */
   if (me->ndmp_enable) {
      start_ndmp_thread_server(me->NDMPaddrs,
                               me->max_concurrent_jobs * 2 + 1,
                               &ndmp_workq);
   }
#endif

   /* Single server used for Director/Storage and File daemon */
   sock_fds = New(alist(10, not_owned_by_alist));
   bnet_thread_server_tcp(me->SDaddrs,
                      me->max_concurrent_jobs * 2 + 1,
                      sock_fds,
                      &dird_workq,
                      me->nokeepalive,
                      handle_connection_request);
   exit(1);                           /* to keep compiler quiet */
}
Exemplo n.º 17
0
con_vec Djoefe (situation & s) 
{
  
  const char name[] = "Djoefe";	// This is the robot driver's name!
  static int init_flag = 1;	// cleared by first call
  con_vec result;		// This is what is returned.
  double alpha, vc;		// components of result
  static double lane = -10000;	// an absurd value to show not initialized
  double bias, speed, width, to_end;
  double speed_next= 0.0;
  
  static double fuel_total = 0;
  static double fuel_last;

  double aftaft_bd, after_bd, bd_now;
    
  // Load the optimization stuff for this track
#ifdef OPTIMIZE
  static int optinit = 0;
  if(optinit==0)
  {
    // Reload the population from the data file
    const char* optfile = "djoefe.opt";
    data.load(optfile,Population,GeneticLength,SetTrackData);
    cout << "\nOptimizing for track in " << optfile << endl;

    optinit = 1;
  }
#endif //OPTIMIZE

  if (init_flag == 1)
  {				// first time only, copy name:
    my_name_is (name);	// copy the name string into the host program
    init_flag = 0;
    result.alpha = result.vc = 0;
    
    return result;  
  }

  // set fuel for qualifications  
  if (s.starting && s.stage == QUALIFYING)
    result.fuel_amount = 20;
    
  // estimate available friction:
  useful_friction = 0.975 * my_friction - 0.2 * s.damage * s.damage / 9e8;
  
  // drive carefully on first laps:
  //    if(lap_count - s.laps_to_go < 2 && s.position >= 4)
  //        useful_friction *= .9*my_friction;
    
  // service routine in the host software to handle getting unstuck from
  // from crashes and pileups:
#ifndef OPTIMIZE
  if (stuck (s.backward, s.v, s.vn, s.to_lft, s.to_rgt, &result.alpha, &result.vc))
    return result;
#endif //OPTIMIZE

  width = s.to_lft + s.to_rgt;	// compute width of track

  
  // This is a little trick so that the car will not try to change lanes
  // during the "dragout" at the start of the race.  We set "lane" to
  // whatever position we have been placed by the host.
    if (lane < -9000)		// will be true only once
    {
      fuel_last = s.fuel;	// setup fuel counter

#ifndef OPTIMIZE
      set_track_data ();
#endif

      lane = s.to_lft;	// better not to change lanes at the start
      slip = BIG_SLIP;
      t = get_track_description ();
      
      if( !args.m_iSurface )		// friction model 0:
	my_friction = slip / (slip + 2.5);
      else			// friction model 1:
	my_friction = 1.05 * (1.0 - exp (-slip / 2.5));      
    }
  
#ifdef OPTIMIZE
  if(s.starting)
  {
    // Figure out a nice estimate of the MPH, or how far we
    // got around the track
    double mph = optimizedata::mph(lastlaptime,t.length,lastdamage,lastdistance);

    if(no_display)
    {
      cout << " Mph: " << mph
           << endl;
    }

    // Tell the optimizer what the last MPH was
    data.step(mph);
    AbortRace = 0;
  }
#endif //OPTIMIZE
    
    // Curve control 1
    // a) If we are in a curve, go to the inside
    // b) If we are exiting the curve into a straight then "slide" out of the curve

    // Sharp left
    if (s.cur_rad > 0.0 && s.cur_rad < straight_radius)	
    {
      if (is_nex_straight (s) && s.to_end <= s.cur_len * (1 - out_of_curve))
      {
        lane = width - dist_from_outside;
      }
      else
      {
	lane = dist_from_inside;
      }
      
    }
    // Sharp right
    else if (s.cur_rad < 0.0 && s.cur_rad > -straight_radius)
    {
      if (is_nex_straight (s) && s.to_end <= s.cur_len * (1 - out_of_curve))
      {
          lane = dist_from_outside;
      }
      else
      {
	  lane = width - dist_from_inside;
      }
    }
    
  // set the bias:
  // Bias is an additive term in the steering servo, so that the servo
  // doesn't have to "hunt" much for the correct alpha value.  It is an
  // estimate of the alpha value that would be found by the servo if there
  // was plenty of settling time.  It is zero for straightaways.
  // Also, for convenience, we call the corn_spd() function here.  On
  // the straightaway, we call it to find out the correct speed for the
  // corner ahead, using s.nex_rad for the radius.  In the curve we of
  // course use the radius of the curve we are in.  But also, we call it
  // for the next segment, to find out our target speed for the end of
  // the current segment, which we call speed_next.
    if (s.cur_rad == 0.0)
    {
	bias = 0.0;
     
	if (!is_nex_straight (s))
	  speed = curvespeed (s, fabs(s.nex_rad) + width * predict_width);	
        else
	  speed = 250.0;
    }
    else
    {
	if (is_nex_straight(s))
	  speed_next = 250.0;
	else
	  speed_next = curvespeed (s, fabs (s.nex_rad) + width * predict_width);
      	
	if(!is_curr_straight(s))
	  speed = curvespeed (s, fabs (s.cur_rad) + width * predict_width);
	else
	  speed = 250;
	
	bias = (s.v * s.v / (speed * speed)) * atan (BIG_SLIP / speed);	
      
	if (s.cur_rad < 0.0)	// bias must be negative for right turn
	  bias = -bias;
    }
    
  // set alpha:  (This line is the complete steering servo.)
    alpha = steer_gain * (s.to_lft - lane) / width - damp_gain * s.vn / s.v + bias;
  
  
  // set vc:  When nearing end of straight, change "lane" for the turn, also.
    if (s.cur_rad == 0.0)
    {				// If we are on a straightaway,
      
      // if we are far from the end,
      if (s.to_end * ignore_slowdown > find_bd (s, speed))
      {
	vc = s.v + 50.0;	// pedal to the metal!
      }
      else
      {			// otherwise, adjust speed for the coming turn:
	  if (s.v > 1.02 * speed)	// if we're 2% too fast,
	    vc = brake_ratio * s.v;	// brake hard.
	  else if (s.v < .98 * speed)	// if we're 2% too slow,
	    vc = 1.1 * speed;	// accelerate hard. 1.1
	  else			// if we are very close to speed,
	    vc = .5 * (s.v + speed);	// approach the speed gently.
       }
      
      // Start diving into the corner

      if(s.to_end < (start_dive * s.v * width))
	{
	  if (s.nex_rad > 0.0)	// left
	    lane = dist_from_inside;
	  else
	    lane = width - dist_from_inside;  
	}
      else
	{
	  if (!is_nex_straight(s) && ((s.cur_len * dive_setup_dist) >= s.to_end))
	    {
	      if (s.nex_rad > 0.0)
		lane = width - dist_for_dive;
	      else if (s.nex_rad < 0.0)
		lane = dist_for_dive;
	    }
	}
      
    }
    else
    {				
      // This is when we are in a curve:  (seek correct speed)
      // calculate vc to maintain speed in corner
      speed = curvespeed (s, fabs (s.cur_rad) + width * predict_width);
      
      vc = .5 * (s.v + speed);	

      // calculate distance to end of curve
      if (s.cur_rad > 0.0)
	  to_end = s.to_end * (s.cur_rad + width * predict_width);
      else	
	  to_end = -s.to_end * (s.cur_rad - width * predict_width);
      
      // compute required braking distance and compare:
      if (to_end <= find_bd (s, speed_next))
      {
	vc = s.v - brake_curve_slip;
      }

      if (is_nex_straight (s) && s.to_end <= s.cur_len * (1 - out_of_curve))
      {  
	vc = s.v * 1.1;  
      }
    }

    // New speed limiter if curve after next is tricky

    // calculate the braking distance we will need to slow down from the
    // speed we now have to the speed in the segment after the next

    aftaft_bd = find_bd(s, crvspeed(s.aftaft_rad));

    after_bd = find_bd(s, crvspeed(s.after_rad));

    if (aftaft_bd > (curve_length(s.nex_len, s.nex_rad) 
		    + curve_length(s.after_len, s.after_rad)))
      {
	bd_now = aftaft_bd - (curve_length(s.nex_len, s.nex_rad) +
			      curve_length(s.after_len, s.after_rad));

	if (bd_now > curve_length(s.to_end, s.cur_rad))
	  {
	    vc = s.v * brake_ratio;
	  }
      }
    // else here ? not sure...
    if (after_bd > (curve_length(s.nex_len, s.nex_rad)))  
      {
	// We will have to start braking in this segment.

	// When = Total - lenght of next curve
	bd_now = after_bd - curve_length(s.nex_len, s.nex_rad);

	if (bd_now > curve_length(s.to_end, s.cur_rad))
	  {   
	    vc = s.v * brake_ratio; 
	  }
      }

#ifndef BFOPT
    // Gotta love this passing code... ;-)
    if (s.dead_ahead)		// Change the lane a little if someone's
      if (s.to_lft > s.to_rgt)	// in your way.
	lane -= DELTA_LANE;	// lane must be a static variable
      else
	lane += DELTA_LANE;
  
    
    if (s.lap_flag)
    {    
	if (s.fuel > fuel_last)
	{			
	  // we refueled...use previous as estimate
	  fuel_total += fuel_total / (s.laps_done - 1); 
	}
	else
	{
	  fuel_total += fuel_last - s.fuel;
	}
	fuel_last = s.fuel;
    }
  
    result.request_pit = 0;

    
    if (s.stage != QUALIFYING && (s.damage > 20000) && (s.laps_to_go > 5))  
    {
      result.request_pit = 1;
      result.repair_amount = max(s.damage, (unsigned)s.laps_to_go * 1000);
      result.fuel_amount = max(0,((fuel_total / s.laps_done) * (s.laps_to_go + 1)) - s.fuel);
    }
  
    if (s.stage != QUALIFYING && s.fuel < (fuel_total / (s.laps_done - 1)) && s.laps_done > 1)
    {
      result.request_pit = 1;
      result.fuel_amount = (fuel_total / s.laps_done) * (s.laps_to_go + 1);
      result.repair_amount = (int)result.fuel_amount * 10;
    }  

#endif
    result.alpha = alpha;
  
    result.vc = vc;
    
    traction_control(s, result);
    
#ifdef OPTIMIZE  // Pitting during optimizing is done differently

  // Keep track of the data from the last lap
  lastlaptime = s.lap_time;
  lastdamage = s.damage;
  lastdistance = s.distance;
  
//   result.fuel_amount = 150;
   result.request_pit = 0;

   // If we are damaged or are too close to the edge, abort the
   // race by deliberate crashing
   /*   if((s.damage)||
      (s.to_lft<EdgeLimit)||
      (s.to_rgt<EdgeLimit))
      AbortRace = 1;*/

   if(AbortRace)
   {
     result.vc = 250.;
     result.alpha = 0.;
   }
#endif //OPTIMIZE

#ifdef SKIDMARKS
    extern int skidmarks;
    skidmarks = 1;

    extern int designated;
    designated = 0;
#endif

    return result;
}