示例#1
0
void multicast_discover_cb(evutil_socket_t sock, short ev, void *arg) {
  static char q_buff[MDNS_MAX_LEN];
  static int snd_len;
  static dns_msg_t msgq;
  static dns_question_t q;

  ask_PTR(UDP_SERV, &q);
  init_msg(&msgq);
  set_QR(&(msgq.header), QR_QUERY);
  set_QDCOUNT(&(msgq.header), 1);

  msgq.questions = &q;
  snd_len = send_format_msg(&msgq, q_buff);

  if(sendto(sock, q_buff, snd_len, 0, (struct sockaddr *) &multicast_addr,
            sizeof(multicast_addr)) != snd_len) {
    fprintf(stderr, "nie udalo sie zapytc o PTR :c\n");
  }

  ask_PTR(TCP_SERV, &q);
  init_msg(&msgq);
  set_QR(&(msgq.header), QR_QUERY);
  set_QDCOUNT(&(msgq.header), 1);

  msgq.questions = &q;
  snd_len = send_format_msg(&msgq, q_buff);

  if(sendto(sock, q_buff, snd_len, 0, (struct sockaddr *) &multicast_addr,
            sizeof(multicast_addr)) != snd_len) {
    fprintf(stderr, "nie udalo sie zapytc o PTR :c\n");
  }
}
示例#2
0
int main(int argc,const char* argv[])
{
    clientSetup = new ClientSetup();
    //If the returned value is not 0, there are problems with WSAStartup and Socket Opening/Binding 
    if(clientSetup->initializeServer() != 0) {
        printf("Could not start the server. We're really sorry.\n");
        return 0;
    }
    else {
        ////Part 1. Receive the JAUS message from Subsytem 1
        ////Receiving the message
        //char* msg = clientSetup->receiveMessage(JAUS_MESSAGE_HEADER_LENGTH 
        //    + SET_WRENCH_EFFORT_LENGTH);
        //UINT16 command_code = endian_change_u16((msg[2] << 8) | msg[3]);
        //SetWrenchEffortMessage * swe;
        ////SetWrenchEffort
        //if(command_code == 1029) {
        //
        //    printf("\nSet Wrench Effort");
        //    printf("\n----------------------------------------");
        //    swe = (SetWrenchEffortMessage *) msg;
        //    printSetWrenchEffort(*swe);
        //}
        //
        ////Part 2. Transfer the JAUS packet to functions.cpp and concatenate the packet into ethercat datagram data     
        //jaus_packet = msg;
        //jaus_packet_length = JAUS_MESSAGE_HEADER_LENGTH + (int)swe->jausMsgHdr.DataControl;
    }

    int c;
    raw_soc = new RawSoc(interf);
    // Print opening line, greeting, instructions, copyright notice etc.
    init_msg();

    do // Main loop.
    {
        printf("\nEcat test:"); // Prompt user for input

        c = _getche(); //Get user response.
        putchar('\n');

        // Take various actions based on user's response.
        int i;
        // Start scanning the array, looking for a match with input and ".key" member Only 'q' will have a zero for f
        for (i = 0; kcd[i].key != 0; i++)
        {
            if (c == kcd[i].key)
            {
                if (kcd[i].f != 0) kcd[i].f();
                    break;
            }
        }
        if (kcd[i].key == 0) top_menu(); //No match, print menu

    } while (c != 'q'); // End of main loop.

    delete raw_soc;

//    return 0;
}
示例#3
0
/*cook pthread*/
void *cook_fun(void *arg)
{
	struct message msg;
	int pid;
	int rvmsg;
	pid = init_msg(&msg);
	while(1){
		/*waiting to cook*/
		if((rvmsg = msgrcv(pid, (void*)&msg, BUFSIZ, 1, IPC_NOWAIT)) == -1)
			continue;
		else
		{
#if DEBUG
			printf("get msg.text.----------------------\n%s\n",msg.msg_text);
#endif
			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			update_cust(msg.msg_text);
			pthread_mutex_unlock(&mutex);
			sleep(10);
			printf("cook done %s\n",msg.msg_text);
		}
		/*check if there has client urging*/
		if((rvmsg = msgrcv(pid, (void*)&msg, BUFSIZ, 2, IPC_NOWAIT)) == -1);
		/*has client urging*/
		else
			printf("---there is/are %d people is waiting!! come on, good cooker...",atoi(msg.msg_text));
	}
	pthread_exit(0);
}
示例#4
0
int CZmqThread::init_socket(){

    int rc;
    void *ctx=zmq_gcontext_get();

    m_socket = zmq_socket (ctx, ZMQ_SUB);
    if (!m_socket) {
        printf ("error in zmq_socket: %s\n", zmq_strerror (errno));
        return -1;
    }

    rc = zmq_connect (m_socket, ( char *)m_host.toUtf8().data());
    if (rc != 0) {
        printf ("error in zmq_connect: %s\n", zmq_strerror (errno));
        return -1;
    }

    rc=zmq_setsockopt (m_socket, ZMQ_SUBSCRIBE, 0,0);
    if (rc != 0) {
        printf ("error in zmq_setoption : %s\n", zmq_strerror (errno));
        return -1;
    }

    init_msg();
    return (0);
}
示例#5
0
 /**
  * Initialize zmq message with zero-terminated string
  */
 ZMQMESSAGE_DLL_PUBLIC
 inline
 void
 init_msg(const char* t, zmq::message_t& msg)
 {
   init_msg(t, strlen(t), msg);
 }
示例#6
0
static int receive_dispatch(global_conf_st *g_conf)
{
    char *msg_str = NULL;
    size_t rtv;
    uint32_t rtf;
    memcached_return rc;
    memcached_st *memc = g_conf->receive_mq->mq_server;
    char *task_name = g_conf->receive_mq->task_name;
    msg_str = memcached_get(memc,task_name,strlen(task_name),&rtv,&rtf,&rc);
    if(rc != MEMCACHED_SUCCESS){
	return -1;
    }
    jlog(L_INFO,"receive fromtask %s --",task_name);
    jlog(L_INFO,"receive msg %s",msg_str);
    msg_st *msg = (msg_st *)calloc(sizeof(msg_st),1);
    
    if(NULL == msg){
	jlog(L_ERR,"out of memory");
	exit(-1);
    }
    if(-1 == init_msg(msg,msg_str)){
	if(msg)
	    free(msg);
	if(msg_str)
	    free(msg_str);
	return 0;
    }
    int thread_index = g_str_hash(msg->src_pnum) % g_conf->max_thread;
    g_async_queue_push(threads[thread_index].msg_queue,msg);
    incrMsgProcNum();
    free(msg_str);
    return 1;
}
示例#7
0
文件: msgbld.c 项目: E-LLP/VICAR
    FUNCTION  int main(void)		

    {
    struct  PARBLK	parblk;		/* block to receive parameters form tm */
    struct  FSBLOCK	txt_fsblk;	/* fsblock for message text file  */
    struct  SFILE	txt_sfile;	/* sfile for message text file	  */
    struct  SFILE	inx_sfile;
    COUNT	txt_lun, inx_lun;	/* lun's to use		  	  */
    CODE		code;
 

    init_msg();				/* send initiation message	*/

    txt_lun = 1;
    inx_lun = 2;
    p_inim(&parblk, sizeof(struct PARBLK), P_ABORT);	/* initialise in abort mode 	*/
    						/* open the message file  */
    code = open_msg(&parblk, &txt_sfile, &txt_fsblk, txt_lun);
    if (code == SUCCESS)			
	code = index_bld(&txt_sfile, &txt_fsblk, &inx_sfile, 
		inx_lun);			/* build the index file   */

    if (code == SUCCESS)
	{
	parm_err("Index file '%s.%s' created successfully .", "TAE-MSGBSUCC", 
		(uintptr_t)txt_fsblk.name, (uintptr_t)INX_TYPE, 0);
	z_exit(1, "TAE-MSGBSUCC");		/* $sfi, $skey indicate success */
	}
    else
	z_exit(-1, "TAE-MSGBFAIL");		/* $sfi, $skey indicate fail */
    return(0);
    }
示例#8
0
 ZMQMESSAGE_DLL_PUBLIC
 inline
 void
 init_msg(const T& t, zmq::message_t& msg, bool binary_mode)
 {
   binary_mode ? init_msg_bin(t, msg) : init_msg(t, msg);
 }
示例#9
0
 ZMQMESSAGE_DLL_PUBLIC
 inline
 void
 init_msg_bin(const T& t, zmq::message_t& msg)
 {
   init_msg(&t, sizeof(T), msg);
 }
示例#10
0
 inline void
 init_msg(const T& t, zmq::message_t& msg,
          typename Private::DisableIf<Private::IsStr<T>::value>::type* = 0,
          typename Private::EnableIf<Private::IsRaw<T>::value>::type* = 0)
 {
   init_msg(&t, sizeof(T), msg);
 }
示例#11
0
文件: testfind.c 项目: AlD/bareos
int
main (int argc, char *const *argv)
{
   FF_PKT *ff;
   const char *configfile = "bareos-dir.conf";
   const char *fileset_name = "Windows-Full-Set";
   int ch, hard_links;

   OSDependentInit();

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

   while ((ch = getopt(argc, argv, "ac:d:f:?")) != -1) {
      switch (ch) {
         case 'a':                    /* print extended attributes *debug* */
            attrs = 1;
            break;

         case 'c':                    /* set debug level */
            configfile = 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;
            }
         }
            break;

         case 'f':                    /* exclude patterns */
            fileset_name = optarg;
            break;

         case '?':
         default:
            usage();

      }
   }

   argc -= optind;
   argv += optind;

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

   MSGSRES *msg;

   foreach_res(msg, R_MSGS)
   {
      init_msg(NULL, msg);
   }
示例#12
0
 ZMQMESSAGE_DLL_PUBLIC
 inline
 void
 init_msg(const T& t, zmq::message_t& msg,
   typename Private::EnableIf<Private::IsStr<T>::value>::type* = 0)
 {
   init_msg(t.data(), t.length(), msg);
 }
示例#13
0
int		update_sent_msg(t_client *client, int len,
				int result, int first)
{
  int		start;
  int		save;
  int		tmp;

  save = client->pos_send;
  client->pos_send = first;
  start = 0;
  while (result > 0)
    {
      tmp = sizeof(TAG_SEND(client)) + sizeof(LEN_SEND(client)) -
	POS_SEND(client);
      if (tmp > 0)
	{
	  if (result >= tmp)
	    {
	      result -= tmp;
	      start += tmp;
	      POS_SEND(client) += tmp;
	    }
	  else
	    {
	      POS_SEND(client) += result;
	      break;
	    }
	}
      if (LEN_SEND(client) > 0)
	{
	  tmp = LEN_SEND(client) - ((tmp < 0) ? (tmp) : (0));
	  if (tmp > 0)
	    {
	      if (result >= tmp)
		{
		  result -= tmp;
		  start += tmp;
		  POS_SEND(client) += tmp;
		}
	      else
		{
		  POS_SEND(client) += result;
		  break;
		}
	    }
	}
      if (MSG_SEND(client))
	free(MSG_SEND(client));
      init_msg(&client->send[client->pos_send]);
      if (++client->pos_send >= NET_MAX_MSG)
	client->pos_send = 0;
    }
  if (client->pos_send != save)
    {
      fprintf(fd_log, "bug...%d, %d\n", client->pos_send, save);
    }
  return (0);
}
 Sink&
 Sink::operator<< (const T& t) throw (ZmqErrorType)
 {
   MsgPtr msg(new zmq::message_t);
   bool binary_mode = options_ & OutOptions::BINARY_MODE;
   init_msg(t, *msg, binary_mode);
   send_owned(msg.release());
   return *this;
 }
示例#15
0
 inline void
 init_msg(const T& t, zmq::message_t& msg,
          typename Private::DisableIf<Private::IsStr<T>::value>::type* = 0,
          typename Private::DisableIf<Private::IsRaw<T>::value>::type* = 0)
 {
   std::ostringstream os;
   os << t;
   const std::string& s = os.str();
   init_msg(s, msg);
 }
示例#16
0
int main(void) {
 s_window = window_create();
  window_set_fullscreen(s_window, true);
    app_comm_set_sniff_interval(SNIFF_INTERVAL_REDUCED);
       app_message_open(256, 256);
  init_msg();
  
  
  window_set_window_handlers(s_window, (WindowHandlers) {
     .load = window_load,
    .unload = handle_window_unload,
  });
示例#17
0
文件: util.c 项目: njutony1991/Nanos
PCB*
create_kthread(void *fun,int ch,PCB **next) {
    if(list_empty(&free)){
        panic("no room for more threads\n");
    }

	PCB *funpcb = list_entry(free.next, PCB, list);
    list_del(&funpcb->list);
    list_init(&funpcb->list);
    num++;
    
	TrapFrame *tf = (TrapFrame *)(funpcb->kstack + KSTACK_SIZE-12)-1;
	tf->eflags = 0x202;
	tf->cs = SELECTOR_KERNEL(SEG_KERNEL_CODE);
	tf->ds = SELECTOR_KERNEL(SEG_KERNEL_DATA);
	tf->es = SELECTOR_KERNEL(SEG_KERNEL_DATA);
	tf->fs = SELECTOR_KERNEL(SEG_KERNEL_DATA);
	tf->gs = SELECTOR_KERNEL(SEG_KERNEL_DATA);
    //tf->ss = SELECTOR_KERNEL(SEG_KERNEL_DATA);
	tf->error_code = 0;
	tf->eip = (uint32_t)fun;
	//tf->esp = (uint32_t)tf;   the esp is not needed in kernal thread
    //tf->ebp = (uint32_t)(tf+1)+4;
    if(ch != 0){   
        int *para1 = (int *)((uint32_t)(tf+1)-4);   //overwrite the esp and ss
        *para1 = ch;
    }
    if(next != NULL){
        PCB ***para2 = (PCB ***)((uint32_t)(tf+1));
        *para2 = next;
    }

	funpcb->tf = tf;
	funpcb->pid = id++;
    funpcb->in_ready = 0;
    funpcb->lock_depth = 0;
    funpcb->IF_bit = 0;

    init_msg(funpcb);

    int i;
    for(i=0;i<=PCB_NUM;i++){
        create_sem(&funpcb->message_guard[i],0);
        list_del(&funpcb->messages[i]);
        list_init(&funpcb->messages[i]);
    }
    create_sem(&funpcb->any_guard,0);

    list_del(&funpcb->hard_messages);
    list_init(&funpcb->hard_messages);

	return funpcb;
}
示例#18
0
文件: init.c 项目: herumi/kernel
void init_base (struct hal_mmmap *mmmap){

  INFO("Resea " VERSION_STR);

  init_memory(mmmap);
  hal_init();
  init_res();
  add_memory_res();
  init_thread();
  init_msg();

  // start_builtin_servers()
}
示例#19
0
/*cook pthread*/
void *cook_fun(void *arg)
{
	struct message msg;
	int pid;
	int rvmsg;
	int rvm;
	int i;
	pid = init_msg(&msg);
	bzero(buf_cook,BUFSIZ);
	sprintf(buf_cook,"*******************************************************\n**********************cooker state*********************\n*********************waiting for cooking***************\n*******************************************************\n");
	while(1){
		/*waiting to cook*/
		if((rvmsg = msgrcv(pid, (void*)&msg, BUFSIZ, 1, IPC_NOWAIT)) <= 0){
			//continue;
		}
		else if(rvmsg > 0)
		{
			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			update_cust(msg.msg_text);
			pthread_mutex_unlock(&mutex);
			bzero(buf_cook,BUFSIZ);
			sprintf(buf_cook,"*******************************************************\n**********************cooker state*********************\n*********************begin to cooking******************\n*******************************************************\n");
			for(i = 0; i< 10; i++){
				sleep(1);
				/*check if there has client urging*/
				if((rvm = msgrcv(pid, (void*)&msg, BUFSIZ, 2, IPC_NOWAIT)) <= 0){
					//continue;
				}
				/*has client urging*/
				else if(rvm > 0)
				{
					char buf_ala[BUFSIZ];
					bzero(buf_ala,BUFSIZ);
					sprintf(buf_ala,"\ncome on, good cooker...\n");
					strncpy(buf_cook+strlen(buf_cook),buf_ala,strlen(buf_ala));
				}

			}
			bzero(buf_cook,BUFSIZ);
			sprintf(buf_cook,"*******************************************************\n***************client %3s's food is done**********\n*********************And waiting for cooking***********\n*******************************************************\n",msg.msg_text);
			sleep(2);
			bzero(msg.msg_text,BUFSIZ);
		}

	}
	pthread_exit(0);
}
 Sink&
 Sink::operator<< (const RawMessage& m)
   throw (ZmqErrorType)
 {
   if (m.deleter)
   {
     Part part(m.data.ptr, m.sz, m.deleter, m.hint);
     send_owned(part);
   }
   else
   {
     Part part;
     init_msg(m.data.cptr, m.sz, part.msg());
     send_owned(part);
   }
   return *this;
 }
示例#21
0
static void reload_dump(global_conf_st *g_conf)
{
    FILE *fp = NULL;
    char line[2048];
    if (g_conf->reload_file)
    {
	if ((fp = fopen(g_conf->reload_file, "r")) == NULL)
	{
	    jlog(L_ERR, "reload file is not exist ");
	    return;
	}
	while (!feof(fp))
	{
	    memset(line, 0, sizeof(line));
	    fgets(line, sizeof(line), fp);
	    jlog(L_DEBUG, "reload %s\n", line);
	    if (is_blank_line(line))
		break;
	    jlog(L_DEBUG, "reload %s\n", line);
	    msg_st *msg = (msg_st *) calloc(sizeof(msg_st), 1);
	    if (msg == NULL)
	    {
		jlog(L_ERR, "out of memory");
		exit(1);
	    }
	    if (-1 == init_msg(msg, line))
	    {
		if (msg)
		    free(msg);
		return ;
	    }

	    int thread_index = g_str_hash(msg->src_pnum) % g_conf->max_thread;
	    g_async_queue_push(threads[thread_index].msg_queue, msg);
	    incrMsgProcNum();
	}
	fclose(fp);
	fp = fopen(g_conf->reload_file, "w");
	fclose(fp);
    }
}
示例#22
0
/*------------------------------------------------------------------------------------------------------------------ 
-- FUNCTION:	connect
-- 
-- DATE:		January 21, 2015
-- 
-- REVISIONS:	
-- 
-- DESIGNER:	Ruoqi Jia
-- 
-- PROGRAMMER:	Ruoqi Jia
-- 
-- INTERFACE:	void connect(int c_pid, struct msg * snd_msg, struct msg * rcv_msg, int * s_pid)
-- 						int c_pid : client's process ID
--						struct msg * snd_msg : pointer to the msg structure for sending 
--						struct msg * rcv_msg : pointer to the msg structure for reading
--						int * s_pid : server's process ID
--
-- RETURNS: void
-- 
-- NOTES: For mainly establishing connection with the server. The client will query a message to the queue and waits 
-- for an aknowledgement from the server with its process ID attached. The server process ID will be stored for future 
-- communications.
--------------------------------------------------------------------------------------------------------------------*/
void connect(int c_pid, struct msg * snd_msg, struct msg * rcv_msg, int * s_pid)
{
	char * c_pids;
	/* convert PID into a string */
	rev_atoi(c_pid, &c_pids);
	
	printf("Client-[%d] Server-[null]: Sending PID\n", c_pid);

	/* initialize message with own PID */ 
	init_msg(snd_msg, CLIENT_MSG, 0, c_pids);

	/* send PID to server */
	mesg_send(snd_msg);

	printf("Waiting for server response...\n");
	/* read msg from server */
	mesg_recv(rcv_msg, SERVER_MSG);
	
	/* store the server PID as an int */
	*s_pid = atoi(rcv_msg->data);

	printf("Client-[%d] Server-[%d]: Recieved response!\n", c_pid, s_pid);
}
示例#23
0
/*------------------------------------------------------------------------------------------------------------------ 
-- FUNCTION:	client_mngr
-- 
-- DATE:		January 21, 2015
-- 
-- REVISIONS:	
-- 
-- DESIGNER:	Ruoqi Jia
-- 
-- PROGRAMMER:	Ruoqi Jia
-- 
-- INTERFACE:	void client_mngr(char * filename, int priority)
-- 						char * filename : the name of file that will be sent from the client and opened by the server
--						int priority : The priority level of the connection. has to be 1-10
--
-- RETURNS: void
-- 
-- NOTES: The main starting point of the client process. It first query for a connection with the server, and once 
-- the acknowledge has been done, the client will wrap up the file name and priority level into a message and send 
-- to the server.
--------------------------------------------------------------------------------------------------------------------*/
void client_mngr(char * filename, int priority)
{
	char * c_pids;
	int s_pid, c_pid = getpid();
	struct msg snd_msg;
	struct msg rcv_msg;;

	/* establish connection */
	connect(c_pid, &snd_msg, &rcv_msg, &s_pid);

	printf("Client-[%d] Server-[%d]: Sending file name-[%s], Priority-[%d]\n", c_pid, s_pid, filename, priority);

	/* initialize message for file request */
	init_msg(&snd_msg, s_pid, priority, filename);

	/* send the message */
	mesg_send(&snd_msg);

	/* waits for the file packets and read it */
	get_qfile(&rcv_msg, c_pid, priority);


}
示例#24
0
文件: stored.c 项目: 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 */
}
示例#25
0
文件: stored.c 项目: AlD/bareos
/* Check Configuration file for necessary info */
static int check_resources()
{
   bool OK = true;
   bool tls_needed;

   me = (STORES *)GetNextRes(R_STORAGE, NULL);
   if (!me) {
      Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
         configfile);
      OK = false;
   }

   if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
      Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
         configfile);
      OK = false;
   }
   if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
      Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
         configfile);
      OK = false;
   }
   if (GetNextRes(R_DEVICE, NULL) == NULL){
      Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
           configfile);
      OK = false;
   }

   if (!me->messages) {
      me->messages = (MSGSRES *)GetNextRes(R_MSGS, NULL);
      if (!me->messages) {
         Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
            configfile);
         OK = false;
      }
   }

   if (!me->working_directory) {
      Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
         configfile);
      OK = false;
   }

   STORES *store;
   foreach_res(store, R_STORAGE) {
      /* tls_require implies tls_enable */
      if (store->tls_require) {
         if (have_tls) {
            store->tls_enable = true;
         } else {
            Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bareos.\n"));
            OK = false;
            continue;
         }
      }

      tls_needed = store->tls_enable || store->tls_authenticate;

      if (!store->tls_certfile && tls_needed) {
         Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Storage \"%s\" in %s.\n"),
              store->hdr.name, configfile);
         OK = false;
      }

      if (!store->tls_keyfile && tls_needed) {
         Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Storage \"%s\" in %s.\n"),
              store->hdr.name, configfile);
         OK = false;
      }

      if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && tls_needed && store->tls_verify_peer) {
         Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
              " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s."
              " At least one CA certificate store is required"
              " when using \"TLS Verify Peer\".\n"),
              store->hdr.name, configfile);
         OK = false;
      }

      /* If everything is well, attempt to initialize our per-resource TLS context */
      if (OK && (tls_needed || store->tls_require)) {
         /* Initialize TLS context:
          * Args: CA certfile, CA certdir, Certfile, Keyfile,
          * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
         store->tls_ctx = new_tls_context(store->tls_ca_certfile,
                                          store->tls_ca_certdir,
                                          store->tls_crlfile,
                                          store->tls_certfile,
                                          store->tls_keyfile,
                                          NULL,
                                          NULL,
                                          store->tls_dhfile,
                                          store->tls_verify_peer);

         if (!store->tls_ctx) {
            Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
                 store->hdr.name, configfile);
            OK = false;
         }

         set_tls_enable(store->tls_ctx, tls_needed);
         set_tls_require(store->tls_ctx, store->tls_require);
      }
   }

   DIRRES *director;
   foreach_res(director, R_DIRECTOR) {
      /* tls_require implies tls_enable */
      if (director->tls_require) {
         director->tls_enable = true;
      }

      tls_needed = director->tls_enable || director->tls_authenticate;

      if (!director->tls_certfile && tls_needed) {
         Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
              director->hdr.name, configfile);
         OK = false;
      }

      if (!director->tls_keyfile && tls_needed) {
         Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
              director->hdr.name, configfile);
         OK = false;
      }

      if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && tls_needed && director->tls_verify_peer) {
         Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
              " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
              " At least one CA certificate store is required"
              " when using \"TLS Verify Peer\".\n"),
              director->hdr.name, configfile);
         OK = false;
      }

      /* If everything is well, attempt to initialize our per-resource TLS context */
      if (OK && (tls_needed || director->tls_require)) {
         /* Initialize TLS context:
          * Args: CA certfile, CA certdir, Certfile, Keyfile,
          * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
         director->tls_ctx = new_tls_context(director->tls_ca_certfile,
                                             director->tls_ca_certdir,
                                             director->tls_crlfile,
                                             director->tls_certfile,
                                             director->tls_keyfile,
                                             NULL,
                                             NULL,
                                             director->tls_dhfile,
                                             director->tls_verify_peer);

         if (!director->tls_ctx) {
            Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
                 director->hdr.name, configfile);
            OK = false;
         }

         set_tls_enable(director->tls_ctx, tls_needed);
         set_tls_require(director->tls_ctx, director->tls_require);
      }
   }

   DEVRES *device;
   foreach_res(device, R_DEVICE) {
      if (device->drive_crypto_enabled && device->cap_bits & CAP_LABEL) {
         Jmsg(NULL, M_FATAL, 0, _("LabelMedia enabled is incompatible with tape crypto on Device \"%s\" in %s.\n"),
              device->hdr.name, configfile);
         OK = false;
      }
   }

   if (OK) {
      OK = init_autochangers();
   }

   if (OK) {
      close_msg(NULL);                   /* close temp message handler */
      init_msg(NULL, me->messages);      /* open daemon message handler */
      set_working_directory(me->working_directory);
   }

   return OK;
}
示例#26
0
void multicast_rcv_cb(evutil_socket_t sock, short ev, void *arg) {
    static char rcv_buff[MDNS_MAX_LEN], ans_buff[MDNS_MAX_LEN];
    static struct sockaddr_in from_addr;
    static int rcv_len, snd_len;
    static unsigned int from_len;
    static dns_msg_t rcv, ans;
    static dns_resource_t ans_r;
    static dns_question_t ans_q;
    static int i, j, jj, fnd, asknm;
    static char * tmp_buff;
    uint32_t rcv_ip;

    init_msg(&rcv);



    memset(rcv_buff, 0, sizeof(rcv_buff));
    memset(&from_addr, 0, sizeof(from_addr));


    if ((rcv_len = recvfrom(sock, rcv_buff, MDNS_MAX_LEN, 0,
      (struct sockaddr*)&from_addr, &from_len)) < 0) {
        return;
    }

    // printf("Received %d bytes from %s: ", rcv_len,
    //        inet_ntoa(from_addr.sin_addr));
    fflush(stdout);
    if(message_from_network(&rcv, rcv_buff, MDNS_MAX_LEN) < 0) {
      printf("bledna wiadomosc\n");
    }
    else if(get_QR(&(rcv.header)) == QR_QUERY) {

      for(i = 0; i < get_QDCOUNT(&(rcv.header)); ++i) {
        if(answer(rcv.questions + i, &ans_r, my_ip) == 0) {
          //potrafie odpowiedziec
          init_msg(&ans);
          set_QR(&(ans.header), QR_RESPONSE);
          set_ANCOUNT(&(ans.header), 1);

          ans.answers = &ans_r;
          snd_len = send_format_msg(&ans, ans_buff);

          if(sendto(sock, ans_buff, snd_len, 0, // TODO unicast
      		    (struct sockaddr *) &multicast_addr,
      		    sizeof(multicast_addr)) != snd_len) {
            fprintf(stderr, "nie udalo sie odpowiedziec na A :c\n");
          }
        }
      }
    }
    else {//if (get_QR(&(rcv.header)) == QR_RESPONSE)

        for(i = 0; i < get_ANCOUNT(&(rcv.header)); ++i) {

          if (is_rA(rcv.answers + i)) {

            for(jj = 0; jj < 4; ++jj){

            }

            rcv_ip = ntohl (*((uint32_t *)rcv.answers[i].RDATA));

            if (names_equal(rcv.answers[i].NAME + rcv.answers[i].NAME[0] + 1,
                            UDP_SERV)) {


              for(j = 0; j < MAX_IPS; ++j) {
                if (names_equal(found_UDP[j], rcv.answers[i].NAME))
                  break;
              }

              if (j == MAX_IPS)
                continue;

              for(jj = 0; jj < MAX_IPS; ++jj) {
                if (found_ips[jj].ip == rcv_ip)
                  break;
              }
              if (jj == MAX_IPS) {
                for(jj = 0; jj < MAX_IPS; ++jj)
                  if(!found_ips[jj].ip) {
                      found_ips[jj].ip = rcv_ip;
                      break;
                  }
              }
              if (jj == MAX_IPS)
               continue; // no bez przesady to sie nie zdarzy

              if(found_ips[jj].ev[0])
                continue;
              found_ips[jj].udp_i = j;
              found_ips[jj].ev[0] = event_new(main_loop, -1,
                  EV_TIMEOUT | EV_PERSIST, udp_delays_ask_cb, (void*) &jj);

              event_add(found_ips[jj].ev[0], &del_tv);
            } else if (names_equal(
              rcv.answers[i].NAME + rcv.answers[i].NAME[0] + 1,
              TCP_SERV)) {

              for(j = 0; j < MAX_IPS; ++j) {
                if (names_equal(found_TCP[j], rcv.answers[i].NAME))
                  break;
              }
              if (j == MAX_IPS)
               continue; //ta nazwa jeszcze nigdy nie byla szukana

              for(jj = 0; jj < MAX_IPS; ++jj) {
                if (found_ips[jj].ip == rcv_ip)
                  break;
              }
              if (jj == MAX_IPS) {
                for(jj = 0; jj < MAX_IPS; ++jj)
                  if(!found_ips[jj].ip) {
                      found_ips[jj].ip = rcv_ip;
                      break;
                  }
              }
              if (jj == MAX_IPS)
                continue; // no bez przesady to sie nie zdarzy



              if(found_ips[jj].ev[0])
                continue;
              found_ips[jj].tcp_i = j;
              found_ips[jj].ev[1] = event_new(main_loop, -1,
                  EV_TIMEOUT | EV_PERSIST, tcp_delay_cb, (void*) &jj);

              event_add(found_ips[jj].ev[0], &del_tv);


            }
          }
          else if (is_rPTR(rcv.answers + i)) {
            asknm = 0;
            if(rPTR_my_name(rcv.answers + i, rcv_buff))
              continue; // zmien nazwe komputera

            tmp_buff = (char *) malloc(sizeof(char) * NAME_MLENGTH);
            memset(tmp_buff, 0, sizeof(char) * NAME_MLENGTH);
            get_NAME_from_net(tmp_buff, rcv.answers[i].RDATA,
                              rcv.answers[i].RDLENGTH, rcv_buff);
            if(rPTR_UDP(rcv.answers + i, rcv_buff)) {
              asknm = 1;
              fnd = 0;
              for(j = 0; j < MAX_IPS; ++j){
                if(found_UDP[i]) {
                  if (names_equal(found_UDP[j], tmp_buff)){
                    fnd = 1;
                    asknm = 0;
                    break;
                  }
                }
              }

              for(j = 0; !fnd && (j < MAX_IPS); ++j) {
                if (found_UDP[j] == NULL)
                  break;
              }
              if(j >= MAX_IPS || fnd)
                free(tmp_buff);
              else
                found_UDP[j] = tmp_buff;
            }
            else if(rPTR_TCP(rcv.answers + i, rcv_buff)) {
              fnd = 0;
              asknm = 1;
              for(j = 0; j < MAX_IPS; ++j){
                if(found_TCP[j]) {
                  if (names_equal(found_TCP[j], tmp_buff)){
                    fnd = 1;
                    asknm = 0;
                    break;
                  }
                }
              }

              for(j = 0; !fnd && (j < MAX_IPS); ++j) {
                if (found_TCP[j] == NULL)
                  break;
              }
              if(j >= MAX_IPS || fnd)
                free(tmp_buff);
              else
                found_TCP[j] = tmp_buff;
            }
            else free(tmp_buff);
            if(asknm) {
              ask_A(tmp_buff, &ans_q);
              init_msg(&ans);
              set_QR(&(ans.header), QR_QUERY);
              set_QDCOUNT(&(ans.header), 1);

              ans.questions = &ans_q;
              snd_len = send_format_msg(&ans, ans_buff);

              if(sendto(sock, ans_buff, snd_len, 0,
          		    (struct sockaddr *) &multicast_addr,
          		    sizeof(multicast_addr)) != snd_len) {
                    fprintf(stderr, "nie udalo sie zapytc o A :c\n");
              }
            }
          }

        }
      }

      clean_msg(&rcv);



}
示例#27
0
文件: bls.c 项目: 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;
}
示例#28
0
文件: bvfs_test.c 项目: tuxmux/bareos
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;
}
示例#29
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;
}
示例#30
0
/*cli pthread:deal the client data*/
void *fun(void *arg)
{
	int cli_fd_t = cli_fd;
	char buf_fun[BUFSIZ];
	bzero(buf_fun,BUFSIZ);
	memcpy(buf_fun,(char *)arg,BUFSIZ);
	/*pose sem let main function continue*/
	sem_post(&sem);
#if DEBUG
	printf("thread original data :---------------------------------\n%s\n",buf_fun);
	printf("strlen of buf_fun :---------------------------------%d\n",strlen(buf_fun));
#endif
	//if(strncmp(buf_fun,"\n",1) == 0)
	//	pthread_exit(0);
	if(strlen(buf_fun) <= 9)
		pthread_exit(0);

	/*decording json*/
	json_object *jiebao, *jiebao_cmd, *jiebao_flag;
	jiebao= json_tokener_parse(buf_fun);

	const char *pstr;
	jiebao_cmd=json_object_array_get_idx(jiebao,0);
	jiebao_flag=json_object_object_get(jiebao_cmd,"fla");
	pstr =json_object_get_string(jiebao_flag);
	int int_pstr = atoi(pstr);
	switch(int_pstr){
#if DEBUG
		printf("pstr == %s\n",pstr);
#endif
		/*search for seat*/
	case 11:
		{
			int re;	
			char **result;
			int nrow = 0;
			int ncolumn = 0;
			char *errmsg;

			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			//pthread_mutex_unlock(&mutex);
			/*search db*/
			re=sqlite3_get_table(db,"select * from tbmenu",&result,&nrow,&ncolumn,&errmsg);
			if(re != SQLITE_OK){
				printf("%s\n",errmsg);
				//exit(-1);
			}
			pthread_mutex_unlock(&mutex);

			int x = 0,y = 0,index = 0;
			index = ncolumn;
			/*pakage json*/
			struct json_object *my_json[nrow];

			for( x=0; x<nrow; x++){
				my_json[x]=json_object_new_object();
			}

			for( x=0; x<nrow; x++){
				for( y=0; y<ncolumn; y++){
					//printf("%s\t",result[index++]);
					json_object_object_add(my_json[x],result[y],json_object_new_string(result[index++]));
				}
			}

			sqlite3_free_table(result);

			struct json_object *json_shuzu;
			json_shuzu=json_object_new_array();
			for( x=0; x<nrow; x++){
				json_object_array_add(json_shuzu,my_json[x]);
			}

			const char * buf_cst =json_object_to_json_string(json_shuzu);
			write(cli_fd_t,buf_cst,strlen(buf_cst));
#if DEBUG
			printf("return seat json:--------------------------------\n%s\n",buf_cst);
#endif
		}break;
		/*choose one table*/
	case 12:
		{
			int json_length = json_object_array_length(jiebao);
			if(json_length != 2){
				char *buf_no= "NO";
				//write(cli_fd_t,buf_no,strlen(buf_no));
				//break;
				pthread_exit(0);
			}
			else {
				char *buf_ok="OK";
				//write(cli_fd_t,buf_ok,strlen(buf_ok));
			}
			json_object *json_seat,*json_seat_tmp;
			json_seat = json_object_array_get_idx(jiebao,1);
			int tb_id;
			char cust_name[30];
			const char *ppstr;
			json_seat_tmp = json_object_object_get(json_seat,"id1");
			ppstr =json_object_get_string(json_seat_tmp);
			tb_id = atoi(ppstr);
			sprintf(cust_name,"cli_id_%d",cli_fd_t);

			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			cust(tb_id,cust_name);
			pthread_mutex_unlock(&mutex);
#if DEBUG
			printf("booking seat OK!--------------------------------------\n");
#endif
		}break;
		/*search for food*/
	case 21:
		{
			int re;	
			char **result;
			int nrow = 0;
			int ncolumn = 0;
			char *errmsg;

			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			/*search db*/
			re=sqlite3_get_table(db,"select * from fdmenu",&result,&nrow,&ncolumn,&errmsg);
			if(re != SQLITE_OK){
				printf("%s\n",errmsg);
				exit(-1);
			}
			pthread_mutex_unlock(&mutex);

			int x = 0,y = 0,index = 0;
			index = ncolumn;

			/*pakage json*/
			struct json_object *my_json[nrow];

			for( x=0; x<nrow; x++){
				my_json[x]=json_object_new_object();
			}

			for( x=0; x<nrow; x++){
				for( y=0; y<ncolumn; y++){
					//printf("%s\t",result[index++]);
					json_object_object_add(my_json[x],result[y],json_object_new_string(result[index++]));
				}
			}

			sqlite3_free_table(result);

			struct json_object *json_shuzu;
			json_shuzu=json_object_new_array();
			for( x=0; x<nrow; x++){
				json_object_array_add(json_shuzu,my_json[x]);
			}

			const char * buf_cst =json_object_to_json_string(json_shuzu);


			write(cli_fd_t,buf_cst,strlen(buf_cst));
#if DEBUG
			printf("send food table to client:------------------------------------\n%s\n",buf_cst);
#endif
		}break;
		/*add food*/
	case 23:;
			/*hand up the food tab*/
	case 22:
			{
				int json_length = json_object_array_length(jiebao);

				if(json_length == 1){
					char *buf_no= "NO";
					//write(cli_fd_t,buf_no,strlen(buf_no));
					//break;
					pthread_exit(0);
				}
				else {
					char *buf_ok="OK";
					//write(cli_fd_t,buf_ok,strlen(buf_ok));
					if(int_pstr == 22)
						total_client++;
				}
				json_object *json_fd[json_length],*json_fd_tmp[3];
				int i;
				const char *ptmp[3];
				char cust_name22[30];
				sprintf(cust_name22,"cli_id_%d",cli_fd_t);
				//char tmpchar[20];
				for(i = 1; i < json_length; i++){
					json_fd[i]= json_object_array_get_idx(jiebao,i);
					json_fd_tmp[0] = json_object_object_get(json_fd[i],"id1");//fd_id
					json_fd_tmp[1] = json_object_object_get(json_fd[i],"foodname");//fd_name
					json_fd_tmp[2] = json_object_object_get(json_fd[i],"prices");//prices
					int n;
					for(n = 0; n < 3; n++){
						ptmp[n] = json_object_get_string(json_fd_tmp[n]);
					}
					//bzero(tmpchar,20);
					//strcpy(tmpchar,ptmp[1]);
					//insert_cust(cust_name22, atoi(ptmp[0]),tmpchar,atoi(ptmp[2]));
					if(pthread_mutex_lock(&mutex)){
						printf("database lock failed!\n");
						pthread_exit(NULL);
					}
					add(atoi(ptmp[0]),cust_name22);
					pthread_mutex_unlock(&mutex);
				}

				struct message msg;
				int pid;
				pid = init_msg(&msg);
				msg.msg_type = 1;
				strncpy(msg.msg_text,cust_name22,strlen(cust_name22));
				if(msgsnd(pid, &msg, strlen(msg.msg_text),0) == -1)
					handle_error("msgsnd");

#if DEBUG
				printf("got food table from client.----------------------------------\n");
				printf("it is waiting to be cook.----------------------------------\n");
#endif
			}break;

			/*ask for faster*/
	case 31:
			{
				int re;	
				char **result;
				int nrow = 0;
				int ncolumn = 0;
				char *errmsg;

				if(pthread_mutex_lock(&mutex)){
					printf("database lock failed!\n");
					pthread_exit(NULL);
				}
				/*search db*/
				re=sqlite3_get_table(db,"select condition from tbmenu where condition = 1",&result,&nrow,&ncolumn,&errmsg);
				if(re != SQLITE_OK){
					printf("%s\n",errmsg);
					exit(-1);
				}
				pthread_mutex_unlock(&mutex);
				sqlite3_free_table(result);

#if DEBUG
				printf("get asking :%d pepeo---\n",nrow);
#endif
				struct message msg;
				int pid;
				pid = init_msg(&msg);
				msg.msg_type = 2;
				bzero(msg.msg_text,BUFSIZ);
				char buf[100];
				bzero(buf,100);
				sprintf(buf,"%d",nrow);
				strncpy(msg.msg_text,buf,strlen(buf));
#if DEBUG
				printf("msgsnd contain %s\n", msg.msg_text);
#endif
				if(msgsnd(pid, &msg, strlen(msg.msg_text),0) == -1)
					handle_error("msgsnd");
#if DEBUG
				printf("msgsnd ok\n");
#endif
			}break;
			/*apply for money*/
	case 41:
			{
#if DEBUG
				printf("come into 41: \n");
#endif
				int json_length = json_object_array_length(jiebao);
				if(json_length != 2){
					char *buf_no= "NO";
					//write(cli_fd_t,buf_no,strlen(buf_no));
					break;
				}
#if DEBUG
				printf("not break here: \n");
#endif
				json_object *json_moy,*json_moy_tmp;
				json_moy_tmp = json_object_array_get_idx(jiebao,1);
				json_moy = json_object_object_get(json_moy_tmp,"prices");	
				char cust_name31[30];
				sprintf(cust_name31,"cli_id_%d",cli_fd_t);
				const char *moy_tmp = json_object_get_string(json_moy);

				if(pthread_mutex_lock(&mutex)){
					printf("database lock failed!\n");
					pthread_exit(NULL);
				}
				insert_cust(cust_name31, 0,NULL,atoi(moy_tmp));//total money
				total_money += atoi(moy_tmp);
#if DEBUG
				printf("money is :%s\n",moy_tmp);
				printf("%d\n",total_money);
#endif
				pthread_mutex_unlock(&mutex);
#if DEBUG
				printf("client apply for money.---------------------------------------\n");
#endif
			}break;

			/*client off line or have applied the money*/
	case 51:
			{
				if(pthread_mutex_lock(&mutex)){
					printf("database lock failed!\n");
					pthread_exit(NULL);
				}
				char cust_name_delete[30];
				sprintf(cust_name_delete,"cli_id_%d",cli_fd_t);//delete the table of a client
				cust_delete(cust_name_delete);
				pthread_mutex_unlock(&mutex);
			}break;
	default:break;
	}
	pthread_exit(0);
}