Exemple #1
0
void pbfilter_base::setblock(bool block)
{
	TRACEV("[pbfilter_base] [setblock]  > Entering routine.");
	TRACEI("[pbfilter_base] [setblock]    acquiring lock");
	mutex::scoped_lock lock(m_blocklock);

	if(block != m_block)
	{
		if (block)
			TRACEI("[pbfilter_base] [setblock]    resetting m_block to: [true]")
		else
			TRACEI("[pbfilter_base] [setblock]    resetting m_block to: [false]");

		m_block = block;
		int data = block ? 1 : 0;

		TRACEI("[pbfilter_base] [setblock]    sending block request to driver...")
		DWORD ret = m_filter.write(IOCTL_PEERBLOCK_HOOK, &data, sizeof(data));
		TRACEI("[pbfilter_base] [setblock]    ...block request sent")
		if(ret != ERROR_SUCCESS)
		{
			TRACEERR("[pbfilter_base] [setblock]", L"sending block request to driver", ret);
			throw win32_error("DeviceIoControl", ret);
		}
	}
	else
	{
Exemple #2
0
uint8_t * get_afu_psa_addr(char * i_afu_path) {
    /*------------------------------------------------------------------------*/
    /*  Local Variables                                                       */
    /*------------------------------------------------------------------------*/
    struct cxl_afu_h * afu_master_h = NULL;
    int afu_master_fd = 0;
    uint8_t * afu_psa_addr = NULL;

    /*------------------------------------------------------------------------*/
    /*  Code                                                                  */
    /*------------------------------------------------------------------------*/
    if ((afu_master_h = cxl_afu_open_dev(i_afu_path)) < 0) {
        TRACEE("Unable to open AFU Master cxl device. errno = %d (%s).\n",
               errno, strerror(errno));
        return NULL;
    }

    TRACEI("Opened %p, now attempting to get FD.\n", afu_master_h);
    afu_master_fd = cxl_afu_fd(afu_master_h);
    TRACEI("Got FD! = %d\n", afu_master_fd);

    if (cxl_afu_attach(afu_master_h, 0)) {
        TRACEE("Call to cxl_afu_attach failed. errno = %d (%s)\n",
               errno, strerror(errno));
        return NULL;
    }

    afu_psa_addr = mmap_afu_registers(afu_master_fd);

    if (!afu_psa_addr) {
        TRACEE("Error attempting to map AFU problem state registers. \
            errno = %d (%s)\n", errno, strerror(errno));
        return NULL;
    }
Exemple #3
0
/*----------------------------------------------------------------------------*/
error_t parse_opt(int key, char * arg, struct argp_state * state) {
    /*------------------------------------------------------------------------*/
    /*  Local Variables                                                       */
    /*------------------------------------------------------------------------*/

    /*------------------------------------------------------------------------*/
    /*  Code                                                                  */
    /*------------------------------------------------------------------------*/
    switch (key)
    {
    case AFUINJ_DEVICE:
        if((arg != NULL) && (strlen(arg) != 0)) {
            strncpy(g_args.target_device, arg, sizeof(g_args.target_device));
            TRACEI("Setting target device to: '%s'\n", g_args.target_device);
        }
        g_args.device = 1;
        break;

    case AFUINJ_READ:
        g_args.read = 1;
        break;

    case AFUINJ_WRITE:
        g_args.write = 1;
        break;

    case AFUINJ_REGISTER:
        if((arg != NULL) && (strlen(arg) != 0)) {
            strncpy(g_args.register_offset, arg, sizeof(g_args.register_offset));
            TRACEI("Using register offset: '%s'\n", g_args.register_offset);
        }
        g_args.reg = 1;
        break;

    case AFUINJ_DATA:
        if((arg != NULL) && (strlen(arg) != 0)) {
            strncpy(g_args.data, arg, sizeof(g_args.data));
            TRACEI("Using data: '%s'\n", g_args.data);
        }
        g_args.data_to_write = 1;
        break;

    case AFUINJ_DEBUG:
        g_args.verbose = atoi(arg);
        if (g_args.verbose >= 1)
            g_traceI = 1;
        if (g_args.verbose >= 2)
            g_traceF = 1;
        if (g_args.verbose >= 3)
            g_traceV = 1;
        TRACEI("Set verbose level to %d.\n", g_args.verbose);
        break;

    default:
        return (ARGP_ERR_UNKNOWN);
    }

    return (0);
}
Exemple #4
0
bool provGetAllAdapters(prov_adapter_info_t* o_info, int* io_num_adapters)
{
    //Locals
    struct cxl_afu_h *l_afu;
    char *l_pci_path = NULL;
    bool l_rc = 0;
    //prov_adapter_info_t* l_curr_adapter_info = NULL;
    int l_num_adapters = 0;
    
    //Code
    cxl_for_each_afu(l_afu)
    {
        if(l_num_adapters >= *io_num_adapters)
        {
            TRACEE("Warning: io_num_adapters = %d, and we have at least one more adapter. Flagging this as an error.\n", *io_num_adapters);
            l_rc = false;
            break;
        }
        TRACEI("AFU found: '%s'\n", cxl_afu_devname(l_afu));
        l_rc = cxl_afu_sysfs_pci(&l_pci_path, l_afu);
        TRACEI("sysfs rc: %d\n", l_rc);
        TRACEI("sysfs path: '%s'\n", l_pci_path);
        l_rc = provGetAdapterInfo(l_pci_path, &o_info[l_num_adapters]);
        if(l_rc == true)
        {
            strncpy(o_info[l_num_adapters].afu_name, cxl_afu_devname(l_afu), sizeof(o_info[l_num_adapters].afu_name));
            l_num_adapters++;
        }
        else
        {
            TRACEE("Failure occurred parsing adapter info for '%s'\n",l_pci_path);
            l_rc = false;
            break;
        }

    }
    
    //all exit paths return the same way
    if(l_rc == false)
    {
        *io_num_adapters = 0;
    }
    else
    {
        *io_num_adapters = l_num_adapters;
    }
    return l_rc;
}
Exemple #5
0
void pbfilter_base::start_thread()
{
	TRACEV("[pbfilter_base] [start_thread]  > Entering routine.");
	m_runthread = true;

	m_exitevt = CreateEvent(0, TRUE, FALSE, 0);
	if(!m_exitevt) throw win32_error("CreateEvent", 0);

	TRACEI("[pbfilter_base] [start_thread]    creating thread_thunk");
	m_thread = CreateThread(0, 0, thread_thunk, this, 0, 0);
	if(!m_thread) {
		DWORD err = GetLastError();

		CloseHandle(m_exitevt);

		TRACEE("[pbfilter_base] [start_thread]    ERROR creating thread_thunk!!");
		throw win32_error("CreateThread", err);
	}

	TCHAR chBuf[256];
	_stprintf_s(chBuf, sizeof(chBuf)/2, _T("[pbfilter_base] [start_thread]    thread_thunk created with handle:[%p]"), m_thread);
	g_tlog.LogMessage(chBuf, TRACELOG_LEVEL_VERBOSE);

	TRACEV("[pbfilter_base] [start_thread]  < Leaving routine.");

} // End of start_thread()
Exemple #6
0
void prov_get_all_adapters()
{
    /*------------------------------------------------------------------------*/
    /*  Local Variables                                                       */
    /*------------------------------------------------------------------------*/
    prov_adapter_info_t l_adapters[MAX_NUM_ADAPTERS];
    int l_num_adapters = MAX_NUM_ADAPTERS;
    bool l_rc = false;
    int l_curr_adapter = 0;
    int l_curr_wwpn = 0;
    /*------------------------------------------------------------------------*/
    /*  Code                                                                  */
    /*------------------------------------------------------------------------*/
    
    bzero(l_adapters, sizeof(l_adapters));
    
    l_rc = provGetAllAdapters(l_adapters, &l_num_adapters);
    if(l_rc == false)
    {
        TRACEE("Error occurred in call to provGetAllAdapters\n");
    }
    else
    {
        TRACEV("Got back %d adapters\n", l_num_adapters);
        for(l_curr_adapter = 0; l_curr_adapter < l_num_adapters; l_curr_adapter++)
        {
            TRACED("Adapter  '%s'\n", l_adapters[l_curr_adapter].afu_name);
            TRACED("PCI Path '%s'\n", l_adapters[l_curr_adapter].pci_path);
            for(l_curr_wwpn = 0; l_curr_wwpn < MAX_WWPNS_PER_ADAPTER; l_curr_wwpn++)
            {
                TRACEI("    Port %d WWPN: 0x%s\n", l_curr_wwpn, l_adapters[l_curr_adapter].wwpn[l_curr_wwpn]);
            }
        }
    }
}
Exemple #7
0
void DillServerChannel::attachSubscriber(DillServerConnection *conn)
{
    TRACEI("     DillServerChannel::attachSubscriber(): subscriber (0x%08x) attached. sending %u logs, %u regctx.", 
        DILL_PTRVAL(conn), Buffers.size(), Registers.size());

    Subscribers.insert(conn);

    for (std::deque<DillParcel*>::iterator it = Buffers.begin();
         it != Buffers.end(); it++)
    {
        conn->asyncWriteParcel(*it);
    }

    boost::shared_ptr<DillParcel> p(new DillParcel);
    p->op = DILL_PRIORITY_REGISTER;
    p->id = ID;
    p->timestamp1 = 0;
    p->timestamp2 = 0;
    for (boost::unordered_map<std::string, std::string>::iterator it = Registers.begin();
         it != Registers.end(); it++)
    {
        p->str1 = it->first;
        p->str2 = it->second;
        conn->asyncWriteParcel(p.get());
    }
}
Exemple #8
0
void provGetAFUs()
{
    //Locals
    struct cxl_afu_h *l_afu;
    char *l_pci_path = NULL;
    int l_rc = 0;
    
    //Code
    cxl_for_each_afu(l_afu)
    {
        TRACEI("AFU found: '%s'\n", cxl_afu_devname(l_afu));
        l_rc = cxl_afu_sysfs_pci(&l_pci_path, l_afu);
        TRACEI("sysfs rc: %d\n", l_rc);
        TRACEI("sysfs path: '%s'\n", l_pci_path);
        free(l_pci_path);
    }
}
Exemple #9
0
bool wait_port_state(const uint8_t* i_afu_psa_addr, const int i_port_offset, const bool i_online)
{
    //Locals
    bool l_rc = false;
    uint8_t i = 0;
    uint32_t mmio_data32 = 0;
    uint32_t l_target_status = FC_MTIP_STATUS_MASK_OFFLINE;
    if(i_online)
    {
        l_target_status = FC_MTIP_STATUS_MASK_ONLINE;
    }
    TRACEV("Waiting for port status mask equal to 0x%08x\n", l_target_status);
    //Code
    for(i=0; i<MAX_PORT_STATUS_RETRY_COUNT; i++)
    {
        //FC_MTIP_STATUS is 32-bit as per MTIP programming reference guide, page 50
        //bit 4 of the register defines whether we are offline
        //bit 5 defines if we are online.
        mmio_data32 = in_mmio32((__u64*)&i_afu_psa_addr[FC_MTIP_STATUS + i_port_offset]);
        TRACEV("FC_MTIP_STATUS    (0x%08X): 0x%08X\n", FC_MTIP_STATUS + i_port_offset, mmio_data32);
        //TODO: define a bitwise union for this structure to ease manipulation
        if( (mmio_data32 & 0x30) == l_target_status)
        {
            //port is now in desired state
            l_rc = true;
            TRACEV("Port state bits are 0x%02x.\n", l_target_status);
            if(i_online)
            {
                TRACEI("Port is now online\n");
            }
            else
            {
                TRACEI("Port is now offline\n");
            }
            break; //break inner for loop...
        }
        TRACEV("Sleeping to retry again...\n");
        usleep(PORT_STATUS_RETRY_INTERVAL_US);
    }
    //rc is only set if we break out of the loop
    return l_rc;
}
void driver::close()
{
	TRACEI("[driver] [close]  > Entering routine.");

	tstring strBuf = boost::str(tformat(_T("[driver] [close]   closing driver - name: [%1%]")) % m_name.c_str() );
	TRACEBUFI(strBuf);

	if(!m_loaded)
	{
		TRACEW("[driver] [close]    Tried to close driver, but it wasn't loaded.");
		TRACEI("[driver] [close]  < Leaving routine (without doing anything).");
		return;
	}

	stop();

	if(this->removable)
	{
		TRACEV("[driver] [close]    driver is removable");
		SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if(!manager) throw win32_error("OpenSCManager");

		SC_HANDLE service = OpenService(manager, m_name.c_str(), SERVICE_ALL_ACCESS);
		if(!service) {
			DWORD err = GetLastError();

			CloseServiceHandle(manager);
			throw win32_error("OpenService", err);
		}

		DeleteService(service);

		CloseServiceHandle(service);
		CloseServiceHandle(manager);
	}

	TRACEI("[driver] [close]    unloaded driver");
	m_loaded = false;

	TRACEI("[driver] [close]  < Leaving routine.");

} // End of close()
Exemple #11
0
bool provLoopbackTest(const prov_adapter_info_t* i_adapter, uint64_t i_test_time_us)
{
    //Locals
    bool l_rc = true; //rely on l_rc defaulting to true. only write it to false on error
    bool l_portrc = true;
    uint8_t l_curr_port = 0;
    char l_afu_path[DEV_PATH_LENGTH] = {0};
    //Code
    do
    {
        if(i_adapter == NULL)
        {
            TRACEE("Error! invalid args detected.\n");
            l_rc = false;
            break;
        }
        if((i_test_time_us < LOOPBACK_TEST_TIME_MIN) || (i_test_time_us > LOOPBACK_TEST_TIME_MAX))
        {
            TRACEE("Error! Test time of %"PRIu64" is invalid.\n", i_test_time_us);
            l_rc = false;
            break;
        }
        snprintf(l_afu_path, sizeof(l_afu_path), "/dev/cxl/%sm", i_adapter->afu_name);
        
        TRACEI("Running loopback for %s\n", l_afu_path);
        for(l_curr_port=0; l_curr_port < MAX_WWPNS_PER_ADAPTER; l_curr_port++)
        {
            l_portrc = loopbackDiag(l_afu_path, l_curr_port, i_test_time_us);
            if(l_portrc == false)
            {
                TRACEI("Loopback failed.\n");
                l_rc = false; //any single port failure makes the entire test fail
            }
        }
        
    } while (0);
    

    return l_rc;
}
Exemple #12
0
void * mmap_afu_registers(int afu_master_fd) {
    /*------------------------------------------------------------------------*/
    /*  Local Variables                                                       */
    /*------------------------------------------------------------------------*/
    void * l_ret_ptr = NULL;

    /*------------------------------------------------------------------------*/
    /*  Code                                                                  */
    /*------------------------------------------------------------------------*/
    TRACEI("Attempting to mmap 0x%016zx bytes of problem state.\n", //%zx prints a size_t gracefully
           sizeof(struct surelock_afu_map));
    l_ret_ptr = mmap(NULL, sizeof(struct surelock_afu_map), PROT_READ|PROT_WRITE, MAP_SHARED,
                     afu_master_fd, 0);
    TRACEI("MMAP AFU Master complete.\n");
    if (l_ret_ptr == MAP_FAILED) {
        TRACEE("Unable to mmap problem state regs. errno = %d (%s).\n",
               errno, strerror(errno));
        l_ret_ptr = NULL;
    }

    return l_ret_ptr;
}
Exemple #13
0
void * mmap_afu_wwpn_registers(int afu_master_fd)
{
    //Locals
	void *l_ret_ptr = NULL;
    
    //Code
    TRACEI("Attempting to mmap 0x%016X bytes of problem state.\n", FC_PORT_MMAP_SIZE);
    l_ret_ptr = mmap(NULL, FC_PORT_MMAP_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED,
                     afu_master_fd, 0);
    TRACEV("MMAP AFU Master  complete\n");
    if (l_ret_ptr == MAP_FAILED) {
        TRACEE("Unable to mmap problem state regs. errno = %d (%s)\n", errno, strerror(errno));
        l_ret_ptr = NULL;
    }
    
	return l_ret_ptr;
}
Exemple #14
0
int main(){
	// Note that the console output is created by default

	// Create a formatted HTML file output
	TdOutputHandle html = td_createFileOutput("log.html", eTD_FMT_HTML);

	// Create a plain text output
	TdOutputHandle plain = td_createFileOutput("log.txt", eTD_FMT_PLAIN_TEXT);

	// Basic log macros
	LOGV("Verbose LOG");

	LOGD("Debug LOG");

	LOGI("Info LOG");

	LOGW("Warning LOG");

	LOGE("Error LOG");

	// Tracing macro
	TRACEV("Verbose TRACE");

	TRACED("Debug TRACE");

	TRACEI("Info TRACE");

	TRACEW("Warning TRACE");

	TRACEE("Error TRACE");

	// Destroy previously created outputs
	td_destroyOutput(html);

	td_destroyOutput(plain);

	system("pause");

	return 0;
}
Exemple #15
0
bool provInitAdapter(const prov_adapter_info_t* i_adapter)
{
    //Locals
    bool l_rc = false;
    uint64_t l_curr_wwpn = 0;
    uint8_t l_curr_port = 0;
    char l_afu_path[DEV_PATH_LENGTH] = {0};
    //Code
    do
    {
        if(i_adapter == NULL)
        {
            TRACEE("Error! invalid args detected.\n");
            l_rc = false;
            break;
        }
        snprintf(l_afu_path, sizeof(l_afu_path), "/dev/cxl/%sm", i_adapter->afu_name);
        TRACED("Setting up adapter '%s'...\n", l_afu_path);
        
        
        TRACEI("Initializing WWPN Data\n");
        for(l_curr_port=0; l_curr_port < MAX_WWPNS_PER_ADAPTER; l_curr_port++)
        {
            l_curr_wwpn = strtoul(i_adapter->wwpn[l_curr_port],NULL,16);
            TRACEV("Initing AFU '%s' port %d\n", l_afu_path, l_curr_port);
            l_rc = initialize_wwpn(l_afu_path, l_curr_port, l_curr_wwpn);
            if(l_rc == false)
            {
                TRACEE("Error occurred while initializing WWPN Data.\n");
                break;
            }
        }
        
        //finished!
        TRACED("SUCCESS: Initialization Complete!\n");
    } while (0);
    

    return l_rc;
}
//================================================================================================
//
//  PerformPrevRelUpdates()
//
//    - Called by Main_OnInitDialog()
//
/// <summary>
///   Checks the version of the last time we ran, and if that number falls within certain ranges
///   we'll do some release-specific cleanup.
/// </summary>
//
void PerformPrevRelUpdates(HWND _hwnd)
{
	int prevRelease = g_config.LastVersionRun;

	if (prevRelease == PB_VER_BUILDNUM)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    no version change, so no updates to perform");
		return;
	}

	if (prevRelease > PB_VER_BUILDNUM)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    WARNING:  Downgrade detected!");
		return;
	}


	//--------------------------------------------------
	// Update PG hosted lists to iblocklist

	if (prevRelease < 134)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    Checking for old peerguardian-hosted lists, and updating any found to iblocklist.com-hosted ones");

		vector<DynamicList> tempList;

		// check each list in configured lists
		for(vector<DynamicList>::size_type i = 0; i < g_config.DynamicLists.size(); ++i)
		{
			// if it's a peerguardian list
			DynamicList *list = &(g_config.DynamicLists[i]);
			if (list->Url.find(_T("http://peerguardian.sourceforge.net/lists/")) != string::npos)
			{
				// swap it out
				tstring strBuf = boost::str(tformat(_T("[mainproc] [PerformPrevRelUpdates]    found old URL: [%1%]")) % list->Url );
				TRACEBUFW(strBuf);

				if (list->Url.find(_T("ads.php")) != string::npos)
				{
					// http://list.iblocklist.com/?list=bt_ads
					TRACEW("[mainproc] [PerformPrevRelUpdates]    - replacing ads.php list with bt_ads");
					//list->Url = _T("http://list.iblocklist.com/?list=bt_ads");
					DynamicList newList = *list;
					newList.Url = _T("http://list.iblocklist.com/lists/bluetack/ads-trackers-and-bad-pr0n");
					tempList.push_back(newList);
				}
				else if (list->Url.find(_T("edu.php")) != string::npos)
				{
					// http://list.iblocklist.com/?list=bt_edu
					TRACEW("[mainproc] [PerformPrevRelUpdates]    - replacing edu.php list with bt_edu");
					//list->Url = _T("http://list.iblocklist.com/?list=bt_edu");
					DynamicList newList = *list;
					newList.Url = _T("http://list.iblocklist.com/lists/bluetack/edu");
					tempList.push_back(newList);
				}
				else if (list->Url.find(_T("p2p.php")) != string::npos)
				{
					// http://list.iblocklist.com/?list=bt_level1
					TRACEW("[mainproc] [PerformPrevRelUpdates]    - replacing p2p.php list with bt_level1");
					//list->Url = _T("http://list.iblocklist.com/?list=bt_level1");
					DynamicList newList = *list;
					newList.Url = _T("http://list.iblocklist.com/lists/bluetack/level-1");
					tempList.push_back(newList);
				}
				else if (list->Url.find(_T("spy.php")) != string::npos)
				{
					// http://list.iblocklist.com/?list=bt_spyware
					TRACEW("[mainproc] [PerformPrevRelUpdates]    - replacing spy.php list with bt_spyware");
					//list->Url = _T("http://list.iblocklist.com/?list=bt_spyware");
					DynamicList newList = *list;
					newList.Url = _T("http://list.iblocklist.com/lists/bluetack/spyware");
					tempList.push_back(newList);
				}
				else if (list->Url.find(_T("gov.php")) != string::npos)
				{
					// remove list
					TRACEW("[mainproc] [PerformPrevRelUpdates]    - removing gov list");
				}
				else
				{
					TRACEE("[mainproc] [PerformPrevRelUpdates]    ERROR:  Unknown PG2 list!!");
				}
			}
			else
			{
				TRACED("[mainproc] [PerformPrevRelUpdates]    found non-PG2 URL");
				DynamicList newList = *list;
				tempList.push_back(newList);
			}
		}

		// Rebuild list if we need to remove Gov list.  Also, check for duplicates.
		g_config.DynamicLists.clear();
		for(vector<DynamicList>::size_type i = 0; i < tempList.size(); ++i)
		{
			if (std::find(g_config.DynamicLists.begin(), g_config.DynamicLists.end(), tempList[i]) == g_config.DynamicLists.end())
			{
				g_config.DynamicLists.push_back(tempList[i]);
			}
		}
	}


	//--------------------------------------------------
	// Update old list-names to new ones

	// Now that iblocklist.com has support for some "friendly" URLs for lists, we can migrate people
	// away from the slow, unreliable bluetack.co.uk servers and over to iblocklist.  We're checking
	// against any of the bluetack URLs from our old dropdown list, and changing 'em over.  Same
	// thing for any of the old naming-scheme iblocklist URLs.  We're also removing the bluetack
	// "trojan" list, since it resolves to an unusable file and there is no iblocklist equivalent.

	if (prevRelease < 268)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    Checking for old-URL lists, and migrating them to the new naming scheme (r268)");
		int result = MessageBox(_hwnd, IDS_PREVREL268TEXT, IDS_PREVREL, MB_ICONINFORMATION|MB_YESNO);
		if (result == IDNO)
		{
			TRACEI("[mainproc] [PerformPrevRelUpdates]    user clicked No");
		}
		else if (result == IDYES)
		{
			TRACEI("[mainproc] [PerformPrevRelUpdates]    user clicked Yes");

			vector<DynamicList> tempList;
			ListUrls listUrls;
			listUrls.Init();

			// check each list in configured lists
			for(vector<DynamicList>::size_type i = 0; i < g_config.DynamicLists.size(); ++i)
			{
				DynamicList *list = &(g_config.DynamicLists[i]);
				LISTNAME listId = listUrls.FindListNum(list->Url);
				if (listId != LISTNAME_COUNT)
				{
					DynamicList newList = *list;
					newList.Url = listUrls.GetBestUrl(listId);
					tempList.push_back(newList);
					if (newList.Url.compare(list->Url) == 0)
					{
						tstring strBuf = boost::str(tformat(_T("[mainproc] [PerformPrevRelUpdates]    - found no better list url than [%1%]"))
							% list->Url.c_str() );
						TRACEBUFW(strBuf);
					}
					else
					{
						tstring strBuf = boost::str(tformat(_T("[mainproc] [PerformPrevRelUpdates]    - migrated list from [%1%] to [%2%]"))
							% list->Url.c_str() % newList.Url.c_str() );
						TRACEBUFW(strBuf);
					}
				}
				else if (list->Url.compare(_T("http://www.bluetack.co.uk/config/trojan.zip")) == 0)
				{
					TRACEW("[mainproc] [PerformPrevRelUpdates]    - removing no-longer-existant bt trojan");
				}
				else
				{
					tstring strBuf = boost::str(tformat(_T("[mainproc] [PerformPrevRelUpdates]    - found unknown list url [%1%], copying over as-is"))
						% list->Url.c_str() );
					TRACEBUFW(strBuf);
					DynamicList newList = *list;
					tempList.push_back(newList);
				}
			}

			// Rebuild list, checking for duplicates.
			g_config.DynamicLists.clear();
			for(vector<DynamicList>::size_type i = 0; i < tempList.size(); ++i)
			{
				if (std::find(g_config.DynamicLists.begin(), g_config.DynamicLists.end(), tempList[i]) == g_config.DynamicLists.end())
				{
					g_config.DynamicLists.push_back(tempList[i]);
				}
			}
		}
	}


	//--------------------------------------------------
	// Update max history.db size from old default of 0 (unlimited) to 100 MB

	if (prevRelease < 341)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    Checking for old History defaults of 0, and migrating it to the new default of 100 MB (r341)");

		if (g_config.CleanupType == None && g_config.MaxHistorySize > 0)
		{
			TRACEW("[mainproc] [PerformPrevRelUpdates]    CleanupType = None, updating it to Delete every 7 Days");
			MessageBox(_hwnd, IDS_PREVREL341TEXT_DEL, IDS_PREVREL, MB_ICONINFORMATION|MB_OK);
			g_config.CleanupType = Delete;
			g_config.CleanupInterval = 7;
			g_config.Save();
		}
		else if (g_config.MaxHistorySize == 0 && g_config.CleanupType != None)
		{
			TRACEW("[mainproc] [PerformPrevRelUpdates]    Max history.db size 0 ('unlimited'), updating it to 100 MB");
			MessageBox(_hwnd, IDS_PREVREL341TEXT_MAX, IDS_PREVREL, MB_ICONINFORMATION|MB_OK);
			g_config.MaxHistorySize = 100 * 1000000;	// g_config.MaxHistory is in bytes...
			g_config.Save();
		}
		else if (g_config.MaxHistorySize == 0 && g_config.CleanupType == None)
		{
			TRACEW("[mainproc] [PerformPrevRelUpdates]    Changing history.db max size to 100 MB, and CleaupType to Delete every 7 days");
			MessageBox(_hwnd, IDS_PREVREL341TEXT_BOTH, IDS_PREVREL, MB_ICONINFORMATION|MB_OK);
			g_config.CleanupType = Delete;
			g_config.CleanupInterval = 7;
			g_config.MaxHistorySize = 100 * 1000000;	// g_config.MaxHistory is in bytes...
			g_config.Save();
		}
		else
		{
			TRACEW("[mainproc] [PerformPrevRelUpdates]    Not changing config");
			tstring strBuf = boost::str(tformat(_T("[mainproc] [PerformPrevRelUpdates]    Max history.db size (%1%) ")) % g_config.MaxHistorySize );
			g_tlog.LogMessage(strBuf, TRACELOG_LEVEL_WARNING);
		}
	}


	//--------------------------------------------------
	// Update Bluetack Webexploit/Forumspam merged list to new individual lists, and cw_bogon list
	// to the most frequently updated one, cidr_bogon

	if (prevRelease < 411)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    Checking for Bluetack Webexploit/Forumspam, cr_bogon, or default lists (r411)");

		vector<DynamicList> tempList;
		ListUrls listUrls;
		listUrls.Init();

		// check each list in configured lists
		for(vector<DynamicList>::size_type i = 0; i < g_config.DynamicLists.size(); ++i)
		{
			DynamicList *list = &(g_config.DynamicLists[i]);
			LISTNAME listId = listUrls.FindListNum(list->Url);
			if (listId == LISTNAME_BT_WEBEX_FSPAM)
			{
				TRACEW("[mainproc] [PerformPrevRelUpdates]    Updating Bluetack Webexploit/Forumspam merged list to new individual lists");
				MessageBox(_hwnd, IDS_PREVREL411TEXT_WEBEX, IDS_PREVREL, MB_ICONINFORMATION|MB_OK);

				DynamicList * newList = new DynamicList;
				newList->Url = listUrls.GetBestUrl(LISTNAME_BT_WEBEXPLOIT);
				newList->Enabled = list->Enabled;
				newList->Description = listUrls.GetListDesc(LISTNAME_BT_WEBEXPLOIT);
				tempList.push_back(*newList);

				DynamicList * newList2 = new DynamicList;
				newList2->Url = listUrls.GetBestUrl(LISTNAME_BT_FORUMSPAM);
				newList2->Enabled = list->Enabled;
				newList2->Description = listUrls.GetListDesc(LISTNAME_BT_FORUMSPAM);
				tempList.push_back(*newList2);
			}
			else if (listId == LISTNAME_CW_BOGON)
			{
				TRACEW("[mainproc] [PerformPrevRelUpdates]    Updating CW Bogon list to CIDR Bogon");
				MessageBox(_hwnd, IDS_PREVREL411TEXT_BOGON, IDS_PREVREL, MB_ICONINFORMATION|MB_OK);

				DynamicList * newList = new DynamicList;
				newList->Url = listUrls.GetBestUrl(LISTNAME_CIDR_BOGON);
				newList->Enabled = list->Enabled;
				newList->Description = listUrls.GetListDesc(LISTNAME_CIDR_BOGON);
				tempList.push_back(*newList);
			}
			else if ( listId == LISTNAME_BT_LEVEL1 || listId == LISTNAME_BT_ADS ||
					  listId == LISTNAME_BT_SPY || listId == LISTNAME_BT_EDU )
			{
				// Make sure Default Lists are set to Block, not Allow.  This will also take care
				// of any misconfigured PG2 lists, and is especially important since the PeerBlock
				// List Manager has no easy way to set lists to Block instead of Allow, nor will
				// it show you that it's an Allow list.

				if (list->Type == List::Allow)
				{
					tstring strBuf = boost::str(tformat(_T("[mainproc] [PerformPrevRelUpdates]    Updating list:[%1%] from type:[Allow] to type:[Block]")) % list->Description );
					TRACEBUFW(strBuf);

					DynamicList * newList = new DynamicList;
					newList->Url = list->Url;
					newList->Enabled = list->Enabled;
					newList->Description = list->Description;
					newList->Type = List::Block;
					tempList.push_back(*newList);
				}
				else
				{
					tempList.push_back(*list);
				}
			}
			else
			{
				// not LISTNAME_BT_WEBEX_FSPAM, LISTNAME_CIDR_BOGON, or a default list
				tempList.push_back(*list);
			}
		}

		// Rebuild list, checking for duplicates.
		g_config.DynamicLists.clear();
		for(vector<DynamicList>::size_type i = 0; i < tempList.size(); ++i)
		{
			if (std::find(g_config.DynamicLists.begin(), g_config.DynamicLists.end(), tempList[i]) == g_config.DynamicLists.end())
			{
				g_config.DynamicLists.push_back(tempList[i]);
			}
		}

	} // end of webex/forumspam update (r411)


	//--------------------------------------------------
	// Delete history.db if it's too large

	if (prevRelease < 454)
	{
		// check for filesize of history.db
		TRACEI("[mainproc] [PerformPrevRelUpdates]    checking size of history.db (r454)");

		struct _stat64 fileStat;
		path history_file = path::base_dir()/_T("history.db");
		int ret = _tstat64( history_file.c_str(), &fileStat );

		if (ret == 0)
		{
			// if it's too-large, delete it outright
			if (fileStat.st_size > g_config.MaxHistorySize*1.5) // 150 MB, by default
			{
				TRACEW("[mainproc] [PerformPrevRelUpdates]    Too-large history.db file detected!");
				path::remove(history_file);
				TRACEW("[mainproc] [PerformPrevRelUpdates]    Deleted history.db");
			}
		}

	} // end of delete too-large history.db (r454)


	//--------------------------------------------------
	// Remove I-Blocklist Subscription URL params if present, add them to peerblock.conf instead

	if (prevRelease < 653)
	{
		TRACEW("[mainproc] [PerformPrevRelUpdates]    Checking for I-Blocklist Subscription list URL params (r653)");

		ListUrls listUrls;
		listUrls.Init();
		tstring username;
		tstring pin;

		// check each list in configured lists
		for(vector<DynamicList>::size_type i = 0; i < g_config.DynamicLists.size(); ++i)
		{
			DynamicList *list = &(g_config.DynamicLists[i]);

			if (string::npos != list->Url.find(_T("http://list.iblocklist.com/?list=")))
			{
				// split url up into tokens
				size_t start = 0;
				size_t end = 0;
				map<tstring, tstring> params;

				start = list->Url.find(_T("?")) + 1;
				while (string::npos != end && string::npos != start)
				{
					end = list->Url.find(_T("&"), start);
					tstring paramSet = list->Url.substr(start,
						(end == string::npos) ? string::npos : end - start);
					start = (end > (string::npos - 1) ) ? string::npos : end + 1;

					size_t eqPos = 0;
					eqPos = paramSet.find(_T("="));
					if (string::npos != eqPos)
					{
						tstring key = paramSet.substr(0, eqPos);
						tstring val = paramSet.substr(eqPos + 1);
						params[key] = val;
					}
				}

				if (params.find(_T("username")) != params.end())
				{
					username = params.at(_T("username"));
				}

				if (params.find(_T("id")) != params.end())
				{
					username = params.at(_T("id"));
				}

				if (params.find(_T("pin")) != params.end())
				{
					pin = params.at(_T("pin"));
				}

				// sanity-check, make sure we didn't screw up and lost the list-param
				if (params.find(_T("list")) != params.end())
				{
					list->Url = tstring(_T("http://list.iblocklist.com/?list=")) + params.at(_T("list"));
				}
			}

			else if (string::npos != list->Url.find(_T("http://list.iblocklist.com/lists/")))
			{
				// split url up into tokens
				size_t urlRootEndPos = 0;
				size_t start = 0;
				size_t end = 0;
				map<tstring, tstring> params;

				urlRootEndPos = list->Url.find(_T("?"));
				if (string::npos != urlRootEndPos)
				{
					// we've got some params here
					start = urlRootEndPos + 1;
					while (string::npos != end && string::npos != start)
					{
						end = list->Url.find(_T("&"), start);
						tstring paramSet = list->Url.substr(start,
							(end == string::npos) ? string::npos : end - start);
						start = (end > (string::npos - 1) ) ? string::npos : end + 1;

						size_t eqPos = 0;
						eqPos = paramSet.find(_T("="));
						if (string::npos != eqPos)
						{
							tstring key = paramSet.substr(0, eqPos);
							tstring val = paramSet.substr(eqPos + 1);
							params[key] = val;
						}
					}

					if (params.find(_T("username")) != params.end())
					{
						username = params.at(_T("username"));
					}

					if (params.find(_T("id")) != params.end())
					{
						username = params.at(_T("id"));
					}

					if (params.find(_T("pin")) != params.end())
					{
						pin = params.at(_T("pin"));
					}

					// strip away all params from this URL, since none are applicable any longer
					list->Url = list->Url.substr(0, urlRootEndPos);
				}
			}
		}

		// if we have a username (id) and pin, save them to config, and remove them from here
		if (!username.empty() && !pin.empty())
		{
			g_config.IblUsername = username;
			g_config.IblPin = pin;
			g_config.Save();
		}

	} // end of i-blocklist subscription list-url param cleanup (r653)


	//--------------------------------------------------
	// Inform user about I-Blocklist's list-update limit

	if (prevRelease < 681)
	{
		TRACEI("[mainproc] [PerformPrevRelUpdates]    displaying info about I-Blocklist list-update limits (r681)");
        MessageBox(_hwnd, IDS_PREVREL681TEXT, IDS_PREVREL, MB_ICONINFORMATION|MB_OK);

	} // end of i-blocklist list-update limit info (r681)

}; // End of PerformPrevRelUpdates()
Exemple #17
0
error_t parse_opt (int key,
                   char *arg,
                   struct argp_state *state)
{
    /*------------------------------------------------------------------------*/
    /*  Local Variables                                                       */
    /*------------------------------------------------------------------------*/
    static int32_t last_command = -1;
    //int32_t l_temp = 0;
    
    /*-------------------------------------------------------------------------*/
    /*  Code                                                                   */
    /*-------------------------------------------------------------------------*/
    
    switch (key)
    {
        case PROV_LIST_AFUS:
            g_args.list_afus = 1;
            break;
        
        case PROV_WWPNS_READ:
            if((arg != NULL) && (strlen(arg) != 0))
            {
                strncpy(g_args.target_adapter, arg, sizeof(g_args.target_adapter));
                TRACEV("Setting target adapter to: '%s'\n", g_args.target_adapter);
            }
            g_args.wwpn_read = 1;
            break;
            
        case PROV_WWPNS_PGM:
            if((arg != NULL) && (strlen(arg) != 0))
            {
                strncpy(g_args.target_adapter, arg, sizeof(g_args.target_adapter));
                TRACEV("Setting target adapter to: '%s'\n", g_args.target_adapter);
            }
            g_args.wwpn_program = 1;
            break;
        
        case PROV_LOOPBACK:
            g_args.loopback = 1;
            g_args.loopback_time = LOOPBACK_TEST_DEFAULT_S; //choose a default value and then check to see if we have an arg
            if((arg != NULL) && (strlen(arg) != 0))
            {
                g_args.loopback_time = atoi(arg);
                if((g_args.loopback_time < LOOPBACK_TEST_MIN_S) || (g_args.loopback_time > LOOPBACK_TEST_MAX_S))
                {
                    TRACED("Invalid loopback test time of %d. Defaulting to %d\n", g_args.loopback_time, LOOPBACK_TEST_DEFAULT_S);
                    g_args.loopback_time = LOOPBACK_TEST_DEFAULT_S;
                }
            }
            break;
            
        case PROV_DEBUG:
            g_args.verbose = atoi (arg);
            TRACEI ("Set verbose level to %d\n", g_args.verbose);
            if (g_args.verbose >= 1)
                g_traceI = 1;
            if (g_args.verbose >= 2)
                g_traceF = 1;
            if (g_args.verbose >= 3)
                g_traceV = 1;
            break;
            
        case 0 :
            
            if((last_command == PROV_QUERY_AFU) &&
               ((strncmp(arg,"/",1))) && // They may put input dir/file
               ((strncmp(arg,".",1))))   //  after comp so look for it
            {
                TRACEI("Also Look for component %s\n",arg);
                last_command = PROV_QUERY_AFU;
                goto exit_no_set;
                
            }
            
            break;
            
        default:
            return (ARGP_ERR_UNKNOWN);
    }
    
    last_command = -1;
    TRACEF ("Last cmd\n");
    return (0);
    
exit_no_set:
    return(0);
    
}
Exemple #18
0
void DillServerChannel::detachSubscriber(DillServerConnection *conn)
{
    TRACEI("     DillServerChannel::detachSubscriber(): subscriber (0x%08x) detached.", DILL_PTRVAL(conn));
    Subscribers.erase(conn);
}
void driver::stop()
{
	TRACEI("[driver] [stop]  > Entering routine.");

	if(!m_started)
	{
		TRACEW("[driver] [stop]    Tried to stop driver, but it is not started");
		TRACEI("[driver] [stop]  < Leaving routine (without doing anything).");
		return;
	}
	else if (!m_stoppable)
	{
		TRACEW("[driver] [stop]    Tried to stop driver, but it is not flagged as a stoppable driver");
		TRACEI("[driver] [stop]  < Leaving routine (without doing anything).");
		return;
	}

	TRACEI("[driver] [stop]    stopping driver");

	if(m_dev != INVALID_HANDLE_VALUE) {
		CloseHandle(m_dev);
		m_dev = INVALID_HANDLE_VALUE;
	}

	SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager)
	{
		TRACEE("[driver] [stop]    ERROR:  Can't OpenSCManager");
		throw win32_error("OpenSCManager");
	}

	SC_HANDLE service=OpenService(manager, m_name.c_str(), SERVICE_ALL_ACCESS);
	if(!service) {
		DWORD err = GetLastError();

		CloseServiceHandle(manager);
		TRACEE("[driver] [stop]    ERROR:  Can't OpenService");
		throw win32_error("OpenService", err);
	}

	SERVICE_STATUS status;
	if(
		(
			!QueryServiceStatus(service, &status) ||
			(
				status.dwCurrentState != SERVICE_STOPPED &&
				status.dwCurrentState != SERVICE_STOP_PENDING
			)
		) &&
		!ControlService(service, SERVICE_CONTROL_STOP, &status))
	{
		DWORD err = GetLastError();

		CloseServiceHandle(service);
		CloseServiceHandle(manager);

		TRACEE("[driver] [stop]    ERROR:  Can't ControlService");
		throw win32_error("ControlService", err);
	}

	CloseServiceHandle(service);
	CloseServiceHandle(manager);

	TRACEI("[driver] [stop]    driver has been stopped");
	m_started = false;

	TRACEI("[driver] [stop]  < Leaving routine.");

} // End of stop()
void driver::start(bool _gethandle)
{
	TRACEV("[driver] [start]  > Entering routine.");
	if(m_started)
	{
		TRACEI("[driver] [start]    driver already started");
		return;
	}

	TRACEI("[driver] [start]    starting driver");

	DWORD err = 0;

	SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager)
	{
		TRACEERR("[driver] [start]", L"ERROR: OpenSCManager", err = GetLastError());
		throw win32_error("OpenSCManager");
	}

	SC_HANDLE service = OpenService(manager, m_name.c_str(), SERVICE_ALL_ACCESS);
	if(!service)
	{
		CloseServiceHandle(manager);
		TRACEERR("[driver] [start]", L"ERROR: OpenService", err = GetLastError());
		throw win32_error("OpenService", err);
	}

	if(!StartService(service, 0, NULL) && (err = GetLastError()) != ERROR_SERVICE_ALREADY_RUNNING)
	{
		bool startFailed = true;

		if (err == ERROR_SERVICE_DATABASE_LOCKED)
		{
			int numRetries = 0;

			do
			{
				TRACEW("[driver] [start]    experiencing ERROR_SERVICE_DATABASE_LOCKED condition; waiting 10 seconds and trying again");
				Sleep(10000); // 10 seconds
				err = 0;

				if (!StartService(service, 0, NULL) && (err = GetLastError()) != ERROR_SERVICE_ALREADY_RUNNING)
					// still having problems
					++numRetries;
				else
					// either success, or another error
					break;

			} while (err == ERROR_SERVICE_DATABASE_LOCKED && numRetries < 6);

			if (numRetries < 6 && (err == 0 || err == ERROR_SERVICE_ALREADY_RUNNING))
			{
				startFailed = false;
				TRACES("[driver] [start]    successfully recovered from ERROR_SERVICE_DATABASE_LOCKED condition");
			}
			else if (err == ERROR_SERVICE_DATABASE_LOCKED)
			{
				TRACEE("[driver] [start]    cannot recover from ERROR_SERVICE_DATABASE_LOCKED condition; giving up");
			}
			else
			{
				TRACEE("[driver] [start]    cannot recover from ERROR_SERVICE_DATABASE_LOCKED condition; another error surfaced; giving up");
			}
		}

		if (startFailed)
		{
			CloseServiceHandle(service);
			CloseServiceHandle(manager);

			TRACEERR("[driver] [start]", L"ERROR: StartService", err);
			throw win32_error("StartService", err);
		}
	}

	CloseServiceHandle(service);
	CloseServiceHandle(manager);

	if (_gethandle)
	{
		tstring strBuf = boost::str(tformat(_T("[driver] [start]    getting handle to driver - devfile: [%1%]")) % m_devfile.c_str() );
		TRACEBUFI(strBuf);

		m_dev = CreateFile(m_devfile.c_str(), GENERIC_READ | GENERIC_WRITE,
			0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);

		if(m_dev == INVALID_HANDLE_VALUE)
		{
			TRACEERR("[driver] [start]", L"ERROR: CreateFile", err = GetLastError());
			throw win32_error("CreateFile");
		}

		m_stoppable = true;
	}
	else
	{
		m_stoppable = false; // should only be false for MS IpFilterDriver
		TRACEI("[driver] [start]    flagging driver as not stoppable");
	}

	TRACEI("[driver] [start]    started driver");
	m_started = true;

	TRACEV("[driver] [start]  < Leaving routine.");

} // End of start()
void driver::load(const std::wstring &name, const std::wstring &file, const std::wstring &devfile)
{
	TRACEV("[driver] [load(3)]  > Entering routine.");
	if(m_loaded) throw std::exception("driver already loaded", 0);

	{
		tstring strBuf = boost::str(tformat(_T("[driver] [load(3)]    loading driver - name: [%1%], file: [%2%], devfile: [%3%]"))
			% name.c_str() % file.c_str() % devfile.c_str() );
		TRACEBUFI(strBuf);
	}

	m_name = name;
	m_file = file;
	m_devfile = devfile;

	SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager) throw win32_error("OpenSCManager");

	SC_HANDLE service = CreateService(manager, m_name.c_str(), m_name.c_str(),
		SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
		m_file.c_str(), NULL, NULL, NULL, NULL, NULL);

	if(!service)
	{
		DWORD err = 0;

		TRACEERR("[driver] [load(3)]", L"driver not currently installed as service", err = GetLastError());

		err = 0;
		service = OpenService(manager, m_name.c_str(), SERVICE_ALL_ACCESS);
		if(!service)
		{
			TRACEERR("[driver] [load(3)]", L"opening service", err = GetLastError());
			CloseServiceHandle(manager);
			throw win32_error("OpenService", err);
		}

		// make sure it has the same path as m_file.

		DWORD bytes;
		BOOL ret = QueryServiceConfig(service, NULL, 0, &bytes);

		if(ret || (err = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
		{
			TRACEERR("[driver] [load(3)]", L"calling QueryServiceConfig", err);
			CloseServiceHandle(service);
			CloseServiceHandle(manager);
			throw win32_error("QueryServiceConfig", err);
		}
		err = 0; // reset error-code, so that nobody else accidentally trips over it.

		QUERY_SERVICE_CONFIG *qsc = (QUERY_SERVICE_CONFIG*)malloc(bytes);
		if(!qsc)
		{
			TRACEERR("[driver] [load(3)]", L"allocating memory for QueryServiceConfig", err = GetLastError());
			CloseServiceHandle(service);
			CloseServiceHandle(manager);
			throw std::bad_alloc();
		}

		ret = QueryServiceConfig(service, qsc, bytes, &bytes);
		if(!ret)
		{
			TRACEERR("[driver] [load(3)]", L"second call to QueryServiceConfig", err = GetLastError());
			CloseServiceHandle(service);
			CloseServiceHandle(manager);
			throw win32_error("QueryServiceConfig", err);
		}

		bool del = _wcsicmp(qsc->lpBinaryPathName, m_file.c_str()) != 0;
		if (del)
		{
			// check for e.g. \??\C:\WINDOWS\System32\DRIVERS\ipfltdrv.sys
			wchar_t * descr = _wgetenv(L"WINDIR");
			if (descr)
			{
				wstring strFullPath(L"\\??\\");
				strFullPath += descr;
				strFullPath += L"\\";
				strFullPath += m_file;

				tstring strBuf = boost::str(tformat(_T("[driver] [load(3)]    comparing against driver full-path:[%1%]")) % strFullPath );
				TRACEBUFI(strBuf);

				del = _wcsicmp(qsc->lpBinaryPathName, strFullPath.c_str()) != 0;
			}
			else
			{
				TRACEW("[driver] [load(3)]    WINDIR environment variable not found!");
			}
		}

		tstring strBuf = boost::str(tformat(_T("[driver] [load(3)]    service name: [%1%], file name: [%2%]"))
			% qsc->lpBinaryPathName % m_file.c_str() );
		TRACEBUFI(strBuf);

		free(qsc);

		// paths don't match, remove service and recreate.
		if(del)
		{
			TRACEW("[driver] [load(3)]    paths don't match, removing and recreating driver-service");
			TCHAR buf[128];

			// if it's not removable, bail out.
			if(!this->removable)
			{
				TRACEC("[driver] [load(3)]    ERROR trying to remove driver-service");
				CloseServiceHandle(service);
				CloseServiceHandle(manager);
				throw std::exception("unremovable service mismatch", 0);
			}

			// check if its running
			SERVICE_STATUS status;
			ret = QueryServiceStatus(service, &status);
			if(!ret)
			{
				TRACEERR("[driver] [load(3)]", L"ERROR calling QueryServiceStatus", err = GetLastError());
				CloseServiceHandle(service);
				CloseServiceHandle(manager);
				throw win32_error("QueryServiceStatus", err);
			}

			// and stop it if it is.
			switch(status.dwCurrentState)
			{
				case SERVICE_STOPPED:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_STOPPED]");
					break;

				case SERVICE_START_PENDING:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_START_PENDING]");
					break;

				case SERVICE_STOP_PENDING:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_STOP_PENDING]");
					break;

				case SERVICE_RUNNING:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_RUNNING]");
					break;

				case SERVICE_CONTINUE_PENDING:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_CONTINUE_PENDING]");
					break;

				case SERVICE_PAUSE_PENDING:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_PAUSE_PENDING]");
					break;

				case SERVICE_PAUSED:
					TRACEI("[driver] [load(3)]    service state: [SERVICE_PAUSED]");
					break;

				default:
					swprintf_s(buf, _countof(buf), L"[driver] [load(3)]  * ERROR: Unknown service state: [%u]", status.dwCurrentState);
					TRACEBUFE(buf);
					break;
			}
			if(status.dwCurrentState != SERVICE_STOPPED && status.dwCurrentState != SERVICE_STOP_PENDING)
			{
				ret = ControlService(service, SERVICE_CONTROL_STOP, &status);
				if(!ret)
				{
					TRACEERR("[driver] [load(3)]", L"ERROR stopping driver-service", err = GetLastError());
					CloseServiceHandle(service);
					CloseServiceHandle(manager);
					throw win32_error("ControlService", err);
				}
			}

			// now delete the service.
			ret = DeleteService(service);
			err = GetLastError();
			CloseServiceHandle(service);

			if(!ret && err != ERROR_SERVICE_MARKED_FOR_DELETE)
			{
				TRACEERR("[driver] [load(3)]", L"ERROR deleting driver-service", err);
				CloseServiceHandle(manager);
				throw win32_error("DeleteService", err);
			}

			// finally recreate it.
			service = CreateService(manager, m_name.c_str(), m_name.c_str(),
				SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
				m_file.c_str(), NULL, NULL, NULL, NULL, NULL);

			if(!service && (err = GetLastError()) == ERROR_SERVICE_MARKED_FOR_DELETE)
			{
				TRACEW("[driver] [load(3)]    Service marked for delete; trying closing/reopening SCM");
				CloseServiceHandle(manager);
				Sleep(10000);
				manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

				if (!manager)
				{
					TRACEERR("[driver] [load(3)]", L"ERROR while re-opening SCM", err = GetLastError());
					throw win32_error("OpenSCManager 2", err);
				}

				service = CreateService(manager, m_name.c_str(), m_name.c_str(),
					SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
					m_file.c_str(), NULL, NULL, NULL, NULL, NULL);
			}

			if(!service)
			{
				TRACEERR("[driver] [load(3)]", L"ERROR re-creating driver-service", err = GetLastError());
				CloseServiceHandle(manager);
				throw win32_error("CreateService", err);
			}

			TRACEI("[driver] [load(3)]    finished re-creating driver-service");
		}
	}

	SERVICE_STATUS status;
	if(QueryServiceStatus(service, &status))
	{
		if (status.dwCurrentState == SERVICE_RUNNING)
		{
			TRACES("[driver] [load(3)]    Driver-service is running");
			m_started = true;
		}
		else if (status.dwCurrentState == SERVICE_START_PENDING)
		{
			TRACEI("[driver] [load(3)]    Driver-service is starting");
		}
		else
		{
			TRACEI("[driver] [load(3)]    driver-service not running");
			TCHAR buf[128];
			swprintf_s(buf, _countof(buf), L"[driver] [load(3)]    - service state: [%u]", status.dwCurrentState);
			TRACEBUFW(buf);
		}
	}

	CloseServiceHandle(service);
	CloseServiceHandle(manager);

	m_loaded = true;
	TRACEV("[driver] [load(3)]  < Leaving routine.");
}
Exemple #22
0
uint8_t provGetAllWWPNs(prov_wwpn_info_t* io_wwpn_info, uint16_t *io_num_wwpns)
{
    //Locals
    struct cxl_afu_h *l_afu;
    char *l_pci_path = NULL;
    char l_afu_path[DEV_PATH_LENGTH];
    int l_rc = 0;
    uint16_t l_total_wwpns = 0;
    uint16_t l_adapter_wwpn_count = 0;
    prov_adapter_info_t l_adapter_info;
    //Code
    do
    {
        TRACEI("Getting WWPNs\n");
        if((io_num_wwpns == 0) || io_wwpn_info == NULL)
        {
            TRACEI("Buffer is too small, or null!");
            break;
        }
        cxl_for_each_afu(l_afu)
        {
            bzero(l_afu_path, sizeof(l_afu_path));
            l_pci_path = NULL;
            TRACEI("AFU found: '%s'\n", cxl_afu_devname(l_afu));
            //TODO: why do i have to build this myself? should we be
            //always appending the "master" context on the end here?
            snprintf(l_afu_path, sizeof(l_afu_path), "/dev/cxl/%sm", cxl_afu_devname(l_afu));
            l_rc = cxl_afu_sysfs_pci(&l_pci_path, l_afu);
            TRACEI("sysfs rc: %d\n", l_rc);
            TRACEI("sysfs path: '%s'\n", l_pci_path);
            TRACEI("afu path: '%s'\n", l_afu_path);
            l_rc = provGetAdapterInfo(l_pci_path, &l_adapter_info);
            //free the buffer so we can reallocate it next time
            if(l_rc == false)
            {
                //skip - invalid data came back
                TRACEI("Invalid VPD found for this adapter. skipping it.\n");
                continue;
            }
            for(l_adapter_wwpn_count = 0; l_adapter_wwpn_count < MAX_WWPNS_PER_ADAPTER; l_adapter_wwpn_count++)
            {
                TRACEI("Got a wwpn: '%s'\n", l_adapter_info.wwpn[l_adapter_wwpn_count]);
                //io_wwpn_info[l_total_wwpns].afu_path
                
                //zero out the next available element
                bzero(&io_wwpn_info[l_total_wwpns], sizeof(prov_wwpn_info_t));
                strncpy(io_wwpn_info[l_total_wwpns].pci_path, l_pci_path, DEV_PATH_LENGTH);
                strncpy(io_wwpn_info[l_total_wwpns].afu_path, l_afu_path, DEV_PATH_LENGTH);
                io_wwpn_info[l_total_wwpns].port_id = l_adapter_wwpn_count;
                strncpy(io_wwpn_info[l_total_wwpns].wwpn, l_adapter_info.wwpn[l_adapter_wwpn_count], WWPN_BUFFER_LENGTH);
                l_total_wwpns++;
            }
            free(l_pci_path);
            l_pci_path = NULL;
            
        }
        if(l_total_wwpns == 0)
        {
            TRACEI("No wwpns found!\n");
        }
        
        
    } while (0);
    
    *io_num_wwpns = l_total_wwpns;
    
    return 0;
    
}
Exemple #23
0
bool provGetAdapterInfo(const char* i_pci_path, prov_adapter_info_t* o_info)
{
    //Locals
    bool l_rc = true;
    FILE *l_vpd_file = NULL;
    char l_pci_path[DEV_PATH_LENGTH];
    uint8_t l_vpd_buffer[MAX_VPD_SIZE];
    int l_kw_length = 0;
    size_t n=0;
    
    //Code
    do
    {
        TRACEI("Reading WWPN data...\n");
        if((i_pci_path == NULL) ||
           (strlen(i_pci_path) == 0) ||
           (strlen(i_pci_path) > DEV_PATH_LENGTH) ||
           (o_info == NULL))
        {
            TRACEI("Found null or invalid parm!\n");
            l_rc = false;
            break;
        }
        
        bzero(l_pci_path, DEV_PATH_LENGTH);
        bzero(l_vpd_buffer, MAX_VPD_SIZE);
        bzero(o_info, sizeof(prov_adapter_info_t));
        
        //generate the proper VPD path to get VPD
        snprintf(l_pci_path, DEV_PATH_LENGTH, "%s/%s", i_pci_path, "vpd");
        
        TRACEV("Opening up '%s'\n", l_pci_path);
        
        l_vpd_file = fopen(l_pci_path, "rb");
        if (l_vpd_file)
        {
            n = fread(l_vpd_buffer, 1, MAX_VPD_SIZE, l_vpd_file);
        }
        else
        {
            TRACEI("Unable to read file. Do you have permission to open '%s' ?", l_pci_path);
            l_rc = false;
            break;
            // error opening file
        }

        if(n < MAX_VPD_SIZE)
        {
            l_rc = false;
            TRACEI("Warning: Buffer underrun. This indicates a potential VPD format problem.\n");
            break;
        }
        TRACEV("Searching for V5 and V6 KW data...\n");
        l_kw_length = 16;
        l_rc = provFindVPDKw("V5", l_vpd_buffer, n, (uint8_t*)o_info->wwpn[0],&l_kw_length);
        if(l_rc == false)
        {
            TRACEE("Error: Unable to find Port name VPD for Port 1 (VPD KW V5)");
            break;
        }
        l_kw_length = 16;
        l_rc = provFindVPDKw("V6", l_vpd_buffer, n, (uint8_t*)o_info->wwpn[1],&l_kw_length);
        if(l_rc == false)
        {
            TRACEE("Error: Unable to find Port name VPD for Port 1 (VPD KW V5)");
            break;
        }
        //set up the output var
        strcpy(o_info->afu_name, "unknown");
        strncpy(o_info->pci_path, i_pci_path, DEV_PATH_LENGTH);
        //TODO - need fns to get VPD data here and fill it in.
        
        //put data in successfully!
        l_rc = true;
        
    } while (0);
    //close the file on all paths, if it was opened
    if(l_vpd_file)
    {
        fclose(l_vpd_file);
        l_vpd_file = NULL;
    }
    return l_rc;
}
Exemple #24
0
bool loopbackDiag(char* i_afu_path, const AFU_PORT_ID i_port, uint64_t i_test_time_us)
{
    //Locals
    struct cxl_afu_h *afu_master_h = NULL;
    int afu_master_fd = 0;
    uint8_t *afu_psa_addr = NULL;
    uint64_t mmio_data = 0;
    int l_fc_port_offset = 0;
    bool l_rc = true;
    uint64_t l_init_txcount = 0;
    uint64_t l_init_errcount = 0;
    uint64_t l_init_passcount = 0;
    uint64_t l_txcount = 0;
    uint64_t l_errcount = 0;
    uint64_t l_passcount = 0;
    
    //Code
    do
    {
        if(i_port >= MAX_WWPNS_PER_ADAPTER)
        {
            TRACEE("Port number %d is not a valid port number. We only support up to %d numbers.\n", i_port, MAX_WWPNS_PER_ADAPTER);
            l_rc = false;
            break;
        }
        
        l_fc_port_offset = FC_PORT_BASE_OFFSET + (i_port * FC_PORT_REG_SIZE);
        TRACEV("Target reg bank for port %d = 0x%08x\n",i_port, l_fc_port_offset);
        
        TRACEI("Attempting to open device '%s'\n", i_afu_path);
        
        /* now that the AFU is started, lets set config options */
        if ((afu_master_h = cxl_afu_open_dev(i_afu_path)) < 0) {
            TRACEE("Unable to open AFU Master cxl device. errno = %d (%s)\n", errno, strerror(errno));
            l_rc = false;
            break;
        }
        TRACEV("Opened %p, now attempting to get FD\n", afu_master_h);
        afu_master_fd = cxl_afu_fd(afu_master_h);
        TRACEV("Got FD! = %d\n", afu_master_fd);
        
        if (cxl_afu_attach(afu_master_h,
                           0)) //no WEQ needed
        {
            TRACEE("Call to cxl_afu_attach failed. errno = %d (%s)\n", errno, strerror(errno));
            l_rc = false;
            break;
        }
        
        
        afu_psa_addr = mmap_afu_wwpn_registers(afu_master_fd);
        if (!afu_psa_addr) {
            TRACEE("Error attempting to map AFU problem state registers. errno = %d (%s)\n", errno, strerror(errno));
            l_rc = false;
            break;
        }
        
        //Loopback enables a special echo mode and checks tx and rx counts to make sure
        //the phy works correctly. The test is relatively short.
        TRACEI("Enabling loopback mode for adapter %s, port %d\n", i_afu_path, i_port);
        //first read back all test register counts. The AFU does not zero them
        l_init_txcount =   in_mmio64((__u64*)&afu_psa_addr[FC_LOOPBACK_TXCNT + l_fc_port_offset]);
        l_init_errcount =  in_mmio64((__u64*)&afu_psa_addr[FC_LOOPBACK_ERRCNT + l_fc_port_offset]);
        l_init_passcount = in_mmio64((__u64*)&afu_psa_addr[FC_LOOPBACK_PASSCNT + l_fc_port_offset]);


        //enable the test
        mmio_data = in_mmio64((__u64*)&afu_psa_addr[FC_CONFIG2 + l_fc_port_offset]);
        mmio_data |= (uint64_t)0x01 << 40; //set ECHO generator for this port (bit 40)
        out_mmio64((__u64*)&afu_psa_addr[FC_CONFIG2 + l_fc_port_offset], mmio_data);

        TRACEI("Waiting %"PRIu64" microseconds for the test to complete...\n", i_test_time_us);
        usleep(i_test_time_us);
        TRACEI("Disabling loopback mode.\n");
        mmio_data = in_mmio64((__u64*)&afu_psa_addr[FC_CONFIG2 + l_fc_port_offset]);
        mmio_data &= ~((uint64_t)0x01 << 40); //clear ECHO generator for this port (bit 40)
        out_mmio64((__u64*)&afu_psa_addr[FC_CONFIG2 + l_fc_port_offset], mmio_data);

        TRACEI("Waiting for the link to quiesce...\n");
        usleep(LOOPBACK_TEST_QUIET_PERIOD);//wait for quiesce and any final timeouts
        
        //check test results from HW - subtract out initial readings
        l_txcount =   in_mmio64((__u64*)&afu_psa_addr[FC_LOOPBACK_TXCNT + l_fc_port_offset]) - l_init_txcount;
        l_errcount =  in_mmio64((__u64*)&afu_psa_addr[FC_LOOPBACK_ERRCNT + l_fc_port_offset]) - l_init_errcount;
        l_passcount = in_mmio64((__u64*)&afu_psa_addr[FC_LOOPBACK_PASSCNT + l_fc_port_offset]) - l_init_passcount;

        if((l_txcount == 0) || 
           (l_errcount != 0) || 
           (l_txcount != l_passcount))
        {
            TRACED("Loopback diagnostic failure detected. AFU: %s, port: %d, Tx Count: %"PRIu64", Pass Count: %"PRIu64", Error Count: %"PRIu64"\n", i_afu_path, i_port, l_txcount, l_passcount, l_errcount);
            l_rc = false;
        }
        else
        {
            TRACEV("Loopback test passed. AFU: %s, port: %d, Tx Count: %"PRIu64", Pass Count: %"PRIu64", Error Count: %"PRIu64"\n", i_afu_path, i_port, l_txcount, l_passcount, l_errcount);
            l_rc = true;
        }

        //done!
        munmap_afu_wwpn_registers((void *) afu_psa_addr);
        cxl_afu_free(afu_master_h);
        
        
    } while (0);
    
    return l_rc;
    
}
Exemple #25
0
bool initialize_wwpn(char* i_afu_path, const AFU_PORT_ID i_port, const uint64_t i_wwpn)
{
    //Locals
	struct cxl_afu_h *afu_master_h = NULL;
	int afu_master_fd = 0;
	uint8_t *afu_psa_addr = NULL;
    uint32_t mmio_data32 = 0;
    uint64_t mmio_data = 0;
    int l_fc_port_offset = 0; //todo: replace all references with "l_fc_port_offset"
    bool l_rc = 0;
    
    //Code
    do
    {
        if(i_port >= MAX_WWPNS_PER_ADAPTER)
        {
            TRACEE("Port number %d is not a valid port number. We only support up to %d numbers.\n", i_port, MAX_WWPNS_PER_ADAPTER);
            l_rc = false;
            break;
        }
        if(i_wwpn == 0)
        {
            TRACEE("WWPN for %s port %d is zero and therefore invalid.\n", i_afu_path, i_port);
            l_rc = false;
            break;
        }
        
        l_fc_port_offset = FC_PORT_BASE_OFFSET + (i_port * FC_PORT_REG_SIZE);
        TRACEV("Target reg bank for port %d = 0x%08x\n",i_port, l_fc_port_offset);
        
        TRACEI("Attempting to open device '%s'\n", i_afu_path);
        
        /* now that the AFU is started, lets set config options */
        if ((afu_master_h = cxl_afu_open_dev(i_afu_path)) < 0) {
            TRACEE("Unable to open AFU Master cxl device. errno = %d (%s)\n", errno, strerror(errno));
            l_rc = false;
            break;
        }
        TRACEV("Opened %p, now attempting to get FD\n", afu_master_h);
        afu_master_fd = cxl_afu_fd(afu_master_h);
        TRACEV("Got FD! = %d\n", afu_master_fd);
        
        if (cxl_afu_attach(afu_master_h,
                           0)) //no WEQ needed
        {
            TRACEE("Call to cxl_afu_attach failed. errno = %d (%s)\n", errno, strerror(errno));
            l_rc = false;
            break;
        }
        
        
        afu_psa_addr = mmap_afu_wwpn_registers(afu_master_fd);
        if (!afu_psa_addr) {
            TRACEE("Error attempting to map AFU problem state registers. errno = %d (%s)\n", errno, strerror(errno));
            l_rc = -1;
            break;
        }
        
        //Take port offline
        
        //TRACED("Bringing port offline\n");

        
        //get status bits for debug
        //TODO: maybe wrap up this print into a nice macro...
        mmio_data32 = in_mmio32((__u64*)&afu_psa_addr[FC_MTIP_STATUS + l_fc_port_offset]);
        TRACEV("FC_MTIP_STATUS    (0x%08X): 0x%08X\n", FC_MTIP_STATUS + l_fc_port_offset, mmio_data32);
        mmio_data32 = in_mmio32((__u64*)&afu_psa_addr[FC_MTIP_CMDCONFIG + l_fc_port_offset]);
        TRACEV("FC_MTIP_CMDCONFIG (0x%08X): 0x%08X\n", FC_MTIP_CMDCONFIG + l_fc_port_offset, mmio_data32);
        mmio_data32 &= ~0x20; // clear ON_LINE
        mmio_data32 |= 0x40;  // set OFF_LINE
        TRACEV("FC_MTIP_CMDCONFIG: Proposed:    0x%08X\n", mmio_data32);
        out_mmio32((__u64*)&afu_psa_addr[FC_MTIP_CMDCONFIG + l_fc_port_offset], mmio_data32);
        
        //wait for the port to be offline
        l_rc = wait_port_state(afu_psa_addr, l_fc_port_offset, false);
        if(l_rc == false)
        {
            TRACEE("Port not offline in time. Aborting.\n");
            l_rc = -1;
            break;
        }
        
        //now we know we are offline, so write the PN...
        
        
        //read out the current PN
        //PN register is 64-bit as per spec
        mmio_data = in_mmio64((__u64*)&afu_psa_addr[FC_PNAME + l_fc_port_offset]);
        TRACEV("FC_PNAME:         (0x%08X): 0x%"PRIx64"\n",FC_PNAME + l_fc_port_offset, mmio_data);
        TRACEI("Current Port Name is  0x%"PRIx64"\n", mmio_data);
        
        mmio_data = i_wwpn;
        TRACEI("New Port Name will be 0x%"PRIx64"\n", mmio_data);
        
        out_mmio64((__u64*)&afu_psa_addr[FC_PNAME + l_fc_port_offset], mmio_data);
        
        //bring the port back online
        //read control bits...
        mmio_data32 = in_mmio32((__u64*)&afu_psa_addr[FC_MTIP_CMDCONFIG + l_fc_port_offset]);
        TRACEV("FC_MTIP_CMDCONFIG (0x%08X): 0x%08X\n", FC_MTIP_CMDCONFIG + l_fc_port_offset, mmio_data32);
        mmio_data32 |= 0x20; // set ON_LINE
        mmio_data32 &= ~0x40;  // clear OFF_LINE
                               //TODO: ask todd - should we explicitly-set other bits? I needed to force the port into FC mode (set bit 1)
        //net result is we write 0x23 to the lowest byte
        TRACEV("FC_MTIP_CMDCONFIG: Proposed:    0x%08X\n", mmio_data32);
        out_mmio32((__u64*)&afu_psa_addr[FC_MTIP_CMDCONFIG + l_fc_port_offset], mmio_data32);
        
        //wait for the port to be online
        l_rc = wait_port_state(afu_psa_addr, l_fc_port_offset, true);
        if(l_rc == false)
        {
            TRACEE("Port not online in time.\n");
            l_rc = -1;
            break;
        }
        
        //done!
        munmap_afu_wwpn_registers((void *) afu_psa_addr);
        cxl_afu_free(afu_master_h);
        
        
        
        TRACEI("Successfully programmed WWPN!\n");
        l_rc = true;
        
    } while (0);
    
	return l_rc;
    
}