Ejemplo n.º 1
0
static DWORD service_run(void)
{
    char filename[_MAX_PATH+1];
    char home[_MAX_PATH+1], *p;
    char *svc_argv[2] = {filename, "-D"};

    if (!hMustTerminate)
        hMustTerminate = CreateEvent(NULL, FALSE, FALSE, NULL);
    set_nt_exit_event(hMustTerminate);
    DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),
                    &hThread, 0, FALSE, DUPLICATE_SAME_ACCESS);

    GetModuleFileName(NULL , filename, _MAX_PATH);
    strcpy(home, filename);
    if (p = strrchr(home, '\\')) {
        *p = 0;
        chdir(home);
    }

    if (!set_stdfiles()) {
        event_log(1010, "stdin|stdout|stderr not created");
        return ERROR_SERVICE_NOT_ACTIVE;
    }

    send_status(SERVICE_RUNNING, NO_ERROR, 0, 1060);
    event_log(10, "Mixmaster Service started");

    mix_main(2, svc_argv);
    return 0;
} /* service_run */
Ejemplo n.º 2
0
/**
 * this function used for bundling of control chunks
 * Used by SCTP-control and Path management
 *
 * @param chunk pointer to chunk, that is to be put in the bundling buffer
 * @return TODO : error value, 0 on success
 */
gint
bu_put_Ctrl_Chunk (SCTP_simple_chunk * chunk, unsigned int * dest_index)
{
  gint result;
  bundling_instance *bu_ptr;
  gint count;
  gboolean lock;

  event_log(INTERNAL_EVENT_0, "bu_put_Ctrl_Chunk() was called");

  bu_ptr = (bundling_instance *) mdi_readBundling ();

  if (!bu_ptr)
  { /* Assume that no association exists, so we take the global bundling buffer */
    event_log(VERBOSE, "Copying Control Chunk to global bundling buffer ");
    bu_ptr = global_buffer;
  }

  if (TOTAL_SIZE(bu_ptr) + CHUNKP_LENGTH((chunk_fixed_t * ) chunk)
      >= MAX_SCTP_PDU)
  {
    lock = bu_ptr->locked;
    event_logi(
        VERBOSE,
        "Chunk Length exceeded MAX_SCTP_PDU : sending chunk to address %u !",
        (dest_index==NULL)?0:*dest_index);
    if (lock)
      bu_ptr->locked = FALSE;
    result = bu_sendAllChunks (dest_index);
    if (lock)
      bu_ptr->locked = TRUE;
  }
  else if (dest_index != NULL)
  {
    bu_ptr->got_send_address = TRUE;
    bu_ptr->requested_destination = *dest_index;
  }

  memcpy (&(bu_ptr->ctrl_buf[bu_ptr->ctrl_position]), chunk,
          CHUNKP_LENGTH((chunk_fixed_t * ) chunk));
  bu_ptr->ctrl_position += CHUNKP_LENGTH((chunk_fixed_t * ) chunk);
  /* insert padding, if necessary */
  if ((CHUNKP_LENGTH((chunk_fixed_t *) chunk) % 4) != 0)
  {
    for (count = 0; count < (4 - (CHUNKP_LENGTH((chunk_fixed_t *) chunk) % 4));
        count++)
    {
      bu_ptr->ctrl_buf[bu_ptr->ctrl_position] = 0;
      bu_ptr->ctrl_position++;
    }
  }
  event_logii(
      VERBOSE,
      "Put Control Chunk Length : %u , Total buffer size now (includes pad): %u\n",
      CHUNKP_LENGTH((chunk_fixed_t *) chunk), TOTAL_SIZE(bu_ptr));

  bu_ptr->ctrl_chunk_in_buffer = TRUE;
  return 0;
}
Ejemplo n.º 3
0
/**
 * Called by recvcontrol, when a SACK must be piggy-backed
 * TODO : Handle multiple calls to this function between two send events
 *
 * @param chunk pointer to chunk, that is to be put in the bundling buffer
 * @return error value, 0 on success, -1 on error
 */
gint
bu_put_SACK_Chunk (SCTP_sack_chunk * chunk, unsigned int * dest_index)
{
  gint result;
  bundling_instance *bu_ptr;
  gboolean lock;

  event_log(INTERNAL_EVENT_0, "bu_put_SACK_Chunk() was called ");

  bu_ptr = (bundling_instance *) mdi_readBundling ();

  if (!bu_ptr)
  { /* Assume that no association exists, so we take the global bundling buffer */
    event_log(VERBOSE, "Copying SACK to global bundling buffer ");
    bu_ptr = global_buffer;
  }

  if (SACK_SIZE(bu_ptr) + CHUNKP_LENGTH((chunk_fixed_t * ) chunk)
      >= MAX_SCTP_PDU)
  {
    lock = bu_ptr->locked;
    event_logi(
        VERBOSE,
        "Chunk Length exceeded MAX_SCTP_PDU : sending chunk to address %u !",
        (dest_index==NULL)?0:*dest_index);
    if (lock)
      bu_ptr->locked = FALSE;
    result = bu_sendAllChunks (dest_index);
    if (lock)
      bu_ptr->locked = TRUE;
  }
  else if (dest_index != NULL)
  {
    bu_ptr->got_send_address = TRUE;
    bu_ptr->requested_destination = *dest_index;
  }

  if (bu_ptr->sack_in_buffer == TRUE)
  { /* multiple calls in between */
    event_log(
        INTERNAL_EVENT_0,
        "bu_put_SACK_Chunk was called a second time, deleting first chunk");
    bu_ptr->sack_position = sizeof(SCTP_common_header);
  }

  memcpy (&(bu_ptr->sack_buf[bu_ptr->sack_position]), chunk,
          CHUNKP_LENGTH((chunk_fixed_t * ) chunk));
  bu_ptr->sack_position += CHUNKP_LENGTH((chunk_fixed_t * ) chunk);
  bu_ptr->sack_in_buffer = TRUE;

  event_logii(VERBOSE,
              "Put SACK Chunk Length : %u , Total buffer size now: %u\n",
              CHUNKP_LENGTH((chunk_fixed_t *) chunk), TOTAL_SIZE(bu_ptr));

  /* SACK always multiple of 32 bytes, do not care about padding */
  return 0;
}
Ejemplo n.º 4
0
/**
 * Keep sender from sending data right away - wait after received chunks have
 * been diassembled completely.
 */
void bu_lock_sender()
{
    bundling_instance *bu_ptr;
    event_log(VERBOSE, "bu_lock_sender() was called... ");

    bu_ptr = (bundling_instance *) mdi_readBundling();
    if (!bu_ptr) {              /* Assume that no association exists, so we take the global bundling buffer */
        event_log(VERBOSE, "Setting global bundling buffer ");
        bu_ptr = global_buffer;
    }
    bu_ptr->locked = TRUE;
    bu_ptr->got_send_request = FALSE;
}
Ejemplo n.º 5
0
/**
 * this function used for putting data chunks into the buffer
 * Used only in the flow control module
 *
 * @param chunk pointer to chunk, that is to be put in the bundling buffer
 * @return TODO : error value, 0 on success
 */
gint bu_put_Data_Chunk(SCTP_simple_chunk * chunk,unsigned int * dest_index)
{
    bundling_instance *bu_ptr;
    gint count;
    gboolean lock;

    event_log(INTERNAL_EVENT_0, "bu_put_Data_Chunk() was called ");

    bu_ptr = (bundling_instance *) mdi_readBundling();

    if (!bu_ptr) {              /* Assume that no association exists, so we take the global bundling buffer */
        event_log(VERBOSE, "Copying data to global bundling buffer ");
        bu_ptr = global_buffer;
    }

    if (TOTAL_SIZE(bu_ptr) + CHUNKP_LENGTH((SCTP_chunk_header *) chunk) >= MAX_SCTP_PDU) {
        lock = bu_ptr->locked;
        event_logi(VERBOSE,
                  "Chunk Length exceeded MAX_SCTP_PDU : sending chunk to address %u !",
                    (dest_index==NULL)?0:*dest_index);
        if (lock) bu_ptr->locked = FALSE;
        bu_sendAllChunks(dest_index);
        if (lock) bu_ptr->locked = TRUE;
    } else if (dest_index != NULL) {
        bu_ptr->got_send_address = TRUE;
        bu_ptr->requested_destination = *dest_index;
    }
    memcpy(&(bu_ptr->data_buf[bu_ptr->data_position]), chunk,
           CHUNKP_LENGTH((SCTP_chunk_header *) chunk));
    bu_ptr->data_position += CHUNKP_LENGTH((SCTP_chunk_header *) chunk);


    /* insert padding, if necessary */
    if ((CHUNKP_LENGTH((SCTP_chunk_header *) chunk) % 4) != 0) {
        for (count = 0; count < (4 - (CHUNKP_LENGTH((SCTP_chunk_header *) chunk) % 4)); count++) {
            bu_ptr->data_buf[bu_ptr->data_position] = 0;
            bu_ptr->data_position++;
        }
    }
    event_logii(VERBOSE, "Put Data Chunk Length : %u , Total buffer size (incl. padding): %u\n",
                CHUNKP_LENGTH((SCTP_chunk_header *) chunk), TOTAL_SIZE(bu_ptr));

    bu_ptr->data_in_buffer = TRUE;

    /* if SACK is waiting, force sending it along */
    if (rxc_sack_timer_is_running() == TRUE) rxc_create_sack(dest_index, TRUE);

    return 0;
}
Ejemplo n.º 6
0
size_t event_log_advice_nn (hashcat_ctx_t *hashcat_ctx, const char *fmt, ...)
{
  event_ctx_t *event_ctx = hashcat_ctx->event_ctx;

  if (fmt == NULL)
  {
    event_ctx->msg_buf[0] = 0;

    event_ctx->msg_len = 0;
  }
  else
  {
    va_list ap;

    va_start (ap, fmt);

    event_ctx->msg_len = event_log (fmt, ap, event_ctx->msg_buf, HCBUFSIZ_TINY - 1);

    va_end (ap);
  }

  event_ctx->msg_newline = false;

  event_call (EVENT_LOG_ADVICE, hashcat_ctx, NULL, 0);

  return event_ctx->msg_len;
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    SERVICE_TABLE_ENTRY dispatchTable[] = {
        {SVCNAME, (LPSERVICE_MAIN_FUNCTION)service_main},
        {NULL,    NULL}
    };

    if ((argc > 1) && ((argv[1][0] == '-') && (argv[1][1] == '-'))) {
        if (!_stricmp("install-svc", argv[1]+2))
            return install_service();
        else if (!_stricmp("remove-svc", argv[1]+2))
            return remove_service();
        else if (_stricmp("run-svc", argv[1]+2) && !is_nt_service())
            return run_notservice(argc, argv);
    } else if (!is_nt_service()) {
        return run_notservice(argc, argv);
    }
    printf("mix --install-svc   install the service\n");
    printf("mix --remove-svc    remove the service\n");
    printf("mix --run-svc       run as a service\n");
    printf("mix -h          view a summary of the command line options.\n");

    printf("\nStartServiceCtrlDispatcher being called.\n" );
    printf("This may take several seconds.  Please wait.\n" );
    if (!StartServiceCtrlDispatcher(dispatchTable)) {
        printf("Service not started: StartServiceCtrlDispatcher failed.\n" );
        event_log(1000, "Service not started: StartServiceCtrlDispatcher failed");
    }
    return 0;
} /* main */
Ejemplo n.º 8
0
void bit::set_torrent_defaults(const connections& defaults)
{
	pimpl()->default_torrent_max_connections_ = defaults.total;
	pimpl()->default_torrent_max_uploads_ = defaults.uploads;

	event_log().post(shared_ptr<EventDetail>(new EventMsg(
		hal::wform(L"Set torrent connections total %1% and uploads %2%.") 
			% defaults.total % defaults.uploads)));

	pimpl()->default_torrent_download_ = defaults.download_rate;
	pimpl()->default_torrent_upload_ = defaults.upload_rate;

	event_log().post(shared_ptr<EventDetail>(new EventMsg(
		hal::wform(L"Set torrent default rates at %1$.2fkb/s down and %2$.2fkb/s upload.") 
			% defaults.download_rate % defaults.upload_rate)));
}
Ejemplo n.º 9
0
void PlayerInst::use_move(GameState* gs, const GameAction& action) {
	perf_timer_begin(FUNCNAME);
	int dx = action.action_x;
	int dy = action.action_y;

	float mag = effective_stats().movespeed;

	float ddx = dx * mag;
	float ddy = dy * mag;

	EnemyInst* target = NULL;
//Enemy hitting test for melee
	gs->object_radius_test(this, (GameInst**)&target, 1, &enemy_colfilter,
			x + ddx * 2, y + ddy * 2);

//Smaller radius enemy pushing test, can intercept enemy radius but not too far
	EnemyInst* alreadyhitting[5] = { 0, 0, 0, 0, 0 };
	gs->object_radius_test(this, (GameInst**)alreadyhitting, 5,
			&enemy_colfilter, x, y, radius);
	bool already = false;
	for (int i = 0; i < 5; i++) {
		if (alreadyhitting[i]) {
			if (ddx < 0 == ((alreadyhitting[i]->x - x + ddx * 2) < 0)) {
				ddx = 0;
			}
			if (ddy < 0 == ((alreadyhitting[i]->y - y + ddy * 2) < 0)) {
				ddy = 0;
			}
			already = true;
		}
	}

	Pos newpos(round(rx + ddx), round(ry + ddy));

	if (!gs->tile_radius_test(newpos.x, newpos.y, radius)) {
		vx = ddx;
		vy = ddy;
	} else if (!gs->tile_radius_test(newpos.x, y, radius)) {
		vx = ddx;
	} else if (!gs->tile_radius_test(x, newpos.y, radius)) {
		vy = ddy;
	} else if (ddx != 0 && ddy != 0) {
		//Alternatives in opposite directions for x & y
		Pos newpos_alt1(round(vx + ddx), round(vy - ddy));
		Pos newpos_alt2(round(vx - ddx), round(vy + ddy));
		if (!gs->tile_radius_test(newpos_alt1.x, newpos_alt1.y, radius)) {
			vx += ddx;
			vy -= ddy;
		} else if (!gs->tile_radius_test(newpos_alt2.x, newpos_alt2.y,
				radius)) {
			vx -= ddx;
			vy += ddy;
		}

	}

	event_log("Player id: %d using move for turn %d, vx=%f, vy=%f\n", id, gs->frame(), vx, vy);
	perf_timer_end(FUNCNAME);
}
Ejemplo n.º 10
0
void eventlist_log(event_t* events)
{
    event_t* e = events;
    while (e) {
        event_log(e);
        e = e->next;
    }
}
Ejemplo n.º 11
0
void bit::set_session_half_open_limit(int halfConn)
{
	libt::session_settings s = pimpl()->session_->settings();
	s.half_open_limit = halfConn;
	pimpl()->session_->set_settings(s);

	event_log().post(shared_ptr<EventDetail>(new EventMsg(
		hal::wform(L"Set half-open connections limit to %1%.") % s.half_open_limit)));
}
Ejemplo n.º 12
0
/**
 * looks for Error chunk_type in a newly received datagram
 * that contains a special error cause code
 *
 * All chunks within the datagram are lookes at, until one is found
 * that equals the parameter chunk_type.
 * @param  datagram     pointer to the newly received data
 * @param  len          stop after this many bytes
 * @param  error_cause  error cause code to look for
 * @return true is chunk_type exists in SCTP datagram, false if it is not in there
 */
gboolean rbu_scanDatagramForError(guchar * datagram, guint len, gushort error_cause)
{
    gushort processed_len = 0, param_length = 0, chunk_length = 0;
    gushort err_len = 0;

    guchar *current_position;
    guint pad_bytes;
    SCTP_simple_chunk *chunk;
    SCTP_staleCookieError *err_chunk;


    current_position = datagram; /* points to the first chunk in this pdu */
    while (processed_len < len) {

        event_logii(VERBOSE,
                    "rbu_scanDatagramForError : len==%u, processed_len == %u", len, processed_len);

        chunk = (SCTP_simple_chunk *) current_position;
        chunk_length = CHUNKP_LENGTH((SCTP_chunk_header *) chunk);
        if (chunk_length < 4 || chunk_length + processed_len > len) return FALSE;

        if (chunk->chunk_header.chunk_id == CHUNK_ERROR) {

            if (chunk_length < 4 || chunk_length + processed_len > len) return FALSE;

            event_log(INTERNAL_EVENT_0, "rbu_scanDatagramForError : Error Chunk Found");
            /* now search for error parameter that fits */
            while (err_len < chunk_length - sizeof(SCTP_chunk_header))  {
                err_chunk = (SCTP_staleCookieError *) &(chunk->simple_chunk_data[err_len]);
                if (ntohs(err_chunk->vlparam_header.param_type) == error_cause) {
                    event_logi(VERBOSE,
                               "rbu_scanDatagramForError : Error Cause %u found -> Returning TRUE",
                               error_cause);
                    return TRUE;
                }
                param_length = ntohs(err_chunk->vlparam_header.param_length);
                if (param_length < 4 || param_length + err_len > len) return FALSE;

                err_len += param_length;
                while ((err_len % 4) != 0)
                    err_len++;
            }
        }

        processed_len += chunk_length;
        pad_bytes = ((processed_len % 4) == 0) ? 0 : (4 - processed_len % 4);
        processed_len += pad_bytes;
        chunk_length = (CHUNKP_LENGTH((SCTP_chunk_header *) chunk) + pad_bytes * sizeof(unsigned char));
        if (chunk_length < 4 || chunk_length + processed_len > len) return FALSE;
        current_position += chunk_length;
    }
    event_logi(VERBOSE,
               "rbu_scanDatagramForError : Error Cause %u NOT found -> Returning FALSE",
               error_cause);
    return FALSE;
}
Ejemplo n.º 13
0
void bit::start_event_receiver()
{
	try {

	pimpl()->start_alert_handler();

	event_log().post(shared_ptr<EventDetail>(new EventMsg(L"	... started handler")));
	
	} HAL_GENERIC_PIMPL_EXCEPTION_CATCH("bit::start_event_receiver()")
}
Ejemplo n.º 14
0
void bit::stop_event_receiver()
{
	try {

	event_log().post(shared_ptr<EventDetail>(new EventMsg(L"Stopping event handler")));

	pimpl()->stop_alert_handler();
	
	} HAL_GENERIC_PIMPL_EXCEPTION_CATCH("bit::stop_event_receiver()")
}
Ejemplo n.º 15
0
gboolean bu_userDataOutbound(void)
{
    bundling_instance *bu_ptr;

    bu_ptr = (bundling_instance *) mdi_readBundling();
    if (!bu_ptr) {              /* Assume that no association exists, so we take the global bundling buffer */
        event_log(VERBOSE, "Setting global bundling buffer ");
        bu_ptr = global_buffer;
    }
    event_logi(VERBOSE, "bu_userDataOutbound() was called... and is %s ",(bu_ptr->data_in_buffer==TRUE)?"TRUE":"FALSE");
    return bu_ptr->data_in_buffer;
}
Ejemplo n.º 16
0
static void service_stop(void)
{
    send_status(SERVICE_STOP_PENDING, NO_ERROR, 5000, 1070);
    if (hMustTerminate) {
        SetEvent(hMustTerminate);
        if (WaitForSingleObject(hThread, 4500) == WAIT_TIMEOUT) {
            if (hThread) {
                TerminateThread(hThread, 0);
                event_log(1080, "Mixmaster Service terminated forcibly");
            }
        } else
            event_log(20, "Mixmaster Service stopped");
        CloseHandle(hMustTerminate);
        hMustTerminate = NULL;
    } else if (hThread)
        TerminateThread(hThread, 0);
    if (hThread)
        CloseHandle(hThread);
    hThread = NULL;
    ssStatus.dwCurrentState = SERVICE_STOPPED;
} /* service_stop */
Ejemplo n.º 17
0
/**
 * Enable sending again - wait after received chunks have
 * been diassembled completely.
 */
void bu_unlock_sender(guint* ad_idx)
{
    bundling_instance *bu_ptr;

    bu_ptr = (bundling_instance *) mdi_readBundling();
    if (!bu_ptr) {              /* Assume that no association exists, so we take the global bundling buffer */
        event_log(VERBOSE, "Setting global bundling buffer ");
        bu_ptr = global_buffer;
    }
    bu_ptr->locked = FALSE;
    event_logi(VERBOSE, "bu_unlock_sender() was called..and got %s send request -> processing",
       (bu_ptr->got_send_request == TRUE)?"A":"NO");

    if (bu_ptr->got_send_request == TRUE) bu_sendAllChunks(ad_idx);

}
Ejemplo n.º 18
0
static BOOL send_status(DWORD current_state, DWORD exit_code, DWORD wait_hint, DWORD id)
{
    static DWORD dwCheckPoint = 1;
    BOOL ret_val;

    if (not_service)
        return TRUE;

    ssStatus.dwCurrentState = current_state;
    ssStatus.dwWin32ExitCode = exit_code;
    ssStatus.dwWaitHint = wait_hint;
    ssStatus.dwControlsAccepted = (current_state == SERVICE_START_PENDING) ?
                                  0 : SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    ssStatus.dwCheckPoint = ((current_state == SERVICE_RUNNING) || (current_state == SERVICE_STOPPED)) ?
                            0 : dwCheckPoint++;

    if (!(ret_val = SetServiceStatus(sshStatusHandle, &ssStatus)))
        event_log(id, "SetServiceStatus failed");
    return ret_val;
} /* send_status */
Ejemplo n.º 19
0
Archivo: log.c Proyecto: Henauxg/minix
static void
_warn_helper(int severity, const char *errstr, const char *fmt, va_list ap)
{
	char buf[1024];
	size_t len;

	if (fmt != NULL)
		evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
	else
		buf[0] = '\0';

	if (errstr) {
		len = strlen(buf);
		if (len < sizeof(buf) - 3) {
			evutil_snprintf(buf + len, sizeof(buf) - len, ": %s", errstr);
		}
	}

	event_log(severity, buf);
}
Ejemplo n.º 20
0
size_t event_log_warning_nn (hashcat_ctx_t *hashcat_ctx, const char *fmt, ...)
{
  va_list ap;

  va_start (ap, fmt);

  event_ctx_t *event_ctx = hashcat_ctx->event_ctx;

  event_ctx->msg_len = event_log (fmt, ap, event_ctx->msg_buf, HCBUFSIZ_TINY - 1);

  event_ctx->msg_buf[event_ctx->msg_len] = 0;

  va_end (ap);

  event_ctx->msg_newline = false;

  event_call (EVENT_LOG_WARNING, hashcat_ctx, NULL, 0);

  return event_ctx->msg_len;
}
Ejemplo n.º 21
0
static void
_warn_helper(int severity, int log_errno, const char *fmt, va_list ap)
{
	char buf[1024];
	size_t len;

	if (fmt != NULL)
		vsnprintf(buf, sizeof(buf), fmt, ap);
	else
		buf[0] = '\0';

	if (log_errno >= 0) {
		len = strlen(buf);
		if (len < sizeof(buf) - 3) {
			snprintf(buf + len, sizeof(buf) - len, ": %s",
			    strerror(log_errno));
		}
	}

	event_log(severity, buf);
}
Ejemplo n.º 22
0
void PlayerInst::perform_action(GameState* gs, const GameAction& action) {
	event_log("Player id=%d performing act=%d, xy=(%d,%d), frame=%d, origin=%d, room=%d, use_id=%d, use_id2=%d\n",
			this->player_entry(gs).net_id,
			action.act, action.action_x,
			action.action_y, action.frame, action.origin, action.room,
			action.use_id, action.use_id2);
	switch (action.act) {
	case GameAction::MOVE:
		return use_move(gs, action);
	case GameAction::USE_WEAPON:
		return use_weapon(gs, action);
	case GameAction::USE_SPELL:
		return use_spell(gs, action);
	case GameAction::USE_REST:
		return use_rest(gs, action);
	case GameAction::USE_PORTAL:
		return use_dngn_portal(gs, action);
	case GameAction::USE_ITEM:
		return use_item(gs, action);
	case GameAction::PICKUP_ITEM:
		return pickup_item(gs, action);
	case GameAction::DROP_ITEM:
		return drop_item(gs, action);
	case GameAction::DEEQUIP_ITEM:
		return equipment().deequip_type(action.use_id);
	case GameAction::REPOSITION_ITEM:
		return reposition_item(gs, action);
	case GameAction::CHOSE_SPELL:
		spellselect = action.use_id;
		return;
	case GameAction::PURCHASE_FROM_STORE:
		return purchase_from_store(gs, action);
	default:
		printf("PlayerInst::perform_action() error: Invalid action id %d!\n",
				action.act);
		break;
	}
}
Ejemplo n.º 23
0
Archivo: log.c Proyecto: TomCN7/Event
void
event_logv_(int severity, const char *errstr, const char *fmt, va_list ap)
{
	char buf[1024];
	size_t len;

	if (severity == EVENT_LOG_DEBUG && !event_debug_get_logging_mask_())
		return;

	if (fmt != NULL)
		evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
	else
		buf[0] = '\0';

	if (errstr) {
		len = strlen(buf);
		if (len < sizeof(buf) - 3) {
			evutil_snprintf(buf + len, sizeof(buf) - len, ": %s", errstr);
		}
	}

	event_log(severity, buf);
}
Ejemplo n.º 24
0
/**
 * Trigger sending of all chunks previously entered with put_Chunk functions
 *  Chunks sent are deleted afterwards.
 *
 * FIXME : special treatment for GLOBAL BUFFER, as this is not associated with
 *         any association.
 *
 *
 *  @return                 Errorcode (0 for good case: length bytes sent; 1 or -1 for error)
 *  @param   ad_idx     pointer to address index or NULL if data is to be sent to default address
 */
gint bu_sendAllChunks(guint * ad_idx)
{
    gint result, send_len = 0;
    guchar *send_buffer = NULL;
    bundling_instance *bu_ptr;
    gshort idx = 0;

    bu_ptr = (bundling_instance *) mdi_readBundling();

    event_log(INTERNAL_EVENT_0, "bu_sendAllChunks() is being executed...");

    if (!bu_ptr) {
        event_log(VERBOSE, "Sending data from global bundling buffer ");
        bu_ptr = global_buffer;
    }
    if (bu_ptr->locked == TRUE) {
        bu_ptr->got_send_request = TRUE;
        if (ad_idx) {
            bu_ptr->got_send_address = TRUE;
            bu_ptr->requested_destination = *ad_idx;
        }
        event_log(INTERNAL_EVENT_0, "bu_sendAllChunks : sender is LOCKED ---> returning ");
        return 1;
    }

    /* TODO : more intelligent path selection strategy */
    /*         should take into account PM_INACTIVE */
    if (ad_idx != NULL) {
        if (*ad_idx > 0xFFFF) {
            error_log(ERROR_FATAL, "address_index too big !");
        } else {
            idx = (short) *ad_idx;
        }
    } else {
        if (bu_ptr->got_send_address) {
            idx = (short)bu_ptr->requested_destination;
        } else {
            idx = -1; /* use last from address */
        }
    }

    event_logi(VVERBOSE, "bu_sendAllChunks : send to path %d ", idx);

    if (bu_ptr->sack_in_buffer)             send_buffer = bu_ptr->sack_buf;
    else if (bu_ptr->ctrl_chunk_in_buffer)  send_buffer = bu_ptr->ctrl_buf;
    else if (bu_ptr->data_in_buffer)        send_buffer = bu_ptr->data_buf;
    else {
        error_log(ERROR_MINOR, "Nothing to send, but bu_sendAllChunks was called !");
        return 1;
    }

    if (bu_ptr->sack_in_buffer) {
        rxc_stop_sack_timer();
        /* SACKs by default go to the last active address, from which data arrived */
        send_len = bu_ptr->sack_position; /* at least sizeof(SCTP_common_header) */
        /* at most pointing to the end of SACK chunk */
        event_logi(VVERBOSE, "bu_sendAllChunks(sack) : send_len == %d ", send_len);
        if (bu_ptr->ctrl_chunk_in_buffer) {
            memcpy(&send_buffer[send_len],
                   &(bu_ptr->ctrl_buf[sizeof(SCTP_common_header)]),
                   (bu_ptr->ctrl_position - sizeof(SCTP_common_header)));
            send_len += bu_ptr->ctrl_position - sizeof(SCTP_common_header);
            event_logi(VVERBOSE, "bu_sendAllChunks(sack+ctrl) : send_len == %d ", send_len);
        }
        if (bu_ptr->data_in_buffer) {
            memcpy(&send_buffer[send_len],
                   &(bu_ptr->data_buf[sizeof(SCTP_common_header)]),
                   (bu_ptr->data_position - sizeof(SCTP_common_header)));
            send_len += bu_ptr->data_position - sizeof(SCTP_common_header);
            event_logi(VVERBOSE, "bu_sendAllChunks(sack+data) : send_len == %d ", send_len);
        }
    } else if (bu_ptr->ctrl_chunk_in_buffer) {
        send_len = bu_ptr->ctrl_position;
        event_logi(VVERBOSE, "bu_sendAllChunks(ctrl) : send_len == %d ", send_len);
        if (bu_ptr->data_in_buffer) {
            memcpy(&send_buffer[send_len],
                   &(bu_ptr->data_buf[sizeof(SCTP_common_header)]),
                   (bu_ptr->data_position - sizeof(SCTP_common_header)));
            send_len += bu_ptr->data_position - sizeof(SCTP_common_header);
            event_logi(VVERBOSE, "bu_sendAllChunks(ctrl+data) : send_len == %d ", send_len);
        }

    } else if (bu_ptr->data_in_buffer) send_len = bu_ptr->data_position;

    event_logi(VVERBOSE, "bu_sendAllChunks(finally) : send_len == %d ", send_len);

    if (send_len > 1480) {
        fprintf(stderr, "MTU definitely exceeded (%u) - aborting\n",send_len);
        fprintf(stderr, "sack_position: %u, ctrl_position: %u, data_position: %u\n",
            bu_ptr->sack_position,bu_ptr->ctrl_position,bu_ptr->data_position);
        abort();
    }

    if ((bu_ptr->data_in_buffer) && (idx != -1)) pm_chunksSentOn(idx);

    event_logii(VERBOSE, "bu_sendAllChunks() : sending message len==%u to adress idx=%d", send_len, idx);

    result = mdi_send_message((SCTP_message *) send_buffer, send_len, idx);

    event_logi(VVERBOSE, "bu_sendAllChunks(): result == %s ", (result==0)?"OKAY":"ERROR");

    /* reset all positions */
    bu_ptr->sack_in_buffer = FALSE;
    bu_ptr->ctrl_chunk_in_buffer = FALSE;
    bu_ptr->data_in_buffer = FALSE;
    bu_ptr->got_send_request = FALSE;
    bu_ptr->got_send_address = FALSE;

    bu_ptr->data_position = sizeof(SCTP_common_header);
    bu_ptr->ctrl_position = sizeof(SCTP_common_header);
    bu_ptr->sack_position = sizeof(SCTP_common_header);

    return result;
}
Ejemplo n.º 25
0
/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ main() $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
int
main(int argc, char *argv[])
{
#ifdef _WITH_BURST_2
   int              cb2_ret;
#endif
   int              current_toggle,
                    exit_status = TRANSFER_SUCCESS,
                    j,
                    fd,
                    status,
                    loops,
                    rest,
                    blocksize,
                    *wmo_counter,
                    wmo_counter_fd = -1;
#ifdef WITH_ARCHIVE_COPY_INFO
   unsigned int     archived_copied = 0;
#endif
   off_t            no_of_bytes;
   time_t           connected,
#ifdef _WITH_BURST_2
                    diff_time,
#endif
                    end_transfer_time_file,
                    start_transfer_time_file = 0,
                    last_update_time,
                    now;
#ifdef _OUTPUT_LOG
   clock_t          end_time = 0,
                    start_time = 0;
   struct tms       tmsdummy;
#endif
   char             *p_file_name_buffer,
                    *buffer,
                    fullname[MAX_PATH_LENGTH + 1],
                    file_path[MAX_PATH_LENGTH];
   clock_t          clktck;
   struct stat      stat_buf;
   struct job       *p_db;
#ifdef SA_FULLDUMP
   struct sigaction sact;
#endif

   CHECK_FOR_VERSION(argc, argv);

#ifdef SA_FULLDUMP
   /*
    * When dumping core sure we do a FULL core dump!
    */
   sact.sa_handler = SIG_DFL;
   sact.sa_flags = SA_FULLDUMP;
   sigemptyset(&sact.sa_mask);
   if (sigaction(SIGSEGV, &sact, NULL) == -1)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "sigaction() error : %s", strerror(errno));
      exit(INCORRECT);
   }
#endif

   /* Do some cleanups when we exit. */
   if (atexit(sf_wmo_exit) != 0)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "Could not register exit function : %s", strerror(errno));
      exit(INCORRECT);
   }

   /* Initialise variables. */
   local_file_counter = 0;
   files_to_send = init_sf(argc, argv, file_path, WMO_FLAG);
   p_db = &db;
   if ((clktck = sysconf(_SC_CLK_TCK)) <= 0)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "Could not get clock ticks per second : %s",
                 strerror(errno));
      exit(INCORRECT);
   }
   if (fsa->trl_per_process > 0)
   {
      if (fsa->trl_per_process < fsa->block_size)
      {
         blocksize = fsa->trl_per_process;
      }
      else
      {
         blocksize = fsa->block_size;
      }
   }
   else
   {
      blocksize = fsa->block_size;
   }

   if ((signal(SIGINT, sig_kill) == SIG_ERR) ||
       (signal(SIGQUIT, sig_exit) == SIG_ERR) ||
       (signal(SIGTERM, SIG_IGN) == SIG_ERR) ||
       (signal(SIGSEGV, sig_segv) == SIG_ERR) ||
       (signal(SIGBUS, sig_bus) == SIG_ERR) ||
       (signal(SIGHUP, SIG_IGN) == SIG_ERR) ||
       (signal(SIGPIPE, SIG_IGN) == SIG_ERR))
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "signal() error : %s", strerror(errno));
      exit(INCORRECT);
   }

   /* Now determine the real hostname. */
   if (db.toggle_host == YES)
   {
      if (fsa->host_toggle == HOST_ONE)
      {
         (void)strcpy(db.hostname, fsa->real_hostname[HOST_TWO - 1]);
         current_toggle = HOST_TWO;
      }
      else
      {
         (void)strcpy(db.hostname, fsa->real_hostname[HOST_ONE - 1]);
         current_toggle = HOST_ONE;
      }
   }
   else
   {
      (void)strcpy(db.hostname,
                   fsa->real_hostname[(int)(fsa->host_toggle - 1)]);
      current_toggle = (int)fsa->host_toggle;
   }

   /* Connect to remote WMO-server. */
#ifdef FTP_CTRL_KEEP_ALIVE_INTERVAL
   if (fsa->protocol_options & AFD_TCP_KEEPALIVE)
   {
      timeout_flag = transfer_timeout - 5;
      if (timeout_flag < MIN_KEEP_ALIVE_INTERVAL)
      {
         timeout_flag = MIN_KEEP_ALIVE_INTERVAL;
      }
   }
#else
   timeout_flag = OFF;
#endif
   if ((status = wmo_connect(db.hostname, db.port, db.sndbuf_size)) != SUCCESS)
   {
      trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                "WMO connection to <%s> at port %d failed (%d).",
                db.hostname, db.port, status);
      exit(eval_timeout(CONNECT_ERROR));
   }
   else
   {
      if (fsa->debug > NORMAL_MODE)
      {
         trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                      "Connected to port %d.", db.port);
      }
   }
   connected = time(NULL);

   /* Inform FSA that we have finished connecting and */
   /* will now start to transfer data.                */
   if (gsf_check_fsa(p_db) != NEITHER)
   {
#ifdef LOCK_DEBUG
      lock_region_w(fsa_fd, db.lock_offset + LOCK_CON, __FILE__, __LINE__);
#else
      lock_region_w(fsa_fd, db.lock_offset + LOCK_CON);
#endif
      fsa->job_status[(int)db.job_no].connect_status = WMO_ACTIVE;
      fsa->job_status[(int)db.job_no].no_of_files = files_to_send;
      fsa->connections += 1;
#ifdef LOCK_DEBUG
      unlock_region(fsa_fd, db.lock_offset + LOCK_CON, __FILE__, __LINE__);
#else
      unlock_region(fsa_fd, db.lock_offset + LOCK_CON);
#endif
   }

   /* Allocate buffer to read data from the source file. */
   if ((buffer = malloc(blocksize + 1 + 4 /* For bulletin end. */)) == NULL)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "malloc() error : %s", strerror(errno));
      exit(ALLOC_ERROR);
   }

   if (db.special_flag & WITH_SEQUENCE_NUMBER)
   {
      char counter_file_name[MAX_FILENAME_LENGTH];

      (void)snprintf(counter_file_name, MAX_FILENAME_LENGTH, "/%s.%d", db.host_alias, db.port);
      if ((wmo_counter_fd = open_counter_file(counter_file_name, &wmo_counter)) < 0)
      {
         system_log(ERROR_SIGN, __FILE__, __LINE__,
                    "Failed to open counter file `%s'.", counter_file_name);
      }
   }

#ifdef _WITH_BURST_2
   do
   {
      if (burst_2_counter > 0)
      {
         if (fsa->debug > NORMAL_MODE)
         {
            trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL, "WMO Bursting.");
         }
      }
#endif

      /* Send all files. */
      p_file_name_buffer = file_name_buffer;
      p_file_size_buffer = file_size_buffer;
      last_update_time = time(NULL);
      local_file_size = 0;
      for (files_send = 0; files_send < files_to_send; files_send++)
      {
         (void)snprintf(fullname, MAX_PATH_LENGTH + 1, "%s/%s",
                        file_path, p_file_name_buffer);

         if (*p_file_size_buffer > 0)
         {
            int end_length = 0,
                header_length = 0,
                length_type_indicator = 10;

            if (gsf_check_fsa(p_db) != NEITHER)
            {
               fsa->job_status[(int)db.job_no].file_size_in_use = *p_file_size_buffer;
               (void)strcpy(fsa->job_status[(int)db.job_no].file_name_in_use,
                            p_file_name_buffer);
            }

            /* Open local file. */
#ifdef O_LARGEFILE
            if ((fd = open(fullname, O_RDONLY | O_LARGEFILE)) == -1)
#else
            if ((fd = open(fullname, O_RDONLY)) == -1)
#endif
            {
               trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                         "Failed to open local file `%s' : %s",
                         fullname, strerror(errno));
               wmo_quit();
               exit(OPEN_LOCAL_ERROR);
            }
            if (fsa->debug > NORMAL_MODE)
            {
                  trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                               "Open local file `%s'", fullname);
            }

#ifdef _OUTPUT_LOG
            if (db.output_log == YES)
            {
               start_time = times(&tmsdummy);
            }
#endif

            /*
             * When the contents does not contain a bulletin header
             * it must be stored in the file name.
             */
            if (db.special_flag & FILE_NAME_IS_HEADER)
            {
               int  space_count;
               char *ptr = p_file_name_buffer;

               buffer[length_type_indicator] = 1; /* SOH */
               buffer[length_type_indicator + 1] = '\015'; /* CR */
               buffer[length_type_indicator + 2] = '\015'; /* CR */
               buffer[length_type_indicator + 3] = '\012'; /* LF */
               header_length = 4;
               space_count = 0;

               if (wmo_counter_fd > 0)
               {
                  if (next_counter(wmo_counter_fd, wmo_counter,
                                   MAX_WMO_COUNTER) < 0)
                  {
                     close_counter_file(wmo_counter_fd, &wmo_counter);
                     wmo_counter_fd = -1;
                     wmo_counter = NULL;
                     system_log(ERROR_SIGN, __FILE__, __LINE__,
                                "Failed to get next WMO counter.");
                  }
                  else
                  {
                     if (*wmo_counter < 10)
                     {
                        buffer[length_type_indicator + header_length] = '0';
                        buffer[length_type_indicator + header_length + 1] = '0';
                        buffer[length_type_indicator + header_length + 2] = *wmo_counter + '0';
                     }
                     else if (*wmo_counter < 100)
                          {
                             buffer[length_type_indicator + header_length] = '0';
                             buffer[length_type_indicator + header_length + 1] = (*wmo_counter / 10) + '0';
                             buffer[length_type_indicator + header_length + 2] = (*wmo_counter % 10) + '0';
                          }
                     else if (*wmo_counter < 1000)
                          {
                             buffer[length_type_indicator + header_length] = ((*wmo_counter / 100) % 10) + '0';
                             buffer[length_type_indicator + header_length + 1] = ((*wmo_counter / 10) % 10) + '0';
                             buffer[length_type_indicator + header_length + 2] = (*wmo_counter % 10) + '0';
                          }
                     buffer[length_type_indicator + header_length + 3] = '\015'; /* CR */
                     buffer[length_type_indicator + header_length + 4] = '\015'; /* CR */
                     buffer[length_type_indicator + header_length + 5] = '\012'; /* LF */
                     header_length += 6;
                  }
               } /* if (wmo_counter_fd > 0) */

               for (;;)
               {
                  while ((*ptr != '_') && (*ptr != '-') && (*ptr != ' ') &&
                         (*ptr != '\0') && (*ptr != '.') && (*ptr != ';'))
                  {
                     buffer[length_type_indicator + header_length] = *ptr;
                     header_length++; ptr++;
                  }
                  if ((*ptr == '\0') || (*ptr == '.') || (*ptr == ';'))
                  {
                     break;
                  }
                  else
                  {
                     if (space_count == 2)
                     {
                        if ((isalpha((int)(*(ptr + 1)))) &&
                            (isalpha((int)(*(ptr + 2)))) &&
                            (isalpha((int)(*(ptr + 3)))))
                        {
                           buffer[length_type_indicator + header_length] = ' ';
                           buffer[length_type_indicator + header_length + 1] = *(ptr + 1);
                           buffer[length_type_indicator + header_length + 2] = *(ptr + 2);
                           buffer[length_type_indicator + header_length + 3] = *(ptr + 3);
                           header_length += 4;
                        }
                        break;
                     }
                     else
                     {
                        buffer[length_type_indicator + header_length] = ' ';
                        header_length++; ptr++; space_count++;
                     }
                  }
               } /* for (;;) */
               buffer[length_type_indicator + header_length] = '\015'; /* CR */
               buffer[length_type_indicator + header_length + 1] = '\015'; /* CR */
               buffer[length_type_indicator + header_length + 2] = '\012'; /* LF */
               header_length += 3;
               end_length = 4;
            }

            /* Read (local) and write (remote) file. */
            no_of_bytes = 0;
            loops = (length_type_indicator + header_length + *p_file_size_buffer) / blocksize;
            rest = (length_type_indicator + header_length + *p_file_size_buffer) % blocksize;

            if ((db.special_flag & FILE_NAME_IS_HEADER) && (rest == 0))
            {
               loops--;
               rest = blocksize;
            }

            /* Write length and type indicator. */
            (void)snprintf(buffer, 9, "%08lu",
                           (unsigned long)(*p_file_size_buffer + header_length + end_length));
            if (db.transfer_mode == 'I')
            {
               buffer[length_type_indicator - 2] = 'B';
               buffer[length_type_indicator - 1] = 'I';
            }
            else if (db.transfer_mode == 'A')
                 {
                    buffer[length_type_indicator - 2] = 'A';
                    buffer[length_type_indicator - 1] = 'N';
                 }
                 else
                 {
                    buffer[length_type_indicator - 2] = 'F';
                    buffer[length_type_indicator - 1] = 'X';
                 }

            if (fsa->trl_per_process > 0)
            {
               init_limit_transfer_rate();
            }
            if (fsa->protocol_options & TIMEOUT_TRANSFER)
            {
               start_transfer_time_file = time(NULL);
            }

            for (;;)
            {
               for (j = 0; j < loops; j++)
               {
#ifdef _SIMULATE_SLOW_TRANSFER
                  (void)sleep(_SIMULATE_SLOW_TRANSFER);
#endif
                  if ((status = read(fd,
                                     (buffer + length_type_indicator + header_length),
                                     (blocksize - length_type_indicator - header_length))) != (blocksize - length_type_indicator - header_length))
                  {
                     trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                               "Could not read() local file `%s' : %s",
                               fullname, strerror(errno));
                     wmo_quit();
                     exit(READ_LOCAL_ERROR);
                  }
                  if ((status = wmo_write(buffer, blocksize)) != SUCCESS)
                  {
                     trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                               "Failed to write block from file `%s' to remote port %d [%d].",
                               p_file_name_buffer, db.port, status);
                     wmo_quit();
                     exit(eval_timeout(WRITE_REMOTE_ERROR));
                  }
                  if (fsa->trl_per_process > 0)
                  {
                     limit_transfer_rate(blocksize, fsa->trl_per_process,
                                         clktck);
                  }

                  no_of_bytes += blocksize;

                  if (gsf_check_fsa(p_db) != NEITHER)
                  {
                     fsa->job_status[(int)db.job_no].file_size_in_use_done = no_of_bytes;
                     fsa->job_status[(int)db.job_no].file_size_done += blocksize;
                     fsa->job_status[(int)db.job_no].bytes_send += blocksize;
                     if (fsa->protocol_options & TIMEOUT_TRANSFER)
                     {
                        end_transfer_time_file = time(NULL);
                        if (end_transfer_time_file < start_transfer_time_file)
                        {
                           start_transfer_time_file = end_transfer_time_file;
                        }
                        else
                        {
                           if ((end_transfer_time_file - start_transfer_time_file) > transfer_timeout)
                           {
                              trans_log(INFO_SIGN, __FILE__, __LINE__, NULL, NULL,
#if SIZEOF_TIME_T == 4
                                        "Transfer timeout reached for `%s' after %ld seconds.",
#else
                                        "Transfer timeout reached for `%s' after %lld seconds.",
#endif
                                        fsa->job_status[(int)db.job_no].file_name_in_use,
                                        (pri_time_t)(end_transfer_time_file - start_transfer_time_file));
                              wmo_quit();
                              exitflag = 0;
                              exit(STILL_FILES_TO_SEND);
                           }
                        }
                     }
                  }
                  if (length_type_indicator > 0)
                  {
                     length_type_indicator = 0;
                     header_length = 0;
                  }
               } /* for (j = 0; j < loops; j++) */

               if (rest > 0)
               {
                  if ((status = read(fd,
                                     (buffer + length_type_indicator + header_length),
                                     (rest - length_type_indicator - header_length))) != (rest - length_type_indicator - header_length))
                  {
                     trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                               "Could not read() local file `%s' : %s",
                               fullname, strerror(errno));
                     wmo_quit();
                     exit(READ_LOCAL_ERROR);
                  }
                  if (end_length == 4)
                  {
                     buffer[rest] = '\015';
                     buffer[rest + 1] = '\015';
                     buffer[rest + 2] = '\012';
                     buffer[rest + 3] = 3;  /* ETX */
                  }
                  if ((status = wmo_write(buffer, rest + end_length)) != SUCCESS)
                  {
                     trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                               "Failed to write rest of file to remote port %d [%d].",
                               p_file_name_buffer, db.port, status);
                     wmo_quit();
                     exit(eval_timeout(WRITE_REMOTE_ERROR));
                  }
                  if (fsa->trl_per_process > 0)
                  {
                     limit_transfer_rate(rest + end_length,
                                         fsa->trl_per_process, clktck);
                  }

                  no_of_bytes += rest + end_length;

                  if (gsf_check_fsa(p_db) != NEITHER)
                  {
                     fsa->job_status[(int)db.job_no].file_size_in_use_done = no_of_bytes;
                     fsa->job_status[(int)db.job_no].file_size_done += rest;
                     fsa->job_status[(int)db.job_no].bytes_send += rest;
                  }
               }

               /*
                * Since there are always some users sending files to the
                * AFD not in dot notation, lets check here if this is really
                * the EOF.
                * If not lets continue so long until we hopefully have reached
                * the EOF.
                * NOTE: This is NOT a fool proof way. There must be a better
                *       way!
                */
               if (fstat(fd, &stat_buf) == -1)
               {
                  (void)rec(transfer_log_fd, DEBUG_SIGN,
                            "Hmmm. Failed to stat() `%s' : %s (%s %d)\n",
                            fullname, strerror(errno), __FILE__, __LINE__);
                  break;
               }
               else
               {
                  if (stat_buf.st_size > *p_file_size_buffer)
                  {
                     char sign[LOG_SIGN_LENGTH];

                     if (db.special_flag & SILENT_NOT_LOCKED_FILE)
                     {
                        (void)memcpy(sign, DEBUG_SIGN, LOG_SIGN_LENGTH);
                     }
                     else
                     {
                        (void)memcpy(sign, WARN_SIGN, LOG_SIGN_LENGTH);
                     }

                     loops = (stat_buf.st_size - *p_file_size_buffer) / blocksize;
                     rest = (stat_buf.st_size - *p_file_size_buffer) % blocksize;
                     *p_file_size_buffer = stat_buf.st_size;

                     /*
                      * Give a warning in the receive log, so some action
                      * can be taken against the originator.
                      */
                     receive_log(sign, __FILE__, __LINE__, 0L, db.id.job,
                                 "File `%s' for host %s was DEFINITELY send without any locking. #%x",
                                 p_file_name_buffer, fsa->host_dsp_name, db.id.job);
                  }
                  else
                  {
                     break;
                  }
               }
            } /* for (;;) */

            if (db.special_flag & WMO_CHECK_ACKNOWLEDGE)
            {
               int ret;

               if ((ret = wmo_check_reply()) == INCORRECT)
               {
                  trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                            "Failed to receive reply from port %d for file %s.",
                            db.port, p_file_name_buffer);
                  wmo_quit();
                  exit(eval_timeout(CHECK_REPLY_ERROR));
               }
               else if (ret == NEGATIV_ACKNOWLEDGE)
                    {
                       trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                                 "Received negative acknowledge from remote port %d for file %s.",
                                 db.port, p_file_name_buffer);
                    }
            }

#ifdef _OUTPUT_LOG
            if (db.output_log == YES)
            {
               end_time = times(&tmsdummy);
            }
#endif

            /* Close local file. */
            if (close(fd) == -1)
            {
               (void)rec(transfer_log_fd, WARN_SIGN,
                         "%-*s[%d]: Failed to close() local file %s : %s (%s %d)\n",
                         MAX_HOSTNAME_LENGTH, tr_hostname, (int)db.job_no,
                         p_file_name_buffer, strerror(errno),
                         __FILE__, __LINE__);
               /*
                * Since we usually do not send more then 100 files and
                * sf_wmo() will exit(), there is no point in stopping
                * the transmission.
                */
            }
         }
         else
         {
            trans_log(INFO_SIGN, __FILE__, __LINE__, NULL, NULL,
                      "File `%s' is of zero length, ignoring.",
                      p_file_name_buffer);
         }

         /* Update FSA, one file transmitted. */
         if (gsf_check_fsa(p_db) != NEITHER)
         {
            fsa->job_status[(int)db.job_no].file_name_in_use[0] = '\0';
            fsa->job_status[(int)db.job_no].no_of_files_done++;
            fsa->job_status[(int)db.job_no].file_size_in_use = 0;
            fsa->job_status[(int)db.job_no].file_size_in_use_done = 0;
            local_file_size += *p_file_size_buffer;
            local_file_counter += 1;

            now = time(NULL);
            if (now >= (last_update_time + LOCK_INTERVAL_TIME))
            {
               last_update_time = now;
               update_tfc(local_file_counter, local_file_size,
                          p_file_size_buffer, files_to_send,
                          files_send, now);
               local_file_size = 0;
               local_file_counter = 0;
            }
         }

#ifdef _WITH_TRANS_EXEC
         if (db.special_flag & TRANS_EXEC)
         {
            trans_exec(file_path, fullname, p_file_name_buffer, clktck);
         }
#endif

#ifdef _OUTPUT_LOG
         if (db.output_log == YES)
         {
            if (ol_fd == -2)
            {
# ifdef WITHOUT_FIFO_RW_SUPPORT
               output_log_fd(&ol_fd, &ol_readfd, &db.output_log);
# else
               output_log_fd(&ol_fd, &db.output_log);
# endif
            }
            if ((ol_fd > -1) && (ol_data == NULL))
            {
               output_log_ptrs(&ol_retries,
                               &ol_job_number,
                               &ol_data,              /* Pointer to buffer.      */
                               &ol_file_name,
                               &ol_file_name_length,
                               &ol_archive_name_length,
                               &ol_file_size,
                               &ol_unl,
                               &ol_size,
                               &ol_transfer_time,
                               &ol_output_type,
                               db.host_alias,
                               (current_toggle - 1),
                               WMO,
                               &db.output_log);
            }
         }
#endif

         /* Now archive file if necessary. */
         if ((db.archive_time > 0) &&
             (p_db->archive_dir[0] != FAILED_TO_CREATE_ARCHIVE_DIR))
         {
#ifdef WITH_ARCHIVE_COPY_INFO
            int ret;
#endif

            /*
             * By telling the function archive_file() that this
             * is the first time to archive a file for this job
             * (in struct p_db) it does not always have to check
             * whether the directory has been created or not. And
             * we ensure that we do not create duplicate names
             * when adding db.archive_time to msg_name.
             */
#ifdef WITH_ARCHIVE_COPY_INFO
            if ((ret = archive_file(file_path, p_file_name_buffer, p_db)) < 0)
#else
            if (archive_file(file_path, p_file_name_buffer, p_db) < 0)
#endif
            {
               if (fsa->debug > NORMAL_MODE)
               {
                  trans_db_log(ERROR_SIGN, __FILE__, __LINE__, NULL,
                               "Failed to archive file `%s'",
                               p_file_name_buffer);
               }

               /*
                * NOTE: We _MUST_ delete the file we just send,
                *       else the file directory will run full!
                */
               if (unlink(fullname) == -1)
               {
                  system_log(ERROR_SIGN, __FILE__, __LINE__,
                             "Could not unlink() local file `%s' after sending it successfully : %s",
                             fullname, strerror(errno));
               }

#ifdef _OUTPUT_LOG
               if (db.output_log == YES)
               {
                  (void)memcpy(ol_file_name, db.p_unique_name, db.unl);
                  (void)strcpy(ol_file_name + db.unl, p_file_name_buffer);
                  *ol_file_name_length = (unsigned short)strlen(ol_file_name);
                  ol_file_name[*ol_file_name_length] = SEPARATOR_CHAR;
                  ol_file_name[*ol_file_name_length + 1] = '\0';
                  (*ol_file_name_length)++;
                  *ol_file_size = *p_file_size_buffer;
                  *ol_job_number = fsa->job_status[(int)db.job_no].job_id;
                  *ol_retries = db.retries;
                  *ol_unl = db.unl;
                  *ol_transfer_time = end_time - start_time;
                  *ol_archive_name_length = 0;
                  *ol_output_type = OT_NORMAL_DELIVERED + '0';
                  ol_real_size = *ol_file_name_length + ol_size;
                  if (write(ol_fd, ol_data, ol_real_size) != ol_real_size)
                  {
                     system_log(ERROR_SIGN, __FILE__, __LINE__,
                                "write() error : %s", strerror(errno));
                  }
               }
#endif
            }
            else
            {
               if (fsa->debug > NORMAL_MODE)
               {
                  trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                               "Archived file `%s'", p_file_name_buffer);
               }
#ifdef WITH_ARCHIVE_COPY_INFO
               if (ret == DATA_COPIED) 
               {
                  archived_copied++;
               }
#endif

#ifdef _OUTPUT_LOG
               if (db.output_log == YES)
               {
                  (void)memcpy(ol_file_name, db.p_unique_name, db.unl);
                  (void)strcpy(ol_file_name + db.unl, p_file_name_buffer);
                  *ol_file_name_length = (unsigned short)strlen(ol_file_name);
                  ol_file_name[*ol_file_name_length] = SEPARATOR_CHAR;
                  ol_file_name[*ol_file_name_length + 1] = '\0';
                  (*ol_file_name_length)++;
                  (void)strcpy(&ol_file_name[*ol_file_name_length + 1],
                               &db.archive_dir[db.archive_offset]);
                  *ol_file_size = *p_file_size_buffer;
                  *ol_job_number = fsa->job_status[(int)db.job_no].job_id;
                  *ol_retries = db.retries;
                  *ol_unl = db.unl;
                  *ol_transfer_time = end_time - start_time;
                  *ol_archive_name_length = (unsigned short)strlen(&ol_file_name[*ol_file_name_length + 1]);
                  *ol_output_type = OT_NORMAL_DELIVERED + '0';
                  ol_real_size = *ol_file_name_length +
                                 *ol_archive_name_length + 1 + ol_size;
                  if (write(ol_fd, ol_data, ol_real_size) != ol_real_size)
                  {
                     system_log(ERROR_SIGN, __FILE__, __LINE__,
                                "write() error : %s", strerror(errno));
                  }
               }
#endif
            }
         }
         else
         {
#ifdef WITH_UNLINK_DELAY
            int unlink_loops = 0;

try_again_unlink:
#endif
            /* Delete the file we just have send. */
            if (unlink(fullname) == -1)
            {
#ifdef WITH_UNLINK_DELAY
               if ((errno == EBUSY) && (unlink_loops < 20))
               {
                  (void)my_usleep(100000L);
                  unlink_loops++;
                  goto try_again_unlink;
               }
#endif
               system_log(ERROR_SIGN, __FILE__, __LINE__,
                          "Could not unlink() local file %s after sending it successfully : %s",
                          fullname, strerror(errno));
            }

#ifdef _OUTPUT_LOG
            if (db.output_log == YES)
            {
               (void)memcpy(ol_file_name, db.p_unique_name, db.unl);
               (void)strcpy(ol_file_name + db.unl, p_file_name_buffer);
               *ol_file_name_length = (unsigned short)strlen(ol_file_name);
               ol_file_name[*ol_file_name_length] = SEPARATOR_CHAR;
               ol_file_name[*ol_file_name_length + 1] = '\0';
               (*ol_file_name_length)++;
               *ol_file_size = *p_file_size_buffer;
               *ol_job_number = fsa->job_status[(int)db.job_no].job_id;
               *ol_retries = db.retries;
               *ol_unl = db.unl;
               *ol_transfer_time = end_time - start_time;
               *ol_archive_name_length = 0;
               *ol_output_type = OT_NORMAL_DELIVERED + '0';
               ol_real_size = *ol_file_name_length + ol_size;
               if (write(ol_fd, ol_data, ol_real_size) != ol_real_size)
               {
                  system_log(ERROR_SIGN, __FILE__, __LINE__,
                             "write() error : %s", strerror(errno));
               }
            }
#endif
         }

         /*
          * After each successful transfer set error
          * counter to zero, so that other jobs can be
          * started.
          */
         if (gsf_check_fsa(p_db) != NEITHER)
         {
            if ((*p_file_size_buffer > 0) && (fsa->error_counter > 0))
            {
               int  fd,
#ifdef WITHOUT_FIFO_RW_SUPPORT
                    readfd,
#endif
                    j;
               char fd_wake_up_fifo[MAX_PATH_LENGTH];

#ifdef LOCK_DEBUG
               lock_region_w(fsa_fd, db.lock_offset + LOCK_EC, __FILE__, __LINE__);
#else
               lock_region_w(fsa_fd, db.lock_offset + LOCK_EC);
#endif
               fsa->error_counter = 0;

               /*
                * Wake up FD!
                */
               (void)snprintf(fd_wake_up_fifo, MAX_PATH_LENGTH, "%s%s%s",
                              p_work_dir, FIFO_DIR, FD_WAKE_UP_FIFO);
#ifdef WITHOUT_FIFO_RW_SUPPORT
               if (open_fifo_rw(fd_wake_up_fifo, &readfd, &fd) == -1)
#else
               if ((fd = open(fd_wake_up_fifo, O_RDWR)) == -1)
#endif
               {
                  system_log(WARN_SIGN, __FILE__, __LINE__,
                             "Failed to open() FIFO %s : %s",
                             fd_wake_up_fifo, strerror(errno));
               }
               else
               {
                  if (write(fd, "", 1) != 1)
                  {
                     system_log(WARN_SIGN, __FILE__, __LINE__,
                                "Failed to write() to FIFO %s : %s",
                                fd_wake_up_fifo, strerror(errno));
                  }
#ifdef WITHOUT_FIFO_RW_SUPPORT
                  if (close(readfd) == -1)
                  {
                     system_log(DEBUG_SIGN, __FILE__, __LINE__,
                                "Failed to close() FIFO %s (read) : %s",
                                fd_wake_up_fifo, strerror(errno));
                  }
#endif
                  if (close(fd) == -1)
                  {
                     system_log(DEBUG_SIGN, __FILE__, __LINE__,
                                "Failed to close() FIFO %s : %s",
                                fd_wake_up_fifo, strerror(errno));
                  }
               }

               /*
                * Remove the error condition (NOT_WORKING) from all jobs
                * of this host.
                */
               for (j = 0; j < fsa->allowed_transfers; j++)
               {
                  if ((j != db.job_no) &&
                      (fsa->job_status[j].connect_status == NOT_WORKING))
                  {
                     fsa->job_status[j].connect_status = DISCONNECT;
                  }
               }
               fsa->error_history[0] = 0;
               fsa->error_history[1] = 0;
#ifdef LOCK_DEBUG
               unlock_region(fsa_fd, db.lock_offset + LOCK_EC, __FILE__, __LINE__);
#else
               unlock_region(fsa_fd, db.lock_offset + LOCK_EC);
#endif

#ifdef LOCK_DEBUG
               lock_region_w(fsa_fd, db.lock_offset + LOCK_HS, __FILE__, __LINE__);
#else
               lock_region_w(fsa_fd, db.lock_offset + LOCK_HS);
#endif
               now = time(NULL);
               if (now > fsa->end_event_handle)
               {
                  fsa->host_status &= ~(EVENT_STATUS_FLAGS | AUTO_PAUSE_QUEUE_STAT);
                  if (fsa->end_event_handle > 0L)
                  {
                     fsa->end_event_handle = 0L;
                  }
                  if (fsa->start_event_handle > 0L)
                  {
                     fsa->start_event_handle = 0L;
                  }
               }
               else
               {
                  fsa->host_status &= ~(EVENT_STATUS_STATIC_FLAGS | AUTO_PAUSE_QUEUE_STAT);
               }
#ifdef LOCK_DEBUG
               unlock_region(fsa_fd, db.lock_offset + LOCK_HS, __FILE__, __LINE__);
#else
               unlock_region(fsa_fd, db.lock_offset + LOCK_HS);
#endif

               /*
                * Since we have successfully transmitted a file, no need to
                * have the queue stopped anymore.
                */
               if (fsa->host_status & AUTO_PAUSE_QUEUE_STAT)
               {
                  char sign[LOG_SIGN_LENGTH];

                  error_action(fsa->host_alias, "stop", HOST_ERROR_ACTION);
                  event_log(0L, EC_HOST, ET_EXT, EA_ERROR_END, "%s",
                            fsa->host_alias);
                  if ((fsa->host_status & HOST_ERROR_OFFLINE_STATIC) ||
                      (fsa->host_status & HOST_ERROR_OFFLINE) ||
                      (fsa->host_status & HOST_ERROR_OFFLINE_T))
                  {
                     (void)memcpy(sign, OFFLINE_SIGN, LOG_SIGN_LENGTH);
                  }
                  else
                  {
                     (void)memcpy(sign, INFO_SIGN, LOG_SIGN_LENGTH);
                  }
                  trans_log(sign, __FILE__, __LINE__, NULL, NULL,
                            "Starting input queue that was stopped by init_afd.");
                  event_log(0L, EC_HOST, ET_AUTO, EA_START_QUEUE, "%s",
                            fsa->host_alias);
               }
            } /* if (fsa->error_counter > 0) */
#ifdef WITH_ERROR_QUEUE
            if (fsa->host_status & ERROR_QUEUE_SET)
            {
               remove_from_error_queue(db.id.job, fsa, db.fsa_pos, fsa_fd);
            }
#endif
            if (fsa->host_status & HOST_ACTION_SUCCESS)
            {
               error_action(fsa->host_alias, "start", HOST_SUCCESS_ACTION);
            }
         }

         p_file_name_buffer += MAX_FILENAME_LENGTH;
         p_file_size_buffer++;
      } /* for (files_send = 0; files_send < files_to_send; files_send++) */

#ifdef WITH_ARCHIVE_COPY_INFO
      if (archived_copied > 0)
      {
         trans_log(DEBUG_SIGN, __FILE__, __LINE__, NULL, NULL,
                   "Copied %u files to archive.", archived_copied);
         archived_copied = 0;
      }
#endif

      if (local_file_counter)
      {
         if (gsf_check_fsa(p_db) != NEITHER)
         {
            update_tfc(local_file_counter, local_file_size,
                       p_file_size_buffer, files_to_send, files_send,
                       time(NULL));
            local_file_size = 0;
            local_file_counter = 0;
         }
      }

      /*
       * Remove file directory, but only when all files have
       * been transmitted.
       */
      if ((files_to_send == files_send) || (files_to_send < 1))
      {
         if (rmdir(file_path) < 0)
         {
            system_log(ERROR_SIGN, __FILE__, __LINE__,
                       "Failed to remove directory %s : %s",
                       file_path, strerror(errno));
         }
      }
      else
      {
         system_log(WARN_SIGN, __FILE__, __LINE__,
                    "There are still %d files for %s. Will NOT remove this job!",
                    files_to_send - files_send, file_path);
         exit_status = STILL_FILES_TO_SEND;
      }

#ifdef _WITH_BURST_2
      burst_2_counter++;
      diff_time = time(NULL) - connected;
      if (((fsa->protocol_options & KEEP_CONNECTED_DISCONNECT) &&
           (db.keep_connected > 0) && (diff_time > db.keep_connected)) ||
          ((db.disconnect > 0) && (diff_time > db.disconnect)))
      {
         cb2_ret = NO;
         break;
      }
   } while ((cb2_ret = check_burst_sf(file_path, &files_to_send, 0,
# ifdef _WITH_INTERRUPT_JOB
                                      0,
# endif
# ifdef _OUTPUT_LOG
                                      &ol_fd,
# endif
# ifndef AFDBENCH_CONFIG
                                      NULL,
# endif
                                      NULL)) == YES);
   burst_2_counter--;

   if (cb2_ret == NEITHER)
   {
      exit_status = STILL_FILES_TO_SEND;
   }
#endif /* _WITH_BURST_2 */

   free(buffer);

   /* Disconnect from remote port. */
   wmo_quit();
   if ((fsa != NULL) && (fsa->debug > NORMAL_MODE))
   {
      trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                   "Disconnected from port %d.", db.port);
   }

   if (wmo_counter_fd > 0)
   {
      close_counter_file(wmo_counter_fd, &wmo_counter);
   }

   exitflag = 0;
   exit(exit_status);
}
Ejemplo n.º 26
0
void PlayerInst::enqueue_io_actions(GameState* gs) {
	LANARTS_ASSERT(is_local_player() && gs->local_player() == this);

	if (actions_set_for_turn) {
		return;
	}

	bool single_player = (gs->player_data().all_players().size() <= 1);

	actions_set_for_turn = true;

	GameSettings& settings = gs->game_settings();
	GameView& view = gs->view();

	PlayerDataEntry& pde = gs->player_data().local_player_data();

	if (pde.action_queue.has_actions_for_frame(gs->frame())) {
		pde.action_queue.extract_actions_for_frame(queued_actions, gs->frame());
		event_log("Player %d has %d actions", player_entry(gs).net_id,
				(int) queued_actions.size());
		return;
	}
	if (!single_player) {
		gs->set_repeat_actions_counter(settings.frame_action_repeat);
	}

	int dx = 0, dy = 0;
	bool mouse_within = gs->mouse_x() < gs->view().width;
	int rmx = view.x + gs->mouse_x(), rmy = view.y + gs->mouse_y();

	bool was_moving = moving, do_stopaction = false;
	IOController& io = gs->io_controller();

	if (!settings.loadreplay_file.empty()) {
		load_actions(gs, queued_actions);
	}

	enqueue_io_movement_actions(gs, dx, dy);

	if (was_moving && !moving && cooldowns().can_do_stopaction()) {
		do_stopaction = true;
	}
//Shifting target
	if (gs->key_press_state(SDLK_k)) {
		shift_autotarget(gs);
	}

	if (gs->key_press_state(SDLK_m))
		spellselect = -1;

	bool attack_used = false;
	if (!gs->game_hud().handle_io(gs, queued_actions)) {
		attack_used = enqueue_io_spell_and_attack_actions(gs, dx, dy);
		enqueue_io_equipment_actions(gs, do_stopaction);
	}

	bool action_usage = io.query_event(IOEvent::ACTIVATE_SPELL_N)
			|| io.query_event(IOEvent::USE_WEAPON)
			|| io.query_event(IOEvent::AUTOTARGET_CURRENT_ACTION)
			|| io.query_event(IOEvent::MOUSETARGET_CURRENT_ACTION);
	if ((do_stopaction && !action_usage) || gs->key_down_state(SDLK_PERIOD)
			|| gs->mouse_downwheel()) {
		queue_portal_use(gs, this, queued_actions);
	}

// If we haven't done anything, rest
	if (queued_actions.empty()) {
		queued_actions.push_back(game_action(gs, this, GameAction::USE_REST));
	}

	ActionQueue only_passive_actions;

	for (int i = 0; i < queued_actions.size(); i++) {
		GameAction::action_t act = queued_actions[i].act;
		if (act == GameAction::MOVE || act == GameAction::USE_REST) {
			only_passive_actions.push_back(queued_actions[i]);
		}
	}

	GameNetConnection& net = gs->net_connection();
	if (net.is_connected()) {
		net_send_player_actions(net, gs->frame(),
				player_get_playernumber(gs, this), queued_actions);
	}

	int repeat = single_player ? 0 : settings.frame_action_repeat;
	for (int i = 1; i <= repeat; i++) {
		for (int j = 0; j < only_passive_actions.size(); j++) {
			only_passive_actions[j].frame = gs->frame() + i;
		}
		pde.action_queue.queue_actions_for_frame(only_passive_actions,
				gs->frame() + i);

		if (net.is_connected()) {
			net_send_player_actions(net, gs->frame() + i,
					player_get_playernumber(gs, this), only_passive_actions);
		}
	}

}
Ejemplo n.º 27
0
/**
 * Deletes a bundling instance
 *
 * @param Pointer which was returned by bu_new()
 */
void bu_delete(gpointer buPtr)
{
    event_log(INTERNAL_EVENT_0, "deleting bundling");
    free(buPtr);
}
Ejemplo n.º 28
0
/*########################### error_action() ############################*/
void
error_action(char *alias_name, char *action, int type)
{
   if (alias_name[0] == '\0')
   {
      system_log(DEBUG_SIGN, __FILE__, __LINE__,
                 _("No alias_name set. [action=`%s' type=%d]"), action, type);
   }
   else
   {
      int  default_action,
           event_action,
           event_class,
           status;
      char fullname[MAX_PATH_LENGTH],
           *p_alias_name;

      if (type == HOST_ERROR_ACTION)
      {
         p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                            "%s%s%s%s%s/",
                                            p_work_dir, ETC_DIR, ACTION_DIR,
                                            ACTION_TARGET_DIR,
                                            ACTION_ERROR_DIR);
         event_class = EC_HOST;
         if ((action[0] == 's') && (action[1] == 't') && (action[2] == 'a') &&
             (action[3] == 'r') && (action[4] == 't') && (action[5] == '\0'))
         {
            event_action = EA_EXEC_ERROR_ACTION_START;
         }
         else if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'o') && (action[3] == 'p') &&
                  (action[4] == '\0'))
              {
                 event_action = EA_EXEC_ERROR_ACTION_STOP;
              }
              else
              {
                 event_action = 0;
              }
      }
      else if (type == DIR_ERROR_ACTION)
           {
              p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                                 "%s%s%s%s%s/",
                                                 p_work_dir, ETC_DIR,
                                                 ACTION_DIR, ACTION_SOURCE_DIR,
                                                 ACTION_ERROR_DIR);
              event_class = EC_DIR;
              if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'a') && (action[3] == 'r') &&
                  (action[4] == 't') && (action[5] == '\0'))
              {
                 event_action = EA_EXEC_ERROR_ACTION_START;
              }
              else if ((action[0] == 's') && (action[1] == 't') &&
                       (action[2] == 'o') && (action[3] == 'p') &&
                       (action[4] == '\0'))
                   {
                      event_action = EA_EXEC_ERROR_ACTION_STOP;
                   }
                   else
                   {
                      event_action = 0;
                   }
           }
      else if (type == HOST_WARN_ACTION)
           {
              p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                                 "%s%s%s%s%s/",
                                                 p_work_dir, ETC_DIR,
                                                 ACTION_DIR, ACTION_TARGET_DIR,
                                                 ACTION_WARN_DIR);
              event_class = EC_HOST;
              if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'a') && (action[3] == 'r') &&
                  (action[4] == 't') && (action[5] == '\0'))
              {
                 event_action = EA_EXEC_WARN_ACTION_START;
              }
              else if ((action[0] == 's') && (action[1] == 't') &&
                       (action[2] == 'o') && (action[3] == 'p') &&
                       (action[4] == '\0'))
                   {
                      event_action = EA_EXEC_WARN_ACTION_STOP;
                   }
                   else
                   {
                      event_action = 0;
                   }
           }
      else if (type == DIR_INFO_ACTION)
           {
              p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                                 "%s%s%s%s%s/",
                                                 p_work_dir, ETC_DIR,
                                                 ACTION_DIR, ACTION_SOURCE_DIR,
                                                 ACTION_INFO_DIR);
              event_class = EC_DIR;
              if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'a') && (action[3] == 'r') &&
                  (action[4] == 't') && (action[5] == '\0'))
              {
                 event_action = EA_EXEC_INFO_ACTION_START;
              }
              else if ((action[0] == 's') && (action[1] == 't') &&
                       (action[2] == 'o') && (action[3] == 'p') &&
                       (action[4] == '\0'))
                   {
                      event_action = EA_EXEC_INFO_ACTION_STOP;
                   }
                   else
                   {
                      event_action = 0;
                   }
           }
      else if (type == DIR_WARN_ACTION)
           {
              p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                                 "%s%s%s%s%s/",
                                                 p_work_dir, ETC_DIR,
                                                 ACTION_DIR, ACTION_SOURCE_DIR,
                                                 ACTION_WARN_DIR);
              event_class = EC_DIR;
              if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'a') && (action[3] == 'r') &&
                  (action[4] == 't') && (action[5] == '\0'))
              {
                 event_action = EA_EXEC_WARN_ACTION_START;
              }
              else if ((action[0] == 's') && (action[1] == 't') &&
                       (action[2] == 'o') && (action[3] == 'p') &&
                       (action[4] == '\0'))
                   {
                      event_action = EA_EXEC_WARN_ACTION_STOP;
                   }
                   else
                   {
                      event_action = 0;
                   }
           }
      else if (type == HOST_SUCCESS_ACTION)
           {
              p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                                 "%s%s%s%s%s/",
                                                 p_work_dir, ETC_DIR,
                                                 ACTION_DIR, ACTION_TARGET_DIR,
                                                 ACTION_SUCCESS_DIR);
              event_class = EC_HOST;
              if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'a') && (action[3] == 'r') &&
                  (action[4] == 't') && (action[5] == '\0'))
              {
                 event_action = EA_EXEC_SUCCESS_ACTION_START;
              }
              else if ((action[0] == 's') && (action[1] == 't') &&
                       (action[2] == 'o') && (action[3] == 'p') &&
                       (action[4] == '\0'))
                   {
                      event_action = EA_EXEC_SUCCESS_ACTION_STOP;
                   }
                   else
                   {
                      event_action = 0;
                   }
           }
      else if (type == DIR_SUCCESS_ACTION)
           {
              p_alias_name = fullname + snprintf(fullname, MAX_PATH_LENGTH,
                                                 "%s%s%s%s%s/",
                                                 p_work_dir, ETC_DIR,
                                                 ACTION_DIR, ACTION_SOURCE_DIR,
                                                 ACTION_SUCCESS_DIR);
              event_class = EC_DIR;
              if ((action[0] == 's') && (action[1] == 't') &&
                  (action[2] == 'a') && (action[3] == 'r') &&
                  (action[4] == 't') && (action[5] == '\0'))
              {
                 event_action = EA_EXEC_SUCCESS_ACTION_START;
              }
              else if ((action[0] == 's') && (action[1] == 't') &&
                       (action[2] == 'o') && (action[3] == 'p') &&
                       (action[4] == '\0'))
                   {
                      event_action = EA_EXEC_SUCCESS_ACTION_STOP;
                   }
                   else
                   {
                      event_action = 0;
                   }
           }
           else
           {
              system_log(WARN_SIGN, __FILE__, __LINE__,
                         _("Unknown action type %d, please contact maintainer %s."),
                         type, AFD_MAINTAINER);
              return;
           }
      (void)strcpy(p_alias_name, alias_name);

      if ((status = eaccess(fullname, (R_OK | X_OK))) != 0)
      {
         default_action = YES;
         (void)strcpy(p_alias_name, DEFAULT_ACTION_FILE);
         status = eaccess(fullname, (R_OK | X_OK));
      }
      else
      {
         default_action = NO;
      }

      if (status == 0)
      {
         pid_t pid;
         char  reason_str[38 + MAX_INT_LENGTH + 1];

         if ((pid = fork()) < 0)
         {
            system_log(WARN_SIGN, __FILE__, __LINE__,
                       _("Could not create a new process : %s"),
                       strerror(errno));
            return;
         }
         else if (pid == 0) /* Child process. */
              {
                 int ret;

                 if ((pid = fork()) < 0)
                 {
                    system_log(WARN_SIGN, __FILE__, __LINE__,
                               _("Could not create a new process : %s"),
                               strerror(errno));
                    _exit(INCORRECT);
                 }
                 else if (pid > 0)
                      {
                         _exit(SUCCESS);
                      }

                 if (default_action == NO)
                 {
                    ret = execlp(fullname, fullname, action, (char *)0);
                 }
                 else
                 {
                    ret = execlp(fullname, fullname, action, alias_name,
                                 (char *)0);
                 }
                 if (ret < 0)
                 {
                    system_log(WARN_SIGN, __FILE__, __LINE__,
                               _("Failed to start process %s (%d) : %s [type=%d alias_name=`%s' action=`%s']"),
                               fullname, ret, strerror(errno), type, alias_name,
                               action);
                    _exit(INCORRECT);
                 }
                 else
                 {
                    system_log(DEBUG_SIGN, NULL, 0,
                               _("Error action: %s %s"), fullname, action);
                 }
                 _exit(SUCCESS);
              }

         if (waitpid(pid, &status, 0) != pid)
         {
            system_log(WARN_SIGN, __FILE__, __LINE__,
#if SIZEOF_PID_T == 4
                       "Failed to wait for pid %ld : %s",
#else
                       "Failed to wait for pid %lld : %s",
#endif
                       (pri_pid_t)pid, strerror(errno));
         }
         if (WIFEXITED(status))
         {
            (void)snprintf(reason_str, 38 + MAX_INT_LENGTH + 1, "%d",
                           WEXITSTATUS(status));
         }
         else if (WIFSIGNALED(status))
              {
                 (void)snprintf(reason_str, 38 + MAX_INT_LENGTH + 1,
                                _("Abnormal termination caused by signal %d"),
                                WTERMSIG(status));
              }
              else
              {
                 (void)my_strncpy(reason_str,
                                  _("Unable to determine return code"),
                                  38 + MAX_INT_LENGTH + 1);
              }

         if (event_action)
         {
            event_log(0L, event_class, ET_AUTO, event_action,
                      "%s%c%s", alias_name, SEPARATOR_CHAR, reason_str);
         }
      }
   }

   return;
}
Ejemplo n.º 29
0
Archivo: sf_exec.c Proyecto: hfs/afd
/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ main() $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
int
main(int argc, char *argv[])
{
#ifdef _WITH_BURST_2
   int              cb2_ret;
#endif
   int              exec_done,
                    exit_status = TRANSFER_SUCCESS,
                    ii,
                    k,
                    last_k,
                    length,
                    length_start,
                    mask_file_name,
#ifdef HAVE_SETPRIORITY
                    sched_priority,
#endif
                    ret;
   time_t           last_update_time,
                    now,
                    *p_file_mtime_buffer;
   char             command_str[MAX_PATH_LENGTH + MAX_RECIPIENT_LENGTH],
                    file_name[MAX_FILENAME_LENGTH],
                    file_path[MAX_PATH_LENGTH],
                    *fnp,
                    *insert_list[MAX_EXEC_FILE_SUBSTITUTION],
                    job_str[4],
                    *p_command,
                    *p_source_file,
                    *p_file_name_buffer,
                    *return_str = NULL,
                    source_file[MAX_PATH_LENGTH],
                    tmp_char,
                    tmp_option[MAX_PATH_LENGTH + MAX_RECIPIENT_LENGTH];
   struct job       *p_db;
#ifdef SA_FULLDUMP
   struct sigaction sact;
#endif
#ifdef WITH_FAST_MOVE
   nlink_t          nlink;
#endif
#ifdef _OUTPUT_LOG
   clock_t          end_time = 0,
                    start_time = 0;
   struct tms       tmsdummy;
#endif

   CHECK_FOR_VERSION(argc, argv);

#ifdef SA_FULLDUMP
   /*
    * When dumping core sure we do a FULL core dump!
    */
   sact.sa_handler = SIG_DFL;
   sact.sa_flags = SA_FULLDUMP;
   sigemptyset(&sact.sa_mask);
   if (sigaction(SIGSEGV, &sact, NULL) == -1)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "sigaction() error : %s", strerror(errno));
      exit(INCORRECT);
   }
#endif

   /* Do some cleanups when we exit. */
   if (atexit(sf_exec_exit) != 0)
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "Could not register exit function : %s", strerror(errno));
      exit(INCORRECT);
   }

   /* Initialise variables. */
   local_file_counter = 0;
   files_to_send = init_sf(argc, argv, file_path, EXEC_FLAG);
   p_db = &db;

   if ((signal(SIGINT, sig_kill) == SIG_ERR) ||
       (signal(SIGQUIT, sig_exit) == SIG_ERR) ||
       (signal(SIGTERM, sig_exit) == SIG_ERR) ||
       (signal(SIGSEGV, sig_segv) == SIG_ERR) ||
       (signal(SIGBUS, sig_bus) == SIG_ERR) ||
       (signal(SIGHUP, SIG_IGN) == SIG_ERR))
   {
      system_log(ERROR_SIGN, __FILE__, __LINE__,
                 "Failed to set signal handlers : %s", strerror(errno));
      exit(INCORRECT);
   }

   /* Inform FSA that we have are ready to copy the files. */
   if (gsf_check_fsa(p_db) != NEITHER)
   {
      fsa->job_status[(int)db.job_no].connect_status = EXEC_ACTIVE;
      fsa->job_status[(int)db.job_no].no_of_files = files_to_send;
   }

   /* Init job_str for exec_cmd(). */
   job_str[0] = '[';
   job_str[1] = db.job_no + '0';
   job_str[2] = ']';
   job_str[3] = '\0';

#ifdef _WITH_BURST_2
   do
   {
      if (burst_2_counter > 0)
      {
         if (fsa->debug > NORMAL_MODE)
         {
            trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL, "Bursting.");
         }
      }
#endif /* _WITH_BURST_2 */
      /* Prepare pointers and directory name. */
      (void)strcpy(source_file, file_path);
      p_source_file = source_file + strlen(source_file);
      *p_source_file++ = '/';

#ifdef HAVE_SETPRIORITY
      if (db.exec_base_priority != NO_PRIORITY)
      {
         sched_priority = db.exec_base_priority;
         if (db.add_afd_priority == YES)
         {
            sched_priority += (int)(fsa->job_status[(int)db.job_no].unique_name[MAX_MSG_NAME_LENGTH - 1]);
            if (sched_priority > db.min_sched_priority)
            {
               sched_priority = db.min_sched_priority;
            }
            else if (sched_priority < db.max_sched_priority)
                 {
                    sched_priority = db.max_sched_priority;
                 }
         }
         if ((sched_priority == db.current_priority) ||
             ((db.current_priority > sched_priority) && (geteuid() != 0)))
         {
            sched_priority = NO_PRIORITY;
         }
      }
      else
      {
         sched_priority = NO_PRIORITY;
      }
#endif

      p_command = db.exec_cmd;
      while ((*p_command == ' ') || (*p_command == '\t'))
      {
         p_command++;
      }
      if ((db.special_flag & EXEC_ONCE_ONLY) == 0)
      {
         char *p_end;

         /* Prepare insert list. */
         p_end = p_command;
         k = 0;
         ii = 0;
         while ((*p_end != '\0') && (ii < MAX_EXEC_FILE_SUBSTITUTION))
         {
            if ((*p_end == '%') && (*(p_end + 1) == 's'))
            {
               tmp_option[k] = *p_end;
               tmp_option[k + 1] = *(p_end + 1);
               insert_list[ii] = &tmp_option[k];
               ii++;
               p_end += 2;
               k += 2;
            }
            else
            {
               tmp_option[k] = *p_end;
               p_end++; k++;
            }
         }
         if (ii >= MAX_EXEC_FILE_SUBSTITUTION)
         {
            trans_log(WARN_SIGN, __FILE__, __LINE__, NULL, NULL,
                      "To many %%s in pexec option. Can oly handle %d.",
                      MAX_EXEC_FILE_SUBSTITUTION);
         }
         tmp_option[k] = '\0';
         p_command = tmp_option;
         last_k = k;
      }

      p_file_name_buffer = file_name_buffer;
      p_file_size_buffer = file_size_buffer;
      p_file_mtime_buffer = file_mtime_buffer;
      last_update_time = time(NULL);
      local_file_size = 0;
      exec_done = NO;
      for (files_send = 0; files_send < files_to_send; files_send++)
      {
         (void)strcpy(p_source_file, p_file_name_buffer);

         if (db.special_flag & EXEC_ONCE_ONLY)
         {
            if (exec_done == NO)
            {
#ifdef _OUTPUT_LOG
               if (db.output_log == YES)
               {
                  start_time = times(&tmsdummy);
               }
#endif
               (void)sprintf(command_str, "cd %s && %s",
                             file_path, p_command);
               if (fsa->debug > NORMAL_MODE)
               {
                  trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                               "Executing command `%s' to send file `%s'",
                               command_str, p_file_name_buffer);
               }
               if ((ret = exec_cmd(command_str, &return_str, transfer_log_fd,
                                   fsa->host_dsp_name, MAX_HOSTNAME_LENGTH,
#ifdef HAVE_SETPRIORITY
                                   sched_priority,
#endif
                                   job_str,
                                   (fsa->protocol_options & TIMEOUT_TRANSFER) ? (time_t)transfer_timeout : 0L,
                                   YES, YES)) != 0)
               {
                  trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                            "Failed to execute command %s [Return code = %d]",
                            command_str, ret);
                  if ((return_str != NULL) && (return_str[0] != '\0'))
                  {
                     char *end_ptr = return_str,
                          *start_ptr;

                     do
                     {
                        start_ptr = end_ptr;
                        while ((*end_ptr != '\n') && (*end_ptr != '\0'))
                        {
                           end_ptr++;
                        }
                        if (*end_ptr == '\n')
                        {
                           *end_ptr = '\0';
                           end_ptr++;
                        }
                        trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                                  "%s", start_ptr);
                     } while (*end_ptr != '\0');
                  }
                  exit(EXEC_ERROR);
               }
#ifdef _OUTPUT_LOG
               if (db.output_log == YES)
               {
                  end_time = times(&tmsdummy);
               }
#endif
               free(return_str);
               return_str = NULL;
               exec_done = YES;
            }
         }
         else
         {
            /* Write status to FSA? */
            if (gsf_check_fsa(p_db) != NEITHER)
            {
               fsa->job_status[(int)db.job_no].file_size_in_use = *p_file_size_buffer;
               (void)strcpy(fsa->job_status[(int)db.job_no].file_name_in_use,
                            p_file_name_buffer);
            }

#ifdef _OUTPUT_LOG
            if (db.output_log == YES)
            {
               start_time = times(&tmsdummy);
            }
#endif

            insert_list[ii] = &tmp_option[last_k];
            tmp_char = *insert_list[0];
            *insert_list[0] = '\0';
            length_start = sprintf(command_str, "cd %s && %s",
                                   file_path, p_command);
            *insert_list[0] = tmp_char;

            fnp = p_file_name_buffer;
            mask_file_name = NO;
            do
            {
               if ((*fnp == ';') || (*fnp == ' '))
               {
                  mask_file_name = YES;
                  break;
               }
               fnp++;
            } while (*fnp != '\0');

            /* Generate command string with file name(s). */
            length = 0;
            for (k = 1; k < (ii + 1); k++)
            {
               tmp_char = *insert_list[k];
               *insert_list[k] = '\0';
               if (mask_file_name == YES)
               {
                  length += sprintf(command_str + length_start + length,
                                    "\"%s\"%s", p_file_name_buffer,
                                    insert_list[k - 1] + 2);
               }
               else
               {
                  length += sprintf(command_str + length_start + length,
                                    "%s%s", p_file_name_buffer,
                                    insert_list[k - 1] + 2);
               }
               *insert_list[k] = tmp_char;
            }

            if ((ret = exec_cmd(command_str, &return_str, transfer_log_fd,
                                fsa->host_dsp_name, MAX_HOSTNAME_LENGTH,
#ifdef HAVE_SETPRIORITY
                                sched_priority,
#endif
                                job_str,
                                (fsa->protocol_options & TIMEOUT_TRANSFER) ? (time_t)transfer_timeout : 0L,
                                YES, YES)) != 0) /* ie != SUCCESS */
            {
               trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                         "Failed to execute command %s [Return code = %d]",
                         command_str, ret);
               if ((return_str != NULL) && (return_str[0] != '\0'))
               {
                  char *end_ptr = return_str,
                       *start_ptr;

                  do
                  {
                     start_ptr = end_ptr;
                     while ((*end_ptr != '\n') && (*end_ptr != '\0'))
                     {
                        end_ptr++;
                     }
                     if (*end_ptr == '\n')
                     {
                        *end_ptr = '\0';
                        end_ptr++;
                     }
                     trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                               "%s", start_ptr);
                  } while (*end_ptr != '\0');
               }
               exit(EXEC_ERROR);
            }
            free(return_str);
            return_str = NULL;

#ifdef _OUTPUT_LOG
            if (db.output_log == YES)
            {
               end_time = times(&tmsdummy);
            }
#endif
         }

         /* Tell FSA we have done a file. */
         if (gsf_check_fsa(p_db) != NEITHER)
         {
            fsa->job_status[(int)db.job_no].file_name_in_use[0] = '\0';
            fsa->job_status[(int)db.job_no].no_of_files_done++;
            fsa->job_status[(int)db.job_no].file_size_in_use = 0;
            fsa->job_status[(int)db.job_no].file_size_in_use_done = 0;
            fsa->job_status[(int)db.job_no].file_size_done += *p_file_size_buffer;
            fsa->job_status[(int)db.job_no].bytes_send += *p_file_size_buffer;
            local_file_size += *p_file_size_buffer;
            local_file_counter += 1;

            now = time(NULL);
            if (now >= (last_update_time + LOCK_INTERVAL_TIME))
            {
               last_update_time = now;
               update_tfc(local_file_counter, local_file_size,
                          p_file_size_buffer, files_to_send, files_send);
               local_file_size = 0;
               local_file_counter = 0;
            }
         }

#ifdef _WITH_TRANS_EXEC
         if (db.special_flag & TRANS_EXEC)
         {
            trans_exec(file_path, source_file, p_file_name_buffer);
         }
#endif

#ifdef _OUTPUT_LOG
         if (db.output_log == YES)
         {
            if (ol_fd == -2)
            {
# ifdef WITHOUT_FIFO_RW_SUPPORT
               output_log_fd(&ol_fd, &ol_readfd);
# else
               output_log_fd(&ol_fd);
# endif
            }
            if ((ol_fd > -1) && (ol_data == NULL))
            {
               output_log_ptrs(&ol_retries, &ol_job_number, &ol_data,
                               &ol_file_name, &ol_file_name_length,
                               &ol_archive_name_length, &ol_file_size,
                               &ol_unl, &ol_size, &ol_transfer_time,
                               &ol_output_type, db.host_alias, 0, EXEC);
            }
         }
#endif

         /* Now archive file if necessary. */
         if ((db.archive_time > 0) &&
             (p_db->archive_dir[0] != FAILED_TO_CREATE_ARCHIVE_DIR))
         {
            /*
             * By telling the function archive_file() that this
             * is the first time to archive a file for this job
             * (in struct p_db) it does not always have to check
             * whether the directory has been created or not. And
             * we ensure that we do not create duplicate names
             * when adding db.archive_time to msg_name.
             */
            if (archive_file(file_path, p_file_name_buffer, p_db) < 0)
            {
               trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                         "Failed to archive file `%s'", file_name);

               /*
                * NOTE: We _MUST_ delete the file we just send,
                *       else the file directory will run full!
                */
               if (unlink(source_file) == -1)
               {
                  system_log(ERROR_SIGN, __FILE__, __LINE__,
                             "Could not unlink() local file `%s' after copying it successfully : %s",
                             source_file, strerror(errno));
               }

#ifdef _OUTPUT_LOG
               if (db.output_log == YES)
               {
                  (void)memcpy(ol_file_name, db.p_unique_name, db.unl);
                  if (db.trans_rename_rule[0] != '\0')
                  {
                     *ol_file_name_length = (unsigned short)sprintf(ol_file_name + db.unl,
                                                                    "%s%c/%s",
                                                                    p_file_name_buffer,
                                                                    SEPARATOR_CHAR,
                                                                    p_file_name_buffer) +
                                                                    db.unl;
                  }
                  else
                  {
                     (void)strcpy(ol_file_name + db.unl, p_file_name_buffer);
                     *ol_file_name_length = (unsigned short)strlen(ol_file_name);
                     ol_file_name[*ol_file_name_length] = SEPARATOR_CHAR;
                     ol_file_name[*ol_file_name_length + 1] = '\0';
                     (*ol_file_name_length)++;
                  }
                  *ol_file_size = *p_file_size_buffer;
                  *ol_job_number = fsa->job_status[(int)db.job_no].job_id;
                  *ol_retries = db.retries;
                  *ol_unl = db.unl;
                  *ol_transfer_time = end_time - start_time;
                  *ol_archive_name_length = 0;
                  *ol_output_type = OT_NORMAL_DELIVERED + '0';
                  ol_real_size = *ol_file_name_length + ol_size;
                  if (write(ol_fd, ol_data, ol_real_size) != ol_real_size)
                  {
                     system_log(ERROR_SIGN, __FILE__, __LINE__,
                                "write() error : %s", strerror(errno));
                  }
               }
#endif
            }
            else
            {
               if (fsa->debug > NORMAL_MODE)
               {
                  trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                               "Archived file `%s'.", file_name);
               }

#ifdef _OUTPUT_LOG
               if (db.output_log == YES)
               {
                  (void)memcpy(ol_file_name, db.p_unique_name, db.unl);
                  if (db.trans_rename_rule[0] != '\0')
                  {
                     *ol_file_name_length = (unsigned short)sprintf(ol_file_name + db.unl,
                                                                    "%s%c/%s",
                                                                    p_file_name_buffer,
                                                                    SEPARATOR_CHAR,
                                                                    p_file_name_buffer) +
                                                                    db.unl;
                  }
                  else
                  {
                     (void)strcpy(ol_file_name + db.unl, p_file_name_buffer);
                     *ol_file_name_length = (unsigned short)strlen(ol_file_name);
                     ol_file_name[*ol_file_name_length] = SEPARATOR_CHAR;
                     ol_file_name[*ol_file_name_length + 1] = '\0';
                     (*ol_file_name_length)++;
                  }
                  (void)strcpy(&ol_file_name[*ol_file_name_length + 1], &db.archive_dir[db.archive_offset]);
                  *ol_file_size = *p_file_size_buffer;
                  *ol_job_number = fsa->job_status[(int)db.job_no].job_id;
                  *ol_retries = db.retries;
                  *ol_unl = db.unl;
                  *ol_transfer_time = end_time - start_time;
                  *ol_archive_name_length = (unsigned short)strlen(&ol_file_name[*ol_file_name_length + 1]);
                  *ol_output_type = OT_NORMAL_DELIVERED + '0';
                  ol_real_size = *ol_file_name_length +
                                 *ol_archive_name_length + 1 + ol_size;
                  if (write(ol_fd, ol_data, ol_real_size) != ol_real_size)
                  {
                     system_log(ERROR_SIGN, __FILE__, __LINE__,
                                "write() error : %s", strerror(errno));
                  }
               }
#endif
            }
         }
         else
         {
#ifdef WITH_UNLINK_DELAY
            int unlink_loops = 0;

try_again_unlink:
#endif
            /* Delete the file we just have executed. */
            if (unlink(source_file) == -1)
            {
#ifdef WITH_UNLINK_DELAY
               if ((errno == EBUSY) && (unlink_loops < 20))
               {
                  (void)my_usleep(100000L);
                  unlink_loops++;
                  goto try_again_unlink;
               }
#endif
               system_log(ERROR_SIGN, __FILE__, __LINE__,
                          "Could not unlink() local file %s after copying it successfully : %s",
                          source_file, strerror(errno));
            }

#ifdef _OUTPUT_LOG
            if (db.output_log == YES)
            {
               (void)memcpy(ol_file_name, db.p_unique_name, db.unl);
               if (db.trans_rename_rule[0] != '\0')
               {
                  *ol_file_name_length = (unsigned short)sprintf(ol_file_name + db.unl,
                                                                 "%s%c/%s",
                                                                 p_file_name_buffer,
                                                                 SEPARATOR_CHAR,
                                                                 p_file_name_buffer) +
                                                                 db.unl;
               }
               else
               {
                  (void)strcpy(ol_file_name + db.unl, p_file_name_buffer);
                  *ol_file_name_length = (unsigned short)strlen(ol_file_name);
                  ol_file_name[*ol_file_name_length] = SEPARATOR_CHAR;
                  ol_file_name[*ol_file_name_length + 1] = '\0';
                  (*ol_file_name_length)++;
               }
               *ol_file_size = *p_file_size_buffer;
               *ol_job_number = fsa->job_status[(int)db.job_no].job_id;
               *ol_retries = db.retries;
               *ol_unl = db.unl;
               *ol_transfer_time = end_time - start_time;
               *ol_archive_name_length = 0;
               *ol_output_type = OT_NORMAL_DELIVERED + '0';
               ol_real_size = *ol_file_name_length + ol_size;
               if (write(ol_fd, ol_data, ol_real_size) != ol_real_size)
               {
                  system_log(ERROR_SIGN, __FILE__, __LINE__,
                             "write() error : %s", strerror(errno));
               }
            }
#endif
         }

         /*
          * After each successful transfer set error counter to zero,
          * so that other jobs can be started.
          */
         if (fsa->error_counter > 0)
         {
            int  fd,
#ifdef WITHOUT_FIFO_RW_SUPPORT
                 readfd,
#endif
                 j;
            char fd_wake_up_fifo[MAX_PATH_LENGTH];

#ifdef LOCK_DEBUG
            lock_region_w(fsa_fd, db.lock_offset + LOCK_EC, __FILE__, __LINE__);
#else
            lock_region_w(fsa_fd, db.lock_offset + LOCK_EC);
#endif
            fsa->error_counter = 0;

            /*
             * Wake up FD!
             */
            (void)sprintf(fd_wake_up_fifo, "%s%s%s",
                          p_work_dir, FIFO_DIR, FD_WAKE_UP_FIFO);
#ifdef WITHOUT_FIFO_RW_SUPPORT
            if (open_fifo_rw(fd_wake_up_fifo, &readfd, &fd) == -1)
#else
            if ((fd = open(fd_wake_up_fifo, O_RDWR)) == -1)
#endif
            {
               system_log(WARN_SIGN, __FILE__, __LINE__,
                          "Failed to open() FIFO %s : %s",
                          fd_wake_up_fifo, strerror(errno));
            }
            else
            {
               if (write(fd, "", 1) != 1)
               {
                  system_log(WARN_SIGN, __FILE__, __LINE__,
                             "Failed to write() to FIFO %s : %s",
                             fd_wake_up_fifo, strerror(errno));
               }
#ifdef WITHOUT_FIFO_RW_SUPPORT
               if (close(readfd) == -1)
               {
                  system_log(DEBUG_SIGN, __FILE__, __LINE__,
                             "Failed to close() FIFO %s : %s",
                             fd_wake_up_fifo, strerror(errno));
               }
#endif
               if (close(fd) == -1)
               {
                  system_log(DEBUG_SIGN, __FILE__, __LINE__,
                             "Failed to close() FIFO %s : %s",
                             fd_wake_up_fifo, strerror(errno));
               }
            }

            /*
             * Remove the error condition (NOT_WORKING) from all jobs
             * of this host.
             */
            for (j = 0; j < fsa->allowed_transfers; j++)
            {
               if ((j != db.job_no) &&
                   (fsa->job_status[j].connect_status == NOT_WORKING))
               {
                  fsa->job_status[j].connect_status = DISCONNECT;
               }
            }
            fsa->error_history[0] = 0;
            fsa->error_history[1] = 0;
#ifdef LOCK_DEBUG
            unlock_region(fsa_fd, db.lock_offset + LOCK_EC, __FILE__, __LINE__);
#else
            unlock_region(fsa_fd, db.lock_offset + LOCK_EC);
#endif

            /*
             * Since we have successfully transmitted a file, no need to
             * have the queue stopped anymore.
             */
            if (fsa->host_status & AUTO_PAUSE_QUEUE_STAT)
            {
               char *sign;

#ifdef LOCK_DEBUG
               lock_region_w(fsa_fd, db.lock_offset + LOCK_HS, __FILE__, __LINE__);
#else
               lock_region_w(fsa_fd, db.lock_offset + LOCK_HS);
#endif
               fsa->host_status &= ~AUTO_PAUSE_QUEUE_STAT;
               if (fsa->host_status & HOST_ERROR_EA_STATIC)
               {
                  fsa->host_status &= ~EVENT_STATUS_STATIC_FLAGS;
               }
               else
               {
                  fsa->host_status &= ~EVENT_STATUS_FLAGS;
               }
               fsa->host_status &= ~PENDING_ERRORS;
#ifdef LOCK_DEBUG
               unlock_region(fsa_fd, db.lock_offset + LOCK_HS, __FILE__, __LINE__);
#else
               unlock_region(fsa_fd, db.lock_offset + LOCK_HS);
#endif
               error_action(fsa->host_alias, "stop", HOST_ERROR_ACTION);
               event_log(0L, EC_HOST, ET_EXT, EA_ERROR_END, "%s",
                         fsa->host_alias);
               if ((fsa->host_status & HOST_ERROR_OFFLINE_STATIC) ||
                   (fsa->host_status & HOST_ERROR_OFFLINE) ||
                   (fsa->host_status & HOST_ERROR_OFFLINE_T))
               {
                  sign = OFFLINE_SIGN;
               }
               else
               {
                  sign = INFO_SIGN;
               }
               trans_log(sign, __FILE__, __LINE__, NULL, NULL,
                         "Starting input queue that was stopped by init_afd.");
               event_log(0L, EC_HOST, ET_AUTO, EA_START_QUEUE, "%s",
                         fsa->host_alias);
            }
         } /* if (fsa->error_counter > 0) */
#ifdef WITH_ERROR_QUEUE
         if (fsa->host_status & ERROR_QUEUE_SET)
         {
            remove_from_error_queue(db.job_id, fsa, db.fsa_pos, fsa_fd);
         }
#endif
         if (fsa->host_status & HOST_ACTION_SUCCESS)
         {
            error_action(fsa->host_alias, "start", HOST_SUCCESS_ACTION);
         }

         p_file_name_buffer += MAX_FILENAME_LENGTH;
         p_file_size_buffer++;
         if (file_mtime_buffer != NULL)
         {
            p_file_mtime_buffer++;
         }
      } /* for (files_send = 0; files_send < files_to_send; files_send++) */

      if (local_file_counter)
      {
         if (gsf_check_fsa(p_db) != NEITHER)
         {
            update_tfc(local_file_counter, local_file_size,
                       p_file_size_buffer, files_to_send, files_send);
            local_file_size = 0;
            local_file_counter = 0;
         }
      }

      /* Do not forget to remove lock file if we have created one. */
      if ((db.lock == LOCKFILE) && (fsa->active_transfers == 1))
      {
         if (unlink(db.lock_file_name) == -1)
         {
            trans_log(ERROR_SIGN, __FILE__, __LINE__, NULL, NULL,
                      "Failed to unlink() lock file `%s' : %s",
                      db.lock_file_name, strerror(errno));
            exit(REMOVE_LOCKFILE_ERROR);
         }
         else
         {
            if (fsa->debug > NORMAL_MODE)
            {
               trans_db_log(INFO_SIGN, __FILE__, __LINE__, NULL,
                            "Removed lock file `%s'.", db.lock_file_name);
            }
         }
      }

      /*
       * Remove file directory with everything in it.
       */
      if (rec_rmdir(file_path) == INCORRECT)
      {
         system_log(ERROR_SIGN, __FILE__, __LINE__,
                    "Failed to rec_rmdir() `%s' : %s",
                    file_path, strerror(errno));
         exit_status = STILL_FILES_TO_SEND;
      }

#ifdef _WITH_BURST_2
      burst_2_counter++;
   } while ((cb2_ret = check_burst_2(file_path, &files_to_send, 0,
# ifdef _WITH_INTERRUPT_JOB
                                     0,
# endif
# ifdef _OUTPUT_LOG
                                     &ol_fd,
# endif
# ifndef AFDBENCH_CONFIG
                                     NULL,
# endif
                                     NULL)) == YES);
   burst_2_counter--;

   if (cb2_ret == NEITHER)
   {
      exit_status = STILL_FILES_TO_SEND;
   }
#endif /* _WITH_BURST_2 */

   exitflag = 0;
   exit(exit_status);
}
Ejemplo n.º 30
0
/**
 * Disassembles chunks from a received datagram
 *
 * FIXME : data chunks may only be parsed after control chunks.....
 *
 * All chunks within the datagram are dispatched and sent to the appropriate
 * module, i.e.: control chunks are sent to sctp_control/pathmanagement,
 * SACK chunks to reliable_transfer, and data_chunks to RX_control.
 * Those modules must get a pointer to the start of a chunk and
 * information about its size (without padding).
 * @param  address_index  index of address on which this data arrived
 * @param  datagram     pointer to first chunk of the newly received data
 * @param  len          length of payload (i.e. len of the concatenation of chunks)
 */
gint rbu_rcvDatagram(guint address_index, guchar * datagram, guint len)
{
    /* sctp common header header has been verified */
    /* tag (if association is established) and CRC is okay */
    /* get first chunk-id and length, pass pointers & len on to relevant module :
       - CHUNK_INIT, CHUNK_INIT_ACK,CHUNK_ABORT, CHUNK_SHUTDOWN,CHUNK_SHUTDOWN_ACK
       CHUNK_COOKIE_ECHO,CHUNK_COOKIE_ACK go to SCTP_CONTROL (change of association state)
       - CHUNK_HBREQ, CHUNK_HBACK go to PATH_MAN instance
       - CHUNK_SACK goes to RELIABLE_TRANSFER
       - CHUNK_ERROR probably to SCTP_CONTROL as well  (at least there !)
       - CHUNK_DATA goes to RX_CONTROL
     */
    guchar *current_position;
    gushort processed_len = 0, chunk_len;
    gushort pad_bytes;
    SCTP_simple_chunk *chunk;
    gboolean data_chunk_received = FALSE;

    int association_state = STATE_OK;
    gboolean send_it = FALSE;

    bu_lock_sender();

    current_position = datagram; /* points to the first chunk in this pdu */
    event_log(INTERNAL_EVENT_0, "Entered rbu_rcvDatagram()...... ");
    /* CHECKME : beim Empfangen leerer Chunks tritt im Bundling eine Endlosschleife auf ??? */
    while (processed_len < len) {

        chunk = (SCTP_simple_chunk *) current_position;
        chunk_len = CHUNKP_LENGTH((SCTP_chunk_header *) chunk);
        event_logiiii(INTERNAL_EVENT_0,
                     "rbu_rcvDatagram(address=%u) : len==%u, processed_len = %u, chunk_len=%u",
                     address_index, len, processed_len, chunk_len);
        if ((processed_len+chunk_len) > len || chunk_len < 4) {
            error_logiii(ERROR_MINOR, "Faulty chunklen=%u, total len=%u,processed_len=%u --> dropping packet  !",
                                    chunk_len,len,processed_len);
            /* if the association has already been removed, we cannot unlock it anymore */
            bu_unlock_sender(&address_index);
            return 1;
        }
        /*
         * TODO :   Add return values to the chunk-functions, where they can indicate what
         *          to do with the rest of the datagram (i.e. DISCARD after stale COOKIE_ECHO
         *          with tie tags that do not match the current ones)
         */
        switch (chunk->chunk_header.chunk_id) {
        case CHUNK_DATA:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received DATA chunk");
            rxc_data_chunk_rx((SCTP_data_chunk*) chunk, address_index);
            data_chunk_received = TRUE;
            break;
        case CHUNK_INIT:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received INIT chunk");
            association_state = sctlr_init((SCTP_init *) chunk);
            break;
        case CHUNK_INIT_ACK:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received INIT ACK chunk");
            association_state = sctlr_initAck((SCTP_init *) chunk);
            break;
        case CHUNK_SACK:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received SACK chunk");
            rtx_process_sack(address_index, chunk, len);
            break;
        case CHUNK_HBREQ:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received HB_REQ chunk");
            pm_heartbeat((SCTP_heartbeat *) chunk, address_index);
            break;
        case CHUNK_HBACK:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received HB_ACK chunk");
            pm_heartbeatAck((SCTP_heartbeat *) chunk);
            break;
        case CHUNK_ABORT:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received ABORT chunk");
            association_state = sctlr_abort();
            break;
        case CHUNK_SHUTDOWN:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received SHUTDOWN chunk");
            association_state = sctlr_shutdown((SCTP_simple_chunk *) chunk);
            break;
        case CHUNK_SHUTDOWN_ACK:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received SHUTDOWN ACK chunk");
            association_state = sctlr_shutdownAck();
            break;
        case CHUNK_ERROR:
            event_log(INTERNAL_EVENT_0, "Error Chunk");
            eh_recv_chunk(chunk);
            break;
        case CHUNK_COOKIE_ECHO:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received COOKIE ECHO chunk");
            sctlr_cookie_echo((SCTP_cookie_echo *) chunk);
            break;
        case CHUNK_COOKIE_ACK:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received COOKIE ACK chunk");
            sctlr_cookieAck((SCTP_simple_chunk *) chunk);
            break;
     /* case CHUNK_ECNE:
        case CHUNK_CWR:
            event_logi(INTERNAL_EVENT_0,
                       "Chunktype %u not Supported Yet !!!!!!!!", chunk->chunk_header.chunk_id);
            break;*/
        case CHUNK_SHUTDOWN_COMPLETE:
            event_log(INTERNAL_EVENT_0, "*******************  Bundling received SHUTDOWN_COMPLETE chunk");
            association_state = sctlr_shutdownComplete();
            break;
        case CHUNK_FORWARD_TSN:
            if (mdi_supportsPRSCTP() == TRUE) {
                event_log(INTERNAL_EVENT_0, "*******************  Bundling received FORWARD_TSN chunk");
                rxc_process_forward_tsn((SCTP_simple_chunk *) chunk);
                break;
            } else
                continue;
    /*    case CHUNK_ASCONF: */
            /* check that ASCONF chunks are standalone chunks, not bundled with any other
               chunks. Else ignore the ASCONF chunk (but not the others) */
/*            event_log(INTERNAL_EVENT_0, "Bundling received ASCONF chunk");
            asc_recv_asconf_chunk((SCTP_simple_chunk *) chunk);
            break;
        case CHUNK_ASCONF_ACK:
            event_log(INTERNAL_EVENT_0, "Bundling received ASCONF_ACK chunk");
            asc_recv_asconf_ack((SCTP_simple_chunk *) chunk);
            break; */
        default:
        /* 00 - Stop processing this SCTP packet and discard it, do not process
                any further chunks within it.
           01 - Stop processing this SCTP packet and discard it, do not process
                any further chunks within it, and report the unrecognized
                parameter in an 'Unrecognized Parameter Type' (in either an
                ERROR or in the INIT ACK).
           10 - Skip this chunk and continue processing.
           11 - Skip this chunk and continue processing, but report in an ERROR
                Chunk using the 'Unrecognized Chunk Type' cause of error. */
            if ((chunk->chunk_header.chunk_id & 0xC0) == 0x0) {            /* 00 */
                processed_len = len;
                event_logi(EXTERNAL_EVENT_X, "00: Unknown chunktype %u in rbundling.c", chunk->chunk_header.chunk_id);
            } else if ((chunk->chunk_header.chunk_id & 0xC0) == 0x40) {    /* 01 */
                processed_len = len;
                eh_send_unrecognized_chunktype((unsigned char*)chunk,chunk_len);
                event_logi(EXTERNAL_EVENT_X, "01: Unknown chunktype %u in rbundling.c",chunk->chunk_header.chunk_id);
            } else if ((chunk->chunk_header.chunk_id & 0xC0) == 0x80) {    /* 10 */
                /* nothing */
                event_logi(EXTERNAL_EVENT_X, "10: Unknown chunktype %u in rbundling.c",chunk->chunk_header.chunk_id);
            } else if ((chunk->chunk_header.chunk_id & 0xC0) == 0xC0) {    /* 11 */
                event_logi(EXTERNAL_EVENT_X, "11: Unknown chunktype %u in rbundling.c", chunk->chunk_header.chunk_id);
                eh_send_unrecognized_chunktype((unsigned char*)chunk,chunk_len);
            }
            break;
        }

        processed_len += chunk_len;
        pad_bytes = ((processed_len % 4) == 0) ? 0 : (4 - processed_len % 4);
        processed_len += pad_bytes;
        current_position += (chunk_len + pad_bytes) * sizeof(unsigned char);

        if (association_state != STATE_OK) processed_len = len;

        event_logiiii(VVERBOSE, "processed_len=%u, pad_bytes=%u, current_position=%u, chunk_len=%u",
            processed_len, pad_bytes, current_position,chunk_len);
    }

    if (association_state != STATE_STOP_PARSING_REMOVED) {

        if (data_chunk_received == TRUE) {
            /* update SACK structure and start SACK timer */
            rxc_all_chunks_processed(TRUE);
        } else {
            /* update SACK structure and datagram counter */
            rxc_all_chunks_processed(FALSE);
        }
        /* optionally also add a SACK chunk, at least for every second datagram
         * see section 6.2, second paragraph
         */
        if (data_chunk_received == TRUE){
            send_it = rxc_create_sack(&address_index, FALSE);
            se_doNotifications();
            if (send_it==TRUE) bu_sendAllChunks(&address_index);
        }
        /* if the association has already been removed, we cannot unlock it anymore */
        bu_unlock_sender(&address_index);
    }

    return 0;

}