Beispiel #1
0
static void ui_answer_call()
{
    pjsua_call_info call_info;
    char buf[128];
    pjsua_msg_data msg_data;

    if (current_call != -1) {
	pjsua_call_get_info(current_call, &call_info);
    } else {
	/* Make compiler happy */
	call_info.role = PJSIP_ROLE_UAC;
	call_info.state = PJSIP_INV_STATE_DISCONNECTED;
    }

    if (current_call == -1 ||
	call_info.role != PJSIP_ROLE_UAS ||
	call_info.state >= PJSIP_INV_STATE_CONNECTING)
    {
	puts("No pending incoming call");
	fflush(stdout);
	return;

    } else {
	int st_code;
	char contact[120];
	pj_str_t hname = { "Contact", 7 };
	pj_str_t hvalue;
	pjsip_generic_string_hdr hcontact;

	if (!simple_input("Answer with code (100-699)", buf, sizeof(buf)))
	    return;

	st_code = my_atoi(buf);
	if (st_code < 100)
	    return;

	pjsua_msg_data_init(&msg_data);

	if (st_code/100 == 3) {
	    if (!simple_input("Enter URL to be put in Contact",
		contact, sizeof(contact)))
		return;
	    hvalue = pj_str(contact);
	    pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue);

	    pj_list_push_back(&msg_data.hdr_list, &hcontact);
	}

	/*
	* Must check again!
	* Call may have been disconnected while we're waiting for
	* keyboard input.
	*/
	if (current_call == -1) {
	    puts("Call has been disconnected");
	    fflush(stdout);
	    return;
	}

	pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data);
    }
}
Beispiel #2
0
__declspec(dllexport) void download (HWND   parent,
              int    string_size,
              char   *variables,
              nsis_stack_t **stacktop)
{
  char buf[1024];
  char url[1024];
  char filename[1024];
  static char proxy[1024];
  BOOL bSuccess=FALSE;
  int timeout_ms=30000;
  int getieproxy=1;
  int manualproxy=0;
  int translation_version;

  char *error=NULL;

  // translation version 2 & 1
  static char szDownloading[1024]; // "Downloading %s"
  static char szConnecting[1024];  // "Connecting ..."
  static char szSecond[1024];      // " (1 second remaining)" for v2
                                   // "second" for v1
  static char szMinute[1024];      // " (1 minute remaining)" for v2
                                   // "minute" for v1
  static char szHour[1024];        // " (1 hour remaining)" for v2
                                   // "hour" for v1
  static char szProgress[1024];    // "%skB (%d%%) of %skB at %u.%01ukB/s" for v2
                                   // "%dkB (%d%%) of %dkB at %d.%01dkB/s" for v1

  // translation version 2 only
  static char szSeconds[1024];     // " (%u seconds remaining)"
  static char szMinutes[1024];     // " (%u minutes remaining)"
  static char szHours[1024];       // " (%u hours remaining)"

  // translation version 1 only
  static char szPlural[1024];      // "s";
  static char szRemaining[1024];   // " (%d %s%s remaining)";

  EXDLL_INIT();

  popstring(url);
  if (!lstrcmpi(url, "/TRANSLATE2")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szSeconds);
    popstring(szMinutes);
    popstring(szHours);
    popstring(szProgress);
    popstring(url);
    translation_version=2;
  } else if (!lstrcmpi(url, "/TRANSLATE")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szPlural);
    popstring(szProgress);
    popstring(szRemaining);
    popstring(url);
    translation_version=1;
  } else {
    lstrcpy(szDownloading, "Downloading %s");
    lstrcpy(szConnecting, "Connecting ...");
    lstrcpy(szSecond, " (1 second remaining)");
    lstrcpy(szMinute, " (1 minute remaining)");
    lstrcpy(szHour, " (1 hour remaining)");
    lstrcpy(szSeconds, " (%u seconds remaining)");
    lstrcpy(szMinutes, " (%u minutes remaining)");
    lstrcpy(szHours, " (%u hours remaining)");
    lstrcpy(szProgress, "%skB (%d%%) of %skB at %u.%01ukB/s");
    translation_version=2;
  }
  lstrcpyn(buf, url, 10);
  if (!lstrcmpi(buf, "/TIMEOUT=")) {
    timeout_ms=my_atoi(url+9);
    popstring(url);
  }
  if (!lstrcmpi(url, "/PROXY")) {
    getieproxy=0;
    manualproxy=1;
    popstring(proxy);
    popstring(url);
  }
  if (!lstrcmpi(url, "/NOIEPROXY")) {
    getieproxy=0;
    popstring(url);
  }
  popstring(filename);

  HANDLE hFile = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

  if (hFile == INVALID_HANDLE_VALUE)
  {
    wsprintf(buf, "Unable to open %s", filename);
    error = buf;
  }
  else
  {
    if (parent)
    {
      uMsgCreate = RegisterWindowMessage("nsisdl create");

      lpWndProcOld = (void *)SetWindowLong(parent,GWL_WNDPROC,(long)ParentWndProc);

      SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent);

      // set initial text
      char *p = filename;
      while (*p) p++;
      while (*p != '\\' && p != filename) p = CharPrev(filename, p);
      wsprintf(buf, szDownloading, p != filename ? p + 1 : p);
      SetDlgItemText(childwnd, 1006, buf);
      SetWindowText(g_hwndStatic, szConnecting);
    }
    {
      WSADATA wsaData;
      WSAStartup(MAKEWORD(1, 1), &wsaData);

      JNL_HTTPGet *get = 0;

      static char main_buf[8192];
      char *buf=main_buf;
      char *p=NULL;

      HKEY hKey;
      if (getieproxy && RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
        DWORD l = 4;
        DWORD t;
        DWORD v;
        if (RegQueryValueEx(hKey,"ProxyEnable",NULL,&t,(unsigned char *)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
        {
          l=8192;
          if (RegQueryValueEx(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
          {
            p=strstr(buf,"http=");
            if (!p) p=buf;
            else {
              p+=5;
            }
            char *tp=strstr(p,";");
            if (tp) *tp=0;
            char *p2=strstr(p,"=");
            if (p2) p=0; // we found the wrong proxy
          }
        }
        buf[8192-1]=0;
        RegCloseKey(hKey);
      }
      if (manualproxy == 1) {
        p = proxy;
      }

      DWORD start_time=GetTickCount();
      get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
      int         st;
      int         has_printed_headers = 0;
      __int64     cl = 0;
      int         len;
      __int64     sofar = 0;
      DWORD last_recv_time=start_time;

      get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
      get->addheader ("Accept: */*");

      get->connect (url);

      while (1) {
        if (g_cancelled)
            error = "cancel";

        if (error)
        {
          if (parent)
          {
            SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent);
            SetWindowLong(parent, GWL_WNDPROC, (long)lpWndProcOld);
          }
          break;
        }

        st = get->run ();

        if (st == -1) {
          lstrcpyn(url, get->geterrorstr(), sizeof(url));
          error = url;
        } else if (st == 1) {
          if (sofar < cl || get->get_status () != 2)
            error="download incomplete";
          else
          {
            bSuccess=TRUE;
            error = "success";
          }
        } else {

          if (get->get_status () == 0) {
            // progressFunc ("Connecting ...", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on connecting.";
            else
              Sleep(10); // don't busy-loop while connecting

          } else if (get->get_status () == 1) {

            progress_callback("Reading headers", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on getting headers.";
            else
              Sleep(10); // don't busy-loop while reading headers

          } else if (get->get_status () == 2) {

            if (! has_printed_headers) {
              has_printed_headers = 1;
              last_recv_time=GetTickCount();

              cl = get->content_length ();
              if (cl == 0)
                error = "Server did not specify content length.";
              else if (g_hwndProgressBar) {
                SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000));
                g_file_size = cl;
              }
            }

            int data_downloaded = 0;
            while ((len = get->bytes_available ()) > 0) {
              data_downloaded++;
              if (len > 8192)
                len = 8192;
              len = get->get_bytes (buf, len);
              if (len > 0) {
                last_recv_time=GetTickCount();
                DWORD dw;
                WriteFile(hFile,buf,len,&dw,NULL);
                sofar += len;
                int time_sofar=(GetTickCount()-start_time)/1000;
                int bps = (int)(sofar/(time_sofar?time_sofar:1));
                int remain = MulDiv64(time_sofar, cl, sofar) - time_sofar;

                if (translation_version == 2) {
                  char *rtext=remain==1?szSecond:szSeconds;;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=remain==1?szMinute:szMinutes;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=remain==1?szHour:szHours;
                    }
                  }

                  char sofar_str[128];
                  char cl_str[128];
                  myitoa64(sofar/1024, sofar_str);
                  myitoa64(cl/1024, cl_str);

                  wsprintf (buf,
                        szProgress, //%skB (%d%%) of %skB @ %u.%01ukB/s
                        sofar_str,
                        MulDiv64(100, sofar, cl),
                        cl_str,
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintf(buf+lstrlen(buf),rtext,
                        remain
                        );
                } else if (translation_version == 1) {
                  char *rtext=szSecond;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=szMinute;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=szHour;
                    }
                  }

                  wsprintf (buf,
                        szProgress, //%dkB (%d%%) of %dkB @ %d.%01dkB/s
                        int(sofar/1024),
                        MulDiv64(100, sofar, cl),
                        int(cl/1024),
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintf(buf+lstrlen(buf),szRemaining,
                        remain,
                        rtext,
                        remain==1?"":szPlural
                        );
                }
                progress_callback(buf, sofar);
              } else {
                if (sofar < cl)
                  error = "Server aborted.";
              }
            }
            if (GetTickCount() > last_recv_time+timeout_ms)
            {
              if (sofar != cl)
              {
                error = "Downloading timed out.";
              }
              else
              {
                // workaround for bug #1713562
                //   buggy servers that wait for the client to close the connection.
                //   another solution would be manually stopping when cl == sofar,
                //   but then buggy servers that return wrong content-length will fail.
                bSuccess = TRUE;
                error = "success";
              }
            }
            else if (!data_downloaded)
              Sleep(10);

          } else {
            error = "Bad response status.";
          }
        }

      }

      // Clean up the connection then release winsock
      if (get) delete get;
      WSACleanup();
    }

    CloseHandle(hFile);
  }

  if (g_cancelled || !bSuccess) {
    DeleteFile(filename);
  }

  pushstring(error);
}
Beispiel #3
0
static void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
	switch (id)
	{
		case IDOK:
			EndDialog(hwnd, 1);
			break;

		case IDCANCEL:
			EndDialog(hwnd, 0);
			break;

		case IDC_TYPE_TABLE:
		case IDC_TYPE_INDEX:
			if (codeNotify == BN_CLICKED) {

				SetProp(hwnd, szErrorProp, (HANDLE)ERROR_NOSHOW);

				Adjust4FillFactors(hwnd);
				InitialiseSpinControls (hwnd);
				LimitNumericEditControls(hwnd);


				DoCalculation(hwnd);

				SetProp(hwnd, szErrorProp, (HANDLE)ERROR_SHOW);
			}
			break;

		case IDC_CLEAR:
			InitialiseSpinControls(hwnd);
			InitialiseEditControls(hwnd);
			UpdateControls(hwnd,TRUE);
			Adjust4FillFactors(hwnd);
			bUserChangeEdit = FALSE;
			break;

		case IDC_PAGESIZE:
			switch (codeNotify)
			{
				case CBN_SELCHANGE:

				// Inhibit error messages while we are updating since
				// the EN_CHANGE message causes all the edit controls to be
				// verified for this structure type,  even the controls that
				// have not been reinitialised yet.

				SetProp(hwnd, szErrorProp, (HANDLE)ERROR_NOSHOW);

				Adjust4FillFactors(hwnd);
				InitialiseSpinControls (hwnd);
				LimitNumericEditControls(hwnd);


				DoCalculation(hwnd);

				SetProp(hwnd, szErrorProp, (HANDLE)ERROR_SHOW);
				break;
			}
		break;

		case IDC_STRUCTURE:
			switch (codeNotify)
			{
				case CBN_SELCHANGE:

					// Inhibit error messages while we are updating since
					// the EN_CHANGE message causes all the edit controls to be
					// verified for this structure type,  even the controls that
					// have not been reinitialised yet.

					SetProp(hwnd, szErrorProp, (HANDLE)ERROR_NOSHOW);

					InitialiseSpinControls(hwnd);
					ResetWithDefaultEditCtrl(hwnd);
					//InitialiseEditControls(hwnd);
					UpdateControls(hwnd,FALSE);
					DoCalculation(hwnd);

					SetProp(hwnd, szErrorProp, (HANDLE)ERROR_SHOW);
					break;

				case CBN_KILLFOCUS:
				{
					// We must verify the edit controls on exiting the
					// structure field since we dont do any checking when
					// it gets the focus,  therefore an edit control could
					// be invalid.

					VerifyAllNumericEditControls(hwnd, TRUE, TRUE);
					break;
				}
			}
			break;

		case IDC_ROWS:
		case IDC_ROWWIDTH:
		case IDC_UNIQUEKEYS:
		case IDC_KEYWIDTH:
		case IDC_DATA:
		case IDC_INDEX:
		case IDC_LEAF:
		{
			switch (codeNotify)
			{
				case EN_CHANGE:
				{
					int nCount;
					BOOL bShowError = (GetProp(hwnd, szErrorProp) == (HANDLE)ERROR_NOSHOW) ? FALSE : TRUE;

					if (id == IDC_DATA
					 || id == IDC_INDEX
					 || id == IDC_LEAF
					 || id == IDC_ROWWIDTH)
					{
						// Do this even on INITDIALOG
						Adjust4FillFactors(hwnd);
					}

					if (!IsWindowVisible(hwnd))
						break;

					// Test to see if the control is empty. If so then
					// set ERROR and break out.  It becomes tiresome to edit
					// if you delete all characters and an error box pops up.

					nCount = Edit_GetTextLength(hwndCtl);
					if (nCount == 0)
					{
						SetCalcError(hwnd);
						break;
					}
					if (!bInitEdit && (   id == IDC_DATA
					                   || id == IDC_INDEX
					                   || id == IDC_LEAF ))
					{
						char szBuf[20];
						INFOOFFSET infoIdx = GetSelectedStructure(hwnd);
						int nData,nIndex,nLeaf;
						GetDlgItemText (hwnd, IDC_DATA, szBuf, sizeof (szBuf));
						nData = my_atoi(szBuf);

						GetDlgItemText (hwnd, IDC_INDEX, szBuf, sizeof (szBuf));
						nIndex = my_atoi(szBuf);

						GetDlgItemText (hwnd, IDC_LEAF, szBuf, sizeof (szBuf));
						nLeaf = my_atoi(szBuf);

						if ( SaveFillFactors.FillFactors.nData != nData)
						{
							SaveFillFactors.FillFactors.nData = nData;
							SaveFillFactors.DefaultData = infoDefaults[infoIdx].fillFactors.nData;
							bUserChangeEdit = TRUE;
						}
						if ( SaveFillFactors.FillFactors.nIndex != nIndex)
							SaveFillFactors.FillFactors.nIndex = nIndex;
						if ( SaveFillFactors.FillFactors.nLeaf != nLeaf)
							SaveFillFactors.FillFactors.nLeaf = nLeaf;
					}

					if (!VerifyAllNumericEditControls(hwnd, bShowError, TRUE))
						break;

					DoCalculation(hwnd);
					break;
				}

				case EN_KILLFOCUS:
				{
					HWND hwndNew = GetFocus();
					int nNewCtl = GetDlgCtrlID(hwndNew);

					if (!IsEditControl(hwnd, hwndNew)
					 || !IsChild(hwnd, hwndNew))
						// Dont recalc on any button hits or change of structure
						// or error message displays
						break;

					if (!VerifyAllNumericEditControls(hwnd, TRUE, TRUE))
						break;

					UpdateSpinButtons(hwnd);
					DoCalculation(hwnd);
					break;
				}
			}
			break;
		}

		case IDC_SPINROWWIDTH:
		case IDC_SPINKEYWIDTH:
		case IDC_SPINROWS:
		case IDC_SPINKEYS:
		case IDC_SPINDATA:
		case IDC_SPINIDX:
		case IDC_SPINLEAF:
		{
			// Handle the spin button notifications

			switch (codeNotify)
			{
				case SN_INCBUTTONUP:
				case SN_DECBUTTONUP:
				{
					switch (id)
					{
						case IDC_SPINDATA:
						case IDC_SPINIDX:
						case IDC_SPINLEAF:
						{
							// Set for no error display so we do not get
							// errors in the row width while decreasing the
							// fillfactors and therefore lowering the row
							// width maximum.  The edit box will just adjust
							// to the new maximum without showing an error.

							SetProp(hwnd, szErrorProp, (HANDLE)ERROR_NOSHOW);
							if (id == IDC_SPINDATA)
								bUserChangeEdit = TRUE;
						}
					}

					if (ProcessSpinControl(hwndCtl, codeNotify, limits))
						DoCalculation(hwnd);

					SetProp(hwnd, szErrorProp, (HANDLE)ERROR_SHOW);
					break;
				}

				default:
					ProcessSpinControl(hwndCtl, codeNotify, limits);
			}
			break;
		}
	}
}
Beispiel #4
0
int pccmdline(void)
{
  int p;
  int gfnm=0;

  for(p=1;p<argc;p++)
  {
 /*
    printf("(%i/%i): %s\n",p,argc,argv[p]);
 */
          
    if((argv[p][0] == '-') || (argv[p][0] == '/'))
    {
      int hasroom=0;
      int pp=1;
      int cp=p;
      int nn='_';
      for(pp=1;argv[cp][pp];pp++)
      {
        if( (p+1) < argc) hasroom=1;
        nn=tolower(argv[cp][pp+1]);
        switch(tolower(argv[cp][pp]))
        {
        case '1': /* Player 1 Input */
        {
          if(!hasroom) return 4;
          pl1contrl=my_atoi(argv[p+1]);
          if(pl1contrl > 6) return 15;
          p++;
          ConvertJoyMap1();
          break;
        }
        case '2': /* Player 2 Input */
        {
          if(!hasroom) return 4;
          pl2contrl=my_atoi(argv[p+1]);
          if(pl2contrl > 6) return 15;
          p++;
          ConvertJoyMap2();
          break;
        }
        case '3':
        {
          vsyncon=0;
          Triplebufen=1;
          p++;
          break;
        }
        case 'f':
        {
          if(!hasroom) return 4;
          frameskip=my_atoi(argv[p+1]);
          if(frameskip > 9) return 10;
          frameskip++;
          p++;
          break;
        }
        case 'g': 
        {
          if(!hasroom) return 4;
          gammalevel=my_atoi(argv[p+1]);
          if(gammalevel > 15) return 11;
          p++;
          break;
        }
        case 'p': 
        {
          if(!hasroom) return 4;
          per2exec=my_atoi(argv[p+1]);
          if(per2exec > 150) return 14;
          if(per2exec < 50) return 14;
          p++;
          break;
        }
        case 'r': 
        {
          if(!hasroom) return 4;
          SoundQuality=my_atoi(argv[p+1]);
          if(SoundQuality > 6) return 12;
          p++;
          break;
        }
        case 'v': 
        {
          if(nn == '8')
          {
            V8Mode=1;
            pp++;
          }
          else
          {
            if(!hasroom) return 4;
            cvidmode=my_atoi(argv[p+1]);
            if(cvidmode > 14) return 13;
            p++;
          }
          break;
        }
        case 'k': 
        {
          if(!hasroom) return 4;
          MusicRelVol=my_atoi(argv[p+1]);
          if(MusicRelVol > 100) return 16;
          p++;
          break;
        }
        case '8':
        {
          Force8b=1;
          break;
        }
        case '0': /* Palette 0 disable */
        {
          Palette0=1;
          break;
        }
        case '7': /* SPC700 speed hack disable */
        {
          SPC700sh=1;
          break;
        }
        case '9': /* Off by 1 line */
        {
          OffBy1Line=1;
          break;
        }
        case 'e':
        {
          enterpress=1;
          break;            
        }
        case 'h':
        {
          romtype=2;
          break;
        }
        case 'l':
        {
          romtype=1;
          break;
        }
        case 'm':
        {
          guioff=1; /* disables GUI */
          break;
        }
        case 'n':
        {
          if(!hasroom) return 4;
          scanlines=my_atoi(argv[p+1]);
          p++;
          break;
        }
        case 's':
        {
          if(nn == 'p')
          {
            DisplayS=1;
            pp++;
          }
          else
          if(nn == 'a')
          {
            showallext=1;
            pp++;
          }
          else
          if(nn == 'n')
          {
            SnowOn=1;
            pp++;
          }
          else
          {
            spcon=1;
            soundon=1;
          }
          break;
        }
        case 't':
        {
          ForcePal=1;
          break;
        }
        case 'u':
        {
          ForcePal=2;
          break;
        }
        case 'w':
        {
          Triplebufen=0;
          vsyncon=1;
          break;
        }
        case 'z':
        {
          // FIX STATMAT
          if(nn == 's')
          {				
            if(!hasroom) return 4;
            autoloadstate=my_atoi(argv[p+1]) + 1;
            p++;
          }
          else StereoSound=0;
          // FIX STATMAT
          break;
        }
        case 'd':
        {
          if(nn == 'd')
          {
            DSPDisable=1;
            pp++;
          }
          else
          {
            debugger=1;
            debugdisble=0;
          }
          break;
        }
        case 'c':
        {
          if(nn == 'c')
          {
            smallscreenon=1;
            pp++;
          }
          else
          {
            ScreenScale=1;
          }
          break;
        }

        case 'y':
        {
          antienab=1;
          break;
        }
        case 'o':
        {
          if(nn == 'm')
          {
            MMXSupport=1;
            pp++;
          }
          else
          {
            MMXSupport=0;
          }
          break;
        }
        case 'i':
        {
          finterleave=1;
          break;
        }
        case 'j':
        {
          GUIClick=0;
          MouseDis=1;
          break;
        }
        case '?':
        {
          return 9;
        }
        }
                                                    
      }
      
    }
    else
    {
      if(gfnm > 0)
      {
        printf("Limit yourself to one filename\n");
        return 2;
      }
      else
      {
        char *fvar;
        fvar=&fname;
        fvar[0] = strlen(argv[p]);
        strncpy(&fvar[1],argv[p],127);
        gfnm++;
      }
    }
  }
  if(gfnm == 1)
  {
    filefound=0;
    makeextension();
  }
  return 0;
}
Beispiel #5
0
int		ask_game(t_match *line)
{
  my_putstr("\nMode one player (1)\nTwo player (2)\nExit program (3): ");
  line->player = my_atoi(get_next_line(0));
}
Beispiel #6
0
int main(int argc, char * * argv)
{
    printf("Welcome to PA02.\n"
	   "\n"
	   "You are encouraged to edit this file in order to test\n"
	   "the behavior of the functions you write in answer02.c\n"
	   "\n"
	   "This file will not be marked, and should not be\n"
	   "submitted.\n"
	   "\n"
	   "Don't forget to post questions on blackboard, and ask\n"
	   "the TAs and your classmates for help.\n"
	   "\n");

    const char * s1 = "Hello World!";
    const char * s2 = "";
    const char * s3 = "foo";

    // -- my_strlen, should be: 12, 0, and 3
    printf("my_strlen(\"%s\") = %d\n", s1, (int) my_strlen(s1));
    printf("my_strlen(\"%s\") = %d\n", s2, (int) my_strlen(s2));
    printf("my_strlen(\"%s\") = %d\n", s3, (int) my_strlen(s3));

    // -- my_countchar, should be: 3, 0, and 2
    printf("my_countchar(\"%s\", 'l') = %d\n", s1, (int) my_countchar(s1, 'l'));
    printf("my_countchar(\"%s\", 'o') = %d\n", s2, (int) my_countchar(s2, 'o'));
    printf("my_countchar(\"%s\", 'o') = %d\n", s3, (int) my_countchar(s3, 'o'));

    // -- my_strchr, should be: "llo World!", "(null)", and ""
    printf("my_strchr(\"%s\", 'l') = %s\n", s1, my_strchr(s1, 'l'));
    printf("my_strchr(\"%s\", 'o') = %s\n", s2, my_strchr(s2, 'o'));
    printf("my_strchr(\"%s\", '\\0') = %s\n", s3, my_strchr(s3, '\0'));

    // -- my_strrchr, should be: "lo World!", "(null)", and ""
    printf("my_strrchr(\"%s\", 'o') = %s\n", s1, my_strrchr(s1, 'o'));
    printf("my_strrchr(\"%s\", 'z') = %s\n", s1, my_strrchr(s1, 'z'));
    printf("my_strrchr(\"%s\", '\\0') = %s\n", s1, my_strrchr(s1, '\0'));

    // -- my_strstr, should be: "World!", "Hello World!", "(null)"
    printf("my_strstr(\"%s\", \"World\") = %s\n", s1, my_strstr(s1, "World"));
    printf("my_strstr(\"%s\", \"\") = %s\n", s1, my_strstr(s1, ""));
    printf("my_strstr(\"%s\", \"hello\") = %s\n", s1, my_strstr(s1, "hello"));

    // -- my_strcpy. For this function you need a buffer where you
    // copy the string to. 
    char buffer[BUFFER_LEN];
    my_strcpy(buffer, s1);
    printf("my_strcpy(buffer, \"%s\"), buffer = \"%s\"\n", s1, buffer);
    my_strcpy(buffer, s2);
    printf("my_strcpy(buffer, \"%s\"), buffer = \"%s\"\n", s2, buffer);
    my_strcpy(buffer, s3);
    printf("my_strcpy(buffer, \"%s\"), buffer = \"%s\"\n", s3, buffer);

    // -- my_strcat. You will have to do this yourself... just
    // look at my_strcpy for an example, and go from there.
    my_strcpy(buffer, "Hello ");
    printf("%s\n", my_strcat(buffer, "Zippy!")); // prints "Hello Zippy!"
    my_strcpy(buffer, "");
    printf("%s\n", my_strcat(buffer, "Hello!")); // prints ("Hello!")   

    // -- my_isspace. You will have to do this for yourself.
    printf("my_isspace('\\n') = %d\n", my_isspace(' '));
    printf("my_isspace('\\f') = %d\n", my_isspace('\f'));
    printf("my_isspace('\\r') = %d\n", my_isspace('\r'));
    printf("my_isspace('\\t') = %d\n", my_isspace('\t'));
    printf("my_isspace('n') = %d\n", my_isspace('l'));

    // -- my_atoi. You will have to do this for yourself.
    printf("my_atoi(\"0\") = %d\n", my_atoi("0")); // 0
    printf("my_atoi(\"-12\") = %d\n", my_atoi("-12")); // -12
    printf("my_atoi(\"15th of March would be the ides.\") = %d\n", my_atoi("15th of March would be the ides.")); // 15
    printf("my_atoi(\"4 months to Summer.\") = %d\n", my_atoi("4 months to Summer.")); // 4
    printf("my_atoi(\"\\n\\f\\t\\v\\r 6 white space characters handled correctly.\") = %d\n", my_atoi("\n\f\t\v\r 6 white space characters handled correctly.")); // 6
    printf("my_atoi(\"garbage should yield 0\") = %d\n", my_atoi("garbage should yield 0")); // 0

    return EXIT_SUCCESS;
}
Beispiel #7
0
int main(int argc, char *argv[])
{
    int sockfd, portno, n, bytesRead, running;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    fd_set master, readfd;

    char *buffer, *nickname;

    buffer = (char *)malloc(sizeof(char) * 256);
    running = 1;
    if (argc < 3) 
    {
       my_str("Usage: /client host port\n");
       exit(1);
    }

    portno = my_atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sockfd < 0) 
        error("ERROR opening socket");

    server = gethostbyname(argv[1]);

    if (server == NULL) 
    {
        my_str("No host with that name found!\n");
        exit(1);
    }

    my_bzero((char *) &serv_addr, sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;

    my_bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);

    serv_addr.sin_port = htons(portno);

    my_bzero(buffer, 256);
    my_str("Please enter your nickname: ");
    bytesRead = read(0, buffer, 255);
    buffer = inputClean(buffer);
    my_str("\n> ");

    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
        error("ERROR connecting");

    if (write(sockfd, buffer, my_strlen(buffer)) < 0) /* write username */
        error("write() error!\n");

    FD_ZERO(&master);
    FD_ZERO(&readfd);

    FD_SET(sockfd, &master);
    FD_SET(0, &master);
    
    while(running == 1)
    {
        readfd = master;
        if(select(sockfd + 1, &readfd, NULL, NULL, NULL) < 0)
            error("Select() failed\n");

        if(FD_ISSET(0, &readfd)) /* reading from console */
        {
            my_bzero(buffer, 256);
            my_str("> ");
            bytesRead = read(0, buffer, 255);

            if (bytesRead < 0)
                error("read() error!\n");
            buffer = inputClean(buffer);
            buffer[bytesRead] = '\0';

            if (my_strcmp(buffer, "/exit") == 0)
            {
                my_str("Disconnecting from server.\n");
                close(sockfd);
                exit(0);
            }
            else if (write(sockfd, buffer, my_strlen(buffer)) < 0)
                error("write() error!\n");
        }
        else if(FD_ISSET(sockfd, &readfd)) /* reading from server */
        {
            my_bzero(buffer, 256);
            bytesRead = read(sockfd, buffer, 255);

            if (bytesRead < 0)
                error("read() from server error!\n");
            else if (bytesRead == 0)
            {
                my_str("Connection to server interrupted!\n");
                close(sockfd);
                exit(0);
            }
            else
            {
                my_char('\n');
                buffer[bytesRead] = '\0';
                my_str(buffer);
                my_char('\n');
                my_str("> ");
            }
        }
    }
    return 0;
}
Beispiel #8
0
int ICACHE_FLASH_ATTR CustomCommand(char * buffer, int retsize, char *pusrdata, unsigned short len)
{
	char * buffend = buffer;

	switch( pusrdata[1] )
	{
	case 'C': case 'c': //Custom command test
	{
		buffend += ets_sprintf( buffend, "CC\n" );
		return buffend-buffer;
	}
	case 'A': case 'a': //AVR Commands
	{
		switch( pusrdata[2] )
		{
		case 'R': case 'r': 
		{
			buffend += ets_sprintf( buffend, "AR\n" );
			return buffend-buffer;
		}
		case 'F': case 'f': 
		{
			int i;
			char     md5h[48];
			char     md5hraw[48];
			MD5_CTX md5ctx;
			char * colon = (char *) ets_strstr( (char*)&pusrdata[3], "\t" );
			char * colon2 = (colon)?((char *)ets_strstr( (char*)(colon+1), "\t" )):0;

			if( !colon || !colon2 ) break;

			*colon = 0; colon++;
			*colon2 = 0; colon2++;


			uint32_t from = my_atoi( &pusrdata[3] );
			uint32_t len = my_atoi( colon );
			char * md5 = colon2;

			printf( "caffer %d %d %s\n", from, len, md5 );
			MD5Init( &md5ctx );
			if( keylen )
				MD5Update( &md5ctx, key, keylen );
			SafeMD5Update( &md5ctx, (uint8_t*)0x40200000 + from, len );
			MD5Final( md5hraw, &md5ctx );

			for( i = 0; i < 16; i++ )
			{
				ets_sprintf( md5h+i*2, "%02x", md5hraw[i] );
			}

			printf( "AVR Program MD5s: %s == %s\n", md5h, md5 );
			for( i = 0; i < 32; i++ )
			{
				if( md5[i] != md5h[i] )
				{
					break;
				}
			}

			if( i != 32 ) break;

			int r = ProgramAVRFlash( (uint8_t*)0x40200000+from, len );

			if( r )
			{
				buffend += ets_sprintf( buffend, "!CAF\t%d\r\n", r );
			}
			else
			{
				buffend += ets_sprintf( buffend, "CAF\r\n" );
			}

			return buffend-buffer;
		}
		default: break;
		}
		buffend += ets_sprintf( buffend, "!CA%c\t-99\r\n", pusrdata[2] );
		return buffend-buffer;
	}

	}
	return -1;
}
Beispiel #9
0
int prs_flt_timelimit(struct linked_list_opt_value *optl, char *val)
{
	timelimit.tv_sec = my_atoi(val,10);
	timelimit.tv_usec = 500;
	return OPT_OK;
}
Beispiel #10
0
/* Initializes the block_list with info from a netlist */
void
read_netlist(IN const char *net_file,
	     IN int num_types,
	     IN const struct s_type_descriptor block_types[],
	     IN t_type_ptr IO_type,
	     IN int io_ipin,
	     IN int io_opin,
	     OUT t_subblock_data * subblock_data_ptr,
	     OUT int *num_blocks,
	     OUT struct s_block *block_list[],
	     OUT int *num_nets,
	     OUT struct s_net *net_list[])
{

    FILE *infile;
    int bcount;
    struct s_block *blist;
    int ncount;
    struct s_net *nlist;

    int i, j, k, l, m;
    enum
    { COUNT, LOAD, MAP, STOP }
    pass;
    int line, prev_line;
    enum special_blk overide;
    char **block_tokens;
    char **pin_tokens;
    char **tokens;
    t_subblock **slist = NULL;
    int *scount = NULL;
    t_type_ptr type = NULL;


    infile = my_fopen(net_file, "r");
    bcount = 0;
    blist = NULL;
    ncount = 0;
    nlist = NULL;
    memset(subblock_data_ptr, 0, sizeof(t_subblock_data));

    /* Multi-pass load 
     * COUNT
     * -> count blocks
     * -> count nets
     * 
     * LOAD
     * -> alloc num_subblocks_per_block list
     * -> allocate s_block list at start
     * -> allocate s_net list at start
     * -> count subblocks per block
     * -> sets block names
     * -> sets block types
     * -> allocs block net lists
     * -> sets net names
     * 
     * MAP
     * -> fills in s_block:nets list 
     * -> fills in subblocks */

    for(pass = 0; pass < STOP; ++pass)
	{
	    rewind(infile);
	    line = 0;
	    i = 0;
	    j = 0;
	    overide = NORMAL;

	    /* Alloc the lists */
	    if(LOAD == pass)
		{
		    blist =
			(struct s_block *)my_malloc(sizeof(struct s_block) *
						    bcount);
		    memset(blist, 0, (sizeof(struct s_block) * bcount));

		    nlist =
			(struct s_net *)my_malloc(sizeof(struct s_net) *
						  ncount);
		    memset(nlist, 0, (sizeof(struct s_net) * ncount));

		    slist =
			(t_subblock **) my_malloc(sizeof(t_subblock *) *
						  bcount);
		    memset(slist, 0, (sizeof(t_subblock *) * bcount));

		    scount = (int *)my_malloc(sizeof(int) * bcount);
		    memset(scount, 0, (sizeof(int) * bcount));
		}

	    /* Read file line by line */
	    block_tokens = ReadLineTokens(infile, &line);
	    prev_line = line;
	    while(block_tokens)
		{

		    /* .global directives have special meaning */
		    if(0 == strcmp(block_tokens[0], ".global"))
			{
			    if(MAP == pass)
				{
				    for(l = 0; l < ncount; ++l)
					{
					    if(0 ==
					       strcmp(nlist[l].name,
						      block_tokens[1]))
						{
						    nlist[l].is_global = TRUE;
						    break;
						}
					}
				    if(l == ncount)
					{
					    printf(ERRTAG
						   "'%s':%d - '.global' specified an invalid net\n",
						   net_file, prev_line);
					    exit(1);
					}
				}

			    /* Don't do any more processing on this */
			    FreeTokens(&block_tokens);
			    block_tokens = ReadLineTokens(infile, &line);
			    prev_line = line;
			    continue;
			}
		    pin_tokens = ReadLineTokens(infile, &line);

		    if(CountTokens(block_tokens) != 2)
			{
			    printf(ERRTAG "'%s':%d - block type line should "
				   "be in form '.type_name block_name'\n",
				   net_file, prev_line);
			    exit(1);
			}
		    if(NULL == pin_tokens)
			{
			    printf(ERRTAG
				   "'%s':%d - blocks must be follow by a 'pinlist:' line\n",
				   net_file, line);
			    exit(1);
			}
		    if(0 != strcmp("pinlist:", pin_tokens[0]))
			{
			    printf(ERRTAG
				   "'%s':%d - 'pinlist:' line must follow "
				   "block type line\n", net_file, line);
			    exit(1);
			}

		    type =
			get_type_by_name(block_tokens[0], num_types,
					 block_types, IO_type, net_file,
					 prev_line, &overide);
		    /* Check if we are overiding the pinlist format for this block */
		    if(overide)
			{
			    if(CountTokens(pin_tokens) != 2)
				{	/* 'pinlist:' and name */
				    printf(ERRTAG
					   "'%s':%d - pinlist for .input and .output should "
					   "only have one item.\n", net_file,
					   line);
				    exit(1);
				}

			    /* Make a new faked token list with 'pinlist:' and then pin mappings and a null */
			    tokens =
				(char **)my_malloc(sizeof(char *) *
						   (type->num_pins + 2));

			    l = strlen(pinlist_str) + 1;
			    k = strlen(pin_tokens[1]) + 1;
			    tokens[0] =
				(char *)my_malloc(sizeof(char) * (k + l));
			    memcpy(tokens[0], pinlist_str, l * sizeof(char));
			    memcpy(tokens[0] + l, pin_tokens[1],
				   k * sizeof(char));

			    /* Set all other pins to open */
			    for(k = 0; k < type->num_pins; ++k)
				{
				    tokens[1 + k] = "open";	/* free wont be called on this so is safe */
				}
			    tokens[1 + k] = NULL;	/* End of token list marker */
			    /* Set the one pin with the value given */
			    for(k = 0; k < type->num_pins; ++k)
				{
				    switch (overide)
					{
					case INPAD:
					    tokens[1 + io_opin] =
						(tokens[0] + l);
					    break;
					case OUTPAD:
					    tokens[1 + io_ipin] =
						(tokens[0] + l);
					    break;
					}
				}
			    FreeTokens(&pin_tokens);
			    pin_tokens = tokens;
			    tokens = NULL;
			}

		    if(CountTokens(pin_tokens) != (type->num_pins + 1))
			{
			    printf(ERRTAG
				   "'%s':%d - 'pinlist:' line has %d pins instead of "
				   "expect %d pins.\n", net_file, line,
				   CountTokens(pin_tokens) - 1,
				   type->num_pins);
			    exit(1);
			}

		    /* Load block name and type and alloc net list */
		    if(LOAD == pass)
			{
			    blist[i].name = my_strdup(block_tokens[1]);
			    blist[i].type = type;
			    blist[i].nets =
				(int *)my_malloc(sizeof(int) *
						 type->num_pins);
			    for(k = 0; k < type->num_pins; ++k)
				{
				    blist[i].nets[k] = OPEN;
				}
			}

		    /* Examine pin list to determine nets */
		    for(k = 0; k < type->num_pins; ++k)
			{
			    if(0 != strcmp("open", pin_tokens[1 + k]))
				{
				    if(DRIVER ==
				       type->class_inf[type->pin_class[k]].
				       type)
					{
					    if(LOAD == pass)
						{
						    nlist[j].name =
							my_strdup(pin_tokens
								  [1 + k]);
						}
					    if(MAP == pass)
						{
						    blist[i].nets[k] = j;	/* If we are net source we don't need to search */
						}

					    ++j;	/* This was an active netlist */
					}
				    else
					{
					    if(MAP == pass)
						{
						    /* Map sinks by doing a linear search to find the net */
						    blist[i].nets[k] = OPEN;
						    for(l = 0; l < ncount;
							++l)
							{
							    if(0 ==
							       strcmp(nlist
								      [l].
								      name,
								      pin_tokens
								      [1 +
								       k]))
								{
								    blist[i].
									nets
									[k] =
									l;
								    break;
								}
							}
						    if(OPEN ==
						       blist[i].nets[k])
							{
							    printf(ERRTAG
								   "'%s':%d - Net '%s' not found\n",
								   net_file,
								   line,
								   pin_tokens
								   [1 + k]);
							    exit(1);
							}
						}
					}
				}
			}

		    /* Allocating subblocks */
		    if(MAP == pass)
			{
				/* All blocks internally have subblocks but I/O subblocks are
				allocated and loaded elsewhere */
				if(scount[i] > 0) {
					slist[i] = (t_subblock *)
					my_malloc(sizeof(t_subblock) * scount[i]);
					for(k = 0; k < scount[i]; ++k)
					{
						slist[i][k].name = NULL;
						slist[i][k].clock = OPEN;
						slist[i][k].inputs =
						(int *)my_malloc(sizeof(int) *
								 type->
								 max_subblock_inputs);
						for(l = 0; l < type->max_subblock_inputs;
						++l)
						{
							slist[i][k].inputs[l] = OPEN;
						}
						slist[i][k].outputs =
						(int *)my_malloc(sizeof(int) *
								 type->
								 max_subblock_outputs);
						for(l = 0; l < type->max_subblock_outputs;
						++l)
						{
							slist[i][k].outputs[l] = OPEN;
						}
					}
				}
			}

		    /* Ignore subblock data */
		    tokens = ReadLineTokens(infile, &line);
		    prev_line = line;
		    m = 0;
		    while(tokens && (0 == strcmp(tokens[0], "subblock:")))
			{
			    if(CountTokens(tokens) != (type->max_subblock_inputs + type->max_subblock_outputs + 1 +	/* clocks */
						       2))
				{	/* 'subblock:', name */
				    printf("subblock wrong pin count, netlist has %d, architecture as %d on line %d \n" ,
						CountTokens(tokens) - 2, (type->max_subblock_inputs + type->max_subblock_outputs + 1),
						line);
				    exit(1);
				}

			    /* Count subblocks given */
			    if(LOAD == pass)
				{
				    scount[i]++;
				}

			    /* Load subblock name */
			    if(MAP == pass)
				{
				    assert(i < bcount);
				    assert(m < scount[i]);
				    slist[i][m].name = my_strdup(tokens[1]);
				    for(k = 0; k < type->max_subblock_inputs;
					++k)
					{
					    /* Check prefix and load pin num */
					    l = 2 + k;
					    if(0 ==
					       strncmp("ble_", tokens[l], 4))
						{
						    slist[i][m].inputs[k] = type->num_pins + my_atoi(tokens[l] + 4);	/* Skip the 'ble_' part */
						}
					    else if(0 !=
						    strcmp("open", tokens[l]))
						{
						    slist[i][m].inputs[k] =
							my_atoi(tokens[l]);
						}
					}
				    for(k = 0; k < type->max_subblock_outputs;
					++k)
					{
					    l = 2 +
						type->max_subblock_inputs + k;
					    if(0 != strcmp("open", tokens[l]))
						{
						    slist[i][m].outputs[k] =
							my_atoi(tokens[l]);
						}
					}
				    l = 2 + type->max_subblock_inputs +
					type->max_subblock_outputs;
				    if(0 != strcmp("open", tokens[l]))
					{
					    slist[i][m].clock =
						my_atoi(tokens[l]);
					}
				}

			    ++m;	/* Next subblock */

			    FreeTokens(&tokens);
			    tokens = ReadLineTokens(infile, &line);
			    prev_line = line;
			}

		    if(pass > COUNT)
			{
			    /* Check num of subblocks read */
			    if(scount[i] > type->max_subblocks)
				{
					printf("too many subblocks on block [%d] %s\n", i, blist[i].name);
				    exit(1);
				}
			}

		    ++i;	/* End of this block */

		    FreeTokens(&block_tokens);
		    FreeTokens(&pin_tokens);
		    block_tokens = tokens;
		}

	    /* Save counts */
	    if(COUNT == pass)
		{
		    bcount = i;
		    ncount = j;
		}
	}
    fclose(infile);

    /* Builds mappings from each netlist to the blocks contained */
    sync_nets_to_blocks(bcount, blist, ncount, nlist);

    /* Send values back to caller */
    *num_blocks = bcount;
    *block_list = blist;
    *num_nets = ncount;
    *net_list = nlist;
    subblock_data_ptr->subblock_inf = slist;
    subblock_data_ptr->num_subblocks_per_block = scount;
}
Beispiel #11
0
int prs_flt_limitnb(struct linked_list_opt_value *optl, char *val)
{
	llimitnb = (int) my_atoi(val,10);
	return OPT_OK;
}
Beispiel #12
0
int main(int argc, char * * argv)
{
    printf("Welcome to PA02.\n"
	   "\n"
	   "You are encouraged to edit this file in order to test\n"
	   "the behavior of the functions you write in answer02.c\n"
	   "\n"
	   "This file will not be marked, and should not be\n"
	   "submitted.\n"
	   "\n"
	   "Don't forget to post questions on blackboard, and ask\n"
	   "the TAs and your classmates for help.\n"
	   "\n");

    const char * s1 = "Hello World!";
    const char * s2 = "";
    const char * s3 = "foo";

    // -- my_strlen, should be: 12, 0, and 3
    printf("my_strlen(\"%s\") = %d\n", s1, (int) my_strlen(s1));
    printf("my_strlen(\"%s\") = %d\n", s2, (int) my_strlen(s2));
    printf("my_strlen(\"%s\") = %d\n", s3, (int) my_strlen(s3));
    printf("\n");

    // -- my_countchar, should be: 3, 0, and 2
    printf("my_countchar(\"%s\", 'l') = %d\n", s1, (int) my_countchar(s1, 'l'));
    printf("my_countchar(\"%s\", 'o') = %d\n", s2, (int) my_countchar(s2, 'o'));
    printf("my_countchar(\"%s\", 'o') = %d\n", s3, (int) my_countchar(s3, 'o'));
    printf("\n");
    
    // -- my_strchr, should be: "llo World!", "(null)", and ""
    printf("my_strchr(\"%s\", 'l') = %s\n", s1, my_strchr(s1, 'l'));
    printf("my_strchr(\"%s\", 'o') = %s\n", s2, my_strchr(s2, 'o'));
    printf("my_strchr(\"%s\", '\\0') = %s\n", s3, my_strchr(s3, '\0'));
    printf("\n");

    // -- my_strrchr, should be: "ld!", "(null)", and ""
    printf("my_strrchr(\"%s\", 'l') = %s\n", s1, my_strrchr(s1, 'l'));
    printf("my_strrchr(\"%s\", 'o') = %s\n", s2, my_strrchr(s2, 'o'));
    printf("my_strrchr(\"%s\", '\\0') = %s\n", s3, my_strrchr(s3, '\0'));
    printf("my_strrchr(\"\", '\\0') = %s\n", my_strrchr("", '\0'));
    printf("my_strrchr(\"Find First 'F' from right\", 'F') = %s\n", my_strrchr("Find First 'F' from right", 'F'));
    printf("my_strrchr(\"Find first char\", 'F') = %s\n", my_strrchr("Find first char", 'F'));
    printf("my_strrchr(\"!Find last char!\", '!') = %s\n", my_strrchr("!Find last char!", '!'));
    printf("\n");

    // -- my_strstr, should be: "World!", "Hello World!", "(null)"
    printf("my_strstr(\"%s\", \"World\") = %s\n", s1, my_strstr(s1, "World"));
    printf("my_strstr(\"%s\", \"\") = %s\n", s1, my_strstr(s1, ""));
    printf("my_strstr(\"%s\", \"hello\") = %s\n", s1, my_strstr(s1, "hello"));
    printf("\n");

    // -- my_strcpy. For this function you need a buffer where you
    // copy the string to. 
    char buffer[BUFFER_LEN];
    my_strcpy(buffer, s1);
    printf("my_strcpy(buffer, \"%s\"), buffer = \"%s\"\n", s1, buffer);
    my_strcpy(buffer, s2);
    printf("my_strcpy(buffer, \"%s\"), buffer = \"%s\"\n", s2, buffer);
    my_strcpy(buffer, s3);
    printf("my_strcpy(buffer, \"%s\"), buffer = \"%s\"\n", s3, buffer);
    printf("\n");

    // -- my_strcat. You will have to do this yourself... just
    // look at my_strcpy for an example, and go from there.
    char dest[BUFFER_LEN];
    char src[BUFFER_LEN];
    my_strcpy(dest, "Hello ");
    my_strcpy(src, "Zippy!");
    printf("my_strcat(\"Hello \", \"%s\") = \"%s\"\n", src,  my_strcat(dest, src));
    my_strcpy(dest, "");
    my_strcpy(src, "Hi!");
    printf("my_strcat(\"\", \"%s\") = \"%s\"\n", src,  my_strcat(dest, src));
    printf("\n");
    
    // -- my_isspace. You will have to do this for yourself.
    printf("my_isspace(' ') = %d\n", my_isspace(' '));
    printf("my_isspace('\\t') = %d\n", my_isspace('\t'));
    printf("my_isspace('\\v') = %d\n", my_isspace('\v'));
    printf("my_isspace('\\f') = %d\n", my_isspace('\f'));
    printf("my_isspace('\\n') = %d\n", my_isspace('\n'));
    printf("my_isspace('\\r') = %d\n", my_isspace('\r'));
    printf("\n");

    // -- my_atoi. You will have to do this for yourself.
    printf("my_atoi(\"%s\") = %d\n", s1, my_atoi(s1));
    printf("my_atoi(\"32 students got an F\") = %d\n", my_atoi("32 students got an F"));
    printf("my_atoi(\"\\n\\t\\v -273\") = %d\n", my_atoi("\n\t\v -273"));
    printf("\n");
    return EXIT_SUCCESS;
}
Beispiel #13
0
int main(int argc, char** argv)
{
	int sockfd;
	int n;
	int port_num;
	
	char buffer[BUFFSIZE];
	char* nname;
	
	struct sockaddr_in server_adderess;

	struct hostent* server;

	if(argc < 3)
	{
		my_str("Use: [Machine_Name] [port_num]\n");
		exit(1);
	}
	
	port_num = my_atoi(argv[2]);
	
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
        my_str("ERROR opening socket");
    server = gethostbyname(argv[1]);
	
	if (server == NULL) 
	{
        my_str("ERROR, no such host\n");
        exit(0);
    }
	
	bzero((char*)&server_adderess, sizeof(server_adderess));

	server_adderess.sin_family = AF_INET;
	
	bcopy((char *)server->h_addr, (char *)&server_adderess.sin_addr.s_addr, server->h_length);
	server_adderess.sin_port = htons(port_num);
	
	//my_str("Try connection now\n");
	
	if(connect(sockfd,  (struct sockaddr *)&server_adderess, sizeof(server_adderess))<0)
	{
		my_str("Could not connect to ");
		my_str(argv[1]);
		my_char('\n');
		exit(0);
	}
	signal(SIGINT, theEndOfTheCli);
	//Initilizing Done
	//Starting Program
	
	bzero(buffer, BUFFSIZE);
	nname = (char*)my_xmalloc(50*sizeof(char));
	
	my_str("Nickname: ");
	n = read(0, nname, 49);
	nname[n] = '\0';
	
	
	int i=0;
	while(nname[i] != '\0')
	{
		if(nname[i++] == '\n')
			nname[--i] = '\0';
	}

	if(n <= 0)
		my_str("Invalid nick name\n");
	
	n = write(sockfd, nname, my_strlen(nname));
	
	if(n < 0)
		my_str("ERROR writing to socket\n");
	//my_str(buffer);
	while(1)
	{
		bzero(buffer, BUFFSIZE);
		my_str(nname);
		my_str(": ");
		n = read(0, buffer, BUFFSIZE-1);
		i=0;
		
		while(buffer[i] != '\0')
		{
			if(buffer[i++] == '\n')
				buffer[--i] = '\0';
		}
		
		if(n <= 0)
			my_str("Unable to read\n");
		
		n = write(sockfd, buffer, my_strlen(buffer));
		if(my_strncmp(buffer, "/exit", 5) == 0)
			exit(0);
		if(my_strncmp(buffer, "/nick", 5) == 0)
		{
			free(nname);
			nname = my_strdup(&buffer[6]);
		}
		if(n <= 0)
			my_str("Unable to Write\n");

	}
}
Beispiel #14
0
void ExecScript(int log) {
  char szRet[128] = "";
  char *pExec;
  int nComSpecSize;
  char meDLLPath[MAX_PATH];    
  char *p;
  char *executor;
  char *g_exec;
  unsigned int g_to;

  nComSpecSize = GetModuleFileName(g_hInst, meDLLPath, MAX_PATH) + 2; // 2 chars for quotes
  p = meDLLPath + nComSpecSize - 2; // point p at null char of meDLLPath
  g_exec = (char *)GlobalAlloc(GPTR, sizeof(char)*g_stringsize+nComSpecSize+2); // 1 for space, 1 for null
  *g_exec = '"';
  executor = g_exec + 1;

  do
  {
    if (*p == '\\')
      break;
    p = CharPrev(meDLLPath, p);
  }
  while (p > meDLLPath);
  if (p == meDLLPath)
  {
    // bad path
    lstrcpy(szRet, "error");
    goto done;
  }

  *p = 0;
  GetTempFileName(meDLLPath, "ns", 0, executor);
  *p = '\\';
  if (CopyFile(meDLLPath, executor, FALSE))
  {
    HANDLE hFile, hMapping;
    LPBYTE pMapView;
    PIMAGE_NT_HEADERS pNTHeaders;
    hFile = CreateFile(executor, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,0, 0);
    hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
    pMapView = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0);
    if (pMapView)
    {
      pNTHeaders = (PIMAGE_NT_HEADERS)(pMapView + ((PIMAGE_DOS_HEADER)pMapView)->e_lfanew);
      pNTHeaders->FileHeader.Characteristics = IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_LOCAL_SYMS_STRIPPED | 
        IMAGE_FILE_LINE_NUMS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE;
      pNTHeaders->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
      pNTHeaders->OptionalHeader.AddressOfEntryPoint = (DWORD)WinMain - (DWORD)g_hInst;  
      UnmapViewOfFile(pMapView);
    }
    CloseHandle(hMapping);
    CloseHandle(hFile);
  }

  lstrcat(g_exec, "\"");

  g_to = 0; // default is no timeout

  g_hwndList = FindWindowEx(FindWindowEx(g_hwndParent,NULL,"#32770",NULL),NULL,"SysListView32",NULL);

  // add space
  pExec = g_exec + lstrlen(g_exec);
  *pExec = ' ';
  pExec++;
  
  popstring(pExec);
  if (my_strstr(pExec, "/TIMEOUT=")) {
    char *szTimeout = pExec + 9;
    g_to = my_atoi(szTimeout);
    popstring(pExec);
  }

  if (!g_exec[0]) 
  {
    lstrcpy(szRet, "error");
    goto done;
  }
  
  {
    STARTUPINFO si={sizeof(si),};
    SECURITY_ATTRIBUTES sa={sizeof(sa),};
    SECURITY_DESCRIPTOR sd={0,};
    PROCESS_INFORMATION pi={0,};
    OSVERSIONINFO osv={sizeof(osv)};
    HANDLE newstdout=0,read_stdout=0;
    HANDLE newstdin=0,read_stdin=0;
    DWORD dwRead = 1;
    DWORD dwExit = !STILL_ACTIVE;
    DWORD dwLastOutput;
    static char szBuf[1024];
    HGLOBAL hUnusedBuf;
    char *szUnusedBuf = 0;

    if (log) {
      hUnusedBuf = GlobalAlloc(GHND, log & 2 ? g_stringsize : sizeof(szBuf)*4);
      if (!hUnusedBuf) {
        lstrcpy(szRet, "error");
        goto done;
      }
      szUnusedBuf = (char *)GlobalLock(hUnusedBuf);
    }

    GetVersionEx(&osv);
    if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) {
      InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
      SetSecurityDescriptorDacl(&sd,true,NULL,false);
      sa.lpSecurityDescriptor = &sd;
    }
    else 
      sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = true;
    if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) {
      lstrcpy(szRet, "error");
      goto done;
    }
    if (!CreatePipe(&read_stdin,&newstdin,&sa,0)) {
      lstrcpy(szRet, "error");
      goto done;
    }

    GetStartupInfo(&si);
    si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;
    si.hStdInput = newstdin;
    si.hStdOutput = newstdout;
    si.hStdError = newstdout;
    if (!CreateProcess(NULL,g_exec,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) {
      lstrcpy(szRet, "error");
      goto done;
    }

    dwLastOutput = GetTickCount();

    while (dwExit == STILL_ACTIVE || dwRead) {
      PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL);
      if (dwRead) {
        dwLastOutput = GetTickCount();
        ReadFile(read_stdout, szBuf, sizeof(szBuf)-1, &dwRead, NULL);
        szBuf[dwRead] = 0;
        if (log) {
          char *p, *p2;
          SIZE_T iReqLen = lstrlen(szBuf) + lstrlen(szUnusedBuf);
          if (GlobalSize(hUnusedBuf) < iReqLen && (iReqLen < g_stringsize || !(log & 2))) {
            GlobalUnlock(hUnusedBuf);
            hUnusedBuf = GlobalReAlloc(hUnusedBuf, iReqLen+sizeof(szBuf), GHND);
            if (!hUnusedBuf) {
              lstrcpy(szRet, "error");
              break;
            }
            szUnusedBuf = (char *)GlobalLock(hUnusedBuf);
          }
          p = szUnusedBuf; // get the old left overs
          if (iReqLen < g_stringsize || !(log & 2)) lstrcat(p, szBuf);
          else {
            lstrcpyn(p + lstrlen(p), szBuf, g_stringsize - lstrlen(p));
          }

          if (!(log & 2)) {
            while (p = my_strstr(p, "\t")) {
              if ((int)(p - szUnusedBuf) > (int)(GlobalSize(hUnusedBuf) - TAB_REPLACE_SIZE - 1))
              {
                *p++ = ' ';
              }
              else
              {
                int len = lstrlen(p);
                char *c_out=(char*)p+TAB_REPLACE_SIZE+len;
                char *c_in=(char *)p+len;
                while (len-- > 0) {
                  *c_out--=*c_in--;
                }

                lstrcpy(p, TAB_REPLACE);
                p += TAB_REPLACE_SIZE;
                *p = ' ';
              }
            }
            
            p = szUnusedBuf; // get the old left overs
            for (p2 = p; *p2;) {
              if (*p2 == '\r') {
                *p2++ = 0;
                continue;
              }
              if (*p2 == '\n') {
                *p2 = 0;
                while (!*p && p != p2) p++;
                LogMessage(p);
                p = ++p2;
                continue;
              }
              p2 = CharNext(p2);
            }
            
            // If data was taken out from the unused buffer, move p contents to the start of szUnusedBuf
            if (p != szUnusedBuf) {
              char *p2 = szUnusedBuf;
              while (*p) *p2++ = *p++;
              *p2 = 0;
            }
          }
        }
      }
      else {
        if (g_to && GetTickCount() > dwLastOutput+g_to) {
          TerminateProcess(pi.hProcess, -1);
          lstrcpy(szRet, "timeout");
        }
        else Sleep(LOOPTIMEOUT);
      }
      GetExitCodeProcess(pi.hProcess, &dwExit);
      if (dwExit != STILL_ACTIVE) {
        PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL);
      }
    }
done:
    if (log & 2) pushstring(szUnusedBuf);
    if (log & 1 && *szUnusedBuf) LogMessage(szUnusedBuf);
    if ( dwExit == STATUS_ILLEGAL_INSTRUCTION )
      lstrcpy(szRet, "error");
    if (!szRet[0]) wsprintf(szRet,"%d",dwExit);
    pushstring(szRet);
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    CloseHandle(newstdout);
    CloseHandle(read_stdout);
    CloseHandle(newstdin);
    CloseHandle(read_stdin);
    *(pExec-2) = '\0'; // skip space and quote
    DeleteFile(executor);
    GlobalFree(g_exec);
    if (log) {
      GlobalUnlock(hUnusedBuf);
      GlobalFree(hUnusedBuf);
    }
  }
}
int		sgt(char *str, t_elem *elem)
{
  elem->actual_time_value = my_atoi(del_bn(str + 4));
  my_printf("Time : %d\n", elem->actual_time_value);
  return (1);
}
Beispiel #16
0
static int
wl_android_set_auto_channel(struct net_device *dev, const char* string_num,
									char* command, int total_len)
{
	int channel;
	int chosen = 0;
	int retry = 0;
	int ret = 0;

	/* Restrict channel to 1 - 7: 2GHz, 20MHz BW, No SB */
	u32 req_buf[8] = {7, 0x2B01, 0x2B02, 0x2B03, 0x2B04, 0x2B05, 0x2B06,
						0x2B07};

	/* Auto channel select */
	wl_uint32_list_t request;

	channel = my_atoi(string_num);
	DHD_INFO(("%s : HAPD_AUTO_CHANNEL = %d\n", __FUNCTION__, channel));

	if (channel == 20)
		ret = wldev_ioctl(dev, WLC_START_CHANNEL_SEL, (void *)&req_buf,
							sizeof(req_buf), true);
	else { /* channel == 0 */
		request.count = htod32(0);
		ret = wldev_ioctl(dev, WLC_START_CHANNEL_SEL, (void *)&request,
							sizeof(request), true);
	}

	if (ret < 0) {
		DHD_ERROR(("%s: can't start auto channel scan, err = %d\n",
					__FUNCTION__, ret));
		channel = 0;
		goto done;
	}

	/* Wait for auto channel selection, max 2500 ms */
	bcm_mdelay(500);

	retry = 10;
	while(retry--) {
		ret = wldev_ioctl(dev, WLC_GET_CHANNEL_SEL, &chosen, sizeof(chosen),
							false);
		if (ret < 0 || dtoh32(chosen) == 0) {
			DHD_INFO(("%s: %d tried, ret = %d, chosen = %d\n",
						__FUNCTION__, (10 - retry), ret, chosen));
			bcm_mdelay(200);
		}
		else {
			channel = (u16)chosen & 0x00FF;
			DHD_ERROR(("%s: selected channel = %d\n", __FUNCTION__, channel));
			break;
		}
	}

	if (retry == 0)	{
		DHD_ERROR(("%s: auto channel timed out, failed\n", __FUNCTION__));
		channel = 0;
	}

done:
//	snprintf(command, total_len, "%d", channel);
	snprintf(command, 4, "%d", channel);
	DHD_INFO(("%s: command result is %s\n", __FUNCTION__, command));

//	return 1;
	return 4;
}
Beispiel #17
0
int fb_find_mode(struct fb_var_screeninfo *var,
		 struct fb_info *info, const char *mode_option,
		 const struct fb_videomode *db, unsigned int dbsize,
		 const struct fb_videomode *default_mode,
		 unsigned int default_bpp)
{
    int i;

    /* Set up defaults */
    if (!db) {
	db = modedb;
	dbsize = ARRAY_SIZE(modedb);
    }

    if (!default_mode)
	default_mode = &db[0];

    if (!default_bpp)
	default_bpp = 8;

    /* Did the user specify a video mode? */
    if (mode_option || (mode_option = global_mode_option)) {
	const char *name = mode_option;
	unsigned int namelen = strlen(name);
	int res_specified = 0, bpp_specified = 0, refresh_specified = 0;
	unsigned int xres = 0, yres = 0, bpp = default_bpp, refresh = 0;
	int yres_specified = 0, cvt = 0, rb = 0, interlace = 0, margins = 0;
	u32 best, diff;

	for (i = namelen-1; i >= 0; i--) {
	    switch (name[i]) {
		case '@':
		    namelen = i;
		    if (!refresh_specified && !bpp_specified &&
			!yres_specified) {
			refresh = my_atoi(&name[i+1]);
			refresh_specified = 1;
			if (cvt || rb)
			    cvt = 0;
		    } else
			goto done;
		    break;
		case '-':
		    namelen = i;
		    if (!bpp_specified && !yres_specified) {
			bpp = my_atoi(&name[i+1]);
			bpp_specified = 1;
			if (cvt || rb)
			    cvt = 0;
		    } else
			goto done;
		    break;
		case 'x':
		    if (!yres_specified) {
			yres = my_atoi(&name[i+1]);
			yres_specified = 1;
		    } else
			goto done;
		    break;
		case '0' ... '9':
		    break;
		case 'M':
		    if (!yres_specified)
			cvt = 1;
		    break;
		case 'R':
		    if (!cvt)
			rb = 1;
		    break;
		case 'm':
		    if (!cvt)
			margins = 1;
		    break;
		case 'i':
		    if (!cvt)
			interlace = 1;
		    break;
		default:
		    goto done;
	    }
	}
	if (i < 0 && yres_specified) {
	    xres = my_atoi(name);
	    res_specified = 1;
	}
done:
	if (cvt) {
	    struct fb_videomode cvt_mode;
	    int ret;

	    DPRINTK("CVT mode %dx%d@%dHz%s%s%s\n", xres, yres,
		    (refresh) ? refresh : 60, (rb) ? " reduced blanking" :
		    "", (margins) ? " with margins" : "", (interlace) ?
		    " interlaced" : "");

	    cvt_mode.xres = xres;
	    cvt_mode.yres = yres;
	    cvt_mode.refresh = (refresh) ? refresh : 60;

	    if (interlace)
		cvt_mode.vmode |= FB_VMODE_INTERLACED;
	    else
		cvt_mode.vmode &= ~FB_VMODE_INTERLACED;

	    ret = fb_find_mode_cvt(&cvt_mode, margins, rb);

	    if (!ret && !fb_try_mode(var, info, &cvt_mode, bpp)) {
		DPRINTK("modedb CVT: CVT mode ok\n");
		return 1;
	    }

	    DPRINTK("CVT mode invalid, getting mode from database\n");
	}

	DPRINTK("Trying specified video mode%s %ix%i\n",
	    refresh_specified ? "" : " (ignoring refresh rate)", xres, yres);

	diff = refresh;
	best = -1;
	for (i = 0; i < dbsize; i++) {
		if (name_matches(db[i], name, namelen) ||
		    (res_specified && res_matches(db[i], xres, yres))) {
			if(!fb_try_mode(var, info, &db[i], bpp)) {
				if(!refresh_specified || db[i].refresh == refresh)
					return 1;
				else {
					if(diff > abs(db[i].refresh - refresh)) {
						diff = abs(db[i].refresh - refresh);
						best = i;
					}
				}
			}
		}
	}
	if (best != -1) {
		fb_try_mode(var, info, &db[best], bpp);
		return 2;
	}

	diff = xres + yres;
	best = -1;
	DPRINTK("Trying best-fit modes\n");
	for (i = 0; i < dbsize; i++) {
	    if (xres <= db[i].xres && yres <= db[i].yres) {
		DPRINTK("Trying %ix%i\n", db[i].xres, db[i].yres);
		if (!fb_try_mode(var, info, &db[i], bpp)) {
		    if (diff > (db[i].xres - xres) + (db[i].yres - yres)) {
			diff = (db[i].xres - xres) + (db[i].yres - yres);
			best = i;
		    }
		}
	    }
	}
	if (best != -1) {
	    fb_try_mode(var, info, &db[best], bpp);
	    return 5;
	}
    }

    DPRINTK("Trying default video mode\n");
    if (!fb_try_mode(var, info, default_mode, default_bpp))
	return 3;

    DPRINTK("Trying all modes\n");
    for (i = 0; i < dbsize; i++)
	if (!fb_try_mode(var, info, &db[i], default_bpp))
	    return 4;

    DPRINTK("No valid mode found\n");
    return 0;
}
Beispiel #18
0
int main(int argc, char** argv)
{
  struct hostent* server;
  char message[BUFFER_SIZE];
  int bytes_read;
  int port;
  struct sockaddr_in serv_addr;
  
  
  signal(SIGINT, client_kill);
  
  if(argc != 3)
    {
      my_str("Usage: ./client serverName portNum\n");
      exit(1);
    }
  port = my_atoi(argv[2]);
  if(port <= 0 || port > 65535)
    {
      my_str("Invalid port number\n");
      exit(1);
    }
  
  memset(&serv_addr.sin_zero, 0, 8);
  
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  server = gethostbyname(argv[1]);
  
  if(server== NULL)
    {
      my_str("Invalid server host name\n");
      exit(1);
    }
  
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(port);
  
  memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
  
  if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)
    {
      my_str("Connection to server failed!\n");
      exit(1);
    }
  
  my_str("Nickname: ");
  bytes_read = read(0, message, BUFFER_SIZE - 1);
  message[bytes_read - 1] = '\0';
  my_char('\n');
  
  if(write(sockfd, message, bytes_read) < 0)
    {
      my_str("Unable to send message to server\n");
      exit(1);
    }
  
  while(1)
    {
      bytes_read = read(sockfd, message, BUFFER_SIZE - 1);
      if(bytes_read < 1)
	{
	  my_str("Server closed connection!\n");
	  exit(1);
	}
      my_str("> ");
      bytes_read = read(0, message, BUFFER_SIZE - 1);
      message[bytes_read - 1] = '\0';
      write(sockfd, message, bytes_read);
      if(my_strncmp(message, "/exit\0", 6) == 0 && my_strncmp(message, "/exit ", 6) == 0)
	{
	  my_str("Bye\n");
	  exit(0);
	}
    }
  
  return 0;
}
Beispiel #19
0
int fb_find_mode(struct fb_var_screeninfo *var,
		 struct fb_info *info, const char *mode_option,
		 const struct fb_videomode *db, unsigned int dbsize,
		 const struct fb_videomode *default_mode,
		 unsigned int default_bpp)
{
    int i;

    /* Set up defaults */
    if (!db) {
	db = modedb;
	dbsize = ARRAY_SIZE(modedb);
    }

    if (!default_mode)
	default_mode = &db[0];

    if (!default_bpp)
	default_bpp = 8;

    /* Did the user specify a video mode? */
    if (!mode_option)
	mode_option = fb_mode_option;
    if (mode_option) {
	const char *name = mode_option;
	unsigned int namelen = strlen(name);
	int res_specified = 0, bpp_specified = 0, refresh_specified = 0;
	unsigned int xres = 0, yres = 0, bpp = default_bpp, refresh = 0;
	int yres_specified = 0, cvt = 0, rb = 0, interlace = 0, margins = 0;
	u32 best, diff, tdiff;

	for (i = namelen-1; i >= 0; i--) {
	    switch (name[i]) {
		case '@':
		    namelen = i;
		    if (!refresh_specified && !bpp_specified &&
			!yres_specified) {
			refresh = my_atoi(&name[i+1]);
			refresh_specified = 1;
			if (cvt || rb)
			    cvt = 0;
		    } else
			goto done;
		    break;
		case '-':
		    namelen = i;
		    if (!bpp_specified && !yres_specified) {
			bpp = my_atoi(&name[i+1]);
			bpp_specified = 1;
			if (cvt || rb)
			    cvt = 0;
		    } else
			goto done;
		    break;
		case 'x':
		    if (!yres_specified) {
			yres = my_atoi(&name[i+1]);
			yres_specified = 1;
		    } else
			goto done;
		    break;
		case '0' ... '9':
		    break;
		case 'M':
		    if (!yres_specified)
			cvt = 1;
		    break;
		case 'R':
		    if (!cvt)
			rb = 1;
		    break;
		case 'm':
		    if (!cvt)
			margins = 1;
		    break;
		case 'i':
		    if (!cvt)
			interlace = 1;
		    break;
		default:
		    goto done;
	    }
	}
	if (i < 0 && yres_specified) {
	    xres = my_atoi(name);
	    res_specified = 1;
	}
done:
	if (cvt) {
	    struct fb_videomode cvt_mode;
	    int ret;

	    DPRINTK("CVT mode %dx%d@%dHz%s%s%s\n", xres, yres,
		    (refresh) ? refresh : 60, (rb) ? " reduced blanking" :
		    "", (margins) ? " with margins" : "", (interlace) ?
		    " interlaced" : "");

	    memset(&cvt_mode, 0, sizeof(cvt_mode));
	    cvt_mode.xres = xres;
	    cvt_mode.yres = yres;
	    cvt_mode.refresh = (refresh) ? refresh : 60;

	    if (interlace)
		cvt_mode.vmode |= FB_VMODE_INTERLACED;
	    else
		cvt_mode.vmode &= ~FB_VMODE_INTERLACED;

	    ret = fb_find_mode_cvt(&cvt_mode, margins, rb);

	    if (!ret && !fb_try_mode(var, info, &cvt_mode, bpp)) {
		DPRINTK("modedb CVT: CVT mode ok\n");
		return 1;
	    }

	    DPRINTK("CVT mode invalid, getting mode from database\n");
	}

	DPRINTK("Trying specified video mode%s %ix%i\n",
	    refresh_specified ? "" : " (ignoring refresh rate)", xres, yres);

	if (!refresh_specified) {
		/*
		 * If the caller has provided a custom mode database and a
		 * valid monspecs structure, we look for the mode with the
		 * highest refresh rate.  Otherwise we play it safe it and
		 * try to find a mode with a refresh rate closest to the
		 * standard 60 Hz.
		 */
		if (db != modedb &&
		    info->monspecs.vfmin && info->monspecs.vfmax &&
		    info->monspecs.hfmin && info->monspecs.hfmax &&
		    info->monspecs.dclkmax) {
			refresh = 1000;
		} else {
			refresh = 60;
		}
	}

	diff = -1;
	best = -1;
	for (i = 0; i < dbsize; i++) {
		int mode_interlace = (db[i].vmode & FB_VMODE_INTERLACED)?1:0;

		if (name_matches(db[i], name, namelen) ||
		    (res_specified && res_matches(db[i], xres, yres))) {
			if(!fb_try_mode(var, info, &db[i], bpp)) {
				if((!refresh_specified || db[i].refresh == refresh) &&
				   (interlace == mode_interlace)) {
					return 1;
				} else {
					if(diff > abs(db[i].refresh - refresh)) {
						diff = abs(db[i].refresh - refresh);
						best = i;
					}
				}
			}
		}
	}
	if (best != -1) {
		fb_try_mode(var, info, &db[best], bpp);
		return (refresh_specified) ? 2 : 1;
	}

	diff = 2 * (xres + yres);
	best = -1;
	DPRINTK("Trying best-fit modes\n");
	for (i = 0; i < dbsize; i++) {
		DPRINTK("Trying %ix%i\n", db[i].xres, db[i].yres);
		if (!fb_try_mode(var, info, &db[i], bpp)) {
			tdiff = abs(db[i].xres - xres) +
				abs(db[i].yres - yres);

			/*
			 * Penalize modes with resolutions smaller
			 * than requested.
			 */
			if (xres > db[i].xres || yres > db[i].yres)
				tdiff += xres + yres;

			if (diff > tdiff) {
				diff = tdiff;
				best = i;
			}
		}
	}
	if (best != -1) {
	    fb_try_mode(var, info, &db[best], bpp);
	    return 5;
	}
    }

    DPRINTK("Trying default video mode\n");
    if (!fb_try_mode(var, info, default_mode, default_bpp))
	return 3;

    DPRINTK("Trying all modes\n");
    for (i = 0; i < dbsize; i++)
	if (!fb_try_mode(var, info, &db[i], default_bpp))
	    return 4;

    DPRINTK("No valid mode found\n");
    return 0;
}
static pj_status_t init_options(int argc, char *argv[])
{
    enum { OPT_THREAD_COUNT = 1, OPT_REAL_SDP, OPT_TRYING, OPT_RINGING };
    struct pj_getopt_option long_options[] = {
	{ "local-port",	    1, 0, 'p' },
	{ "count",	    1, 0, 'c' },
	{ "thread-count",   1, 0, OPT_THREAD_COUNT },
	{ "method",	    1, 0, 'm' },
	{ "help",	    0, 0, 'h' },
	{ "stateless",	    0, 0, 's' },
	{ "timeout",	    1, 0, 't' },
	{ "real-sdp",	    0, 0, OPT_REAL_SDP },
	{ "verbose",        0, 0, 'v' },
	{ "use-tcp",	    0, 0, 'T' },
	{ "window",	    1, 0, 'w' },
	{ "delay",	    1, 0, 'd' },
	{ "trying",	    0, 0, OPT_TRYING},
	{ "ringing",	    0, 0, OPT_RINGING},
	{ NULL, 0, 0, 0 },
    };
    int c;
    int option_index;

    /* Init default application configs */
    app.local_port = 5060;
    app.thread_count = 1;
    app.client.job_count = DEFAULT_COUNT;
    app.client.method = *pjsip_get_options_method();
    app.client.job_window = c = JOB_WINDOW;
    app.client.timeout = 60;
    app.log_level = 3;


    /* Parse options */
    pj_optind = 0;
    while((c=pj_getopt_long(argc,argv, "p:c:m:t:w:d:hsv", 
			    long_options, &option_index))!=-1) 
    {
	switch (c) {
	case 'p':
	    app.local_port = my_atoi(pj_optarg);
	    if (app.local_port < 0 || app.local_port > 65535) {
		PJ_LOG(3,(THIS_FILE, "Invalid --local-port %s", pj_optarg));
		return -1;
	    }
	    break;

	case 'c':
	    app.client.job_count = my_atoi(pj_optarg);
	    if (app.client.job_count < 0) {
		PJ_LOG(3,(THIS_FILE, "Invalid --local-port %s", pj_optarg));
		return -1;
	    }
	    if (app.client.job_count > pjsip_cfg()->tsx.max_count)
		PJ_LOG(3,(THIS_FILE, 
			  "Warning: --count value (%d) exceeds maximum "
			  "transaction count (%d)", app.client.job_count,
			  pjsip_cfg()->tsx.max_count));
	    break;

	case OPT_THREAD_COUNT:
	    app.thread_count = my_atoi(pj_optarg);
	    if (app.thread_count < 1 || app.thread_count > 16) {
		PJ_LOG(3,(THIS_FILE, "Invalid --thread-count %s", pj_optarg));
		return -1;
	    }
	    break;

	case 'm':
	    {
		pj_str_t temp = pj_str((char*)pj_optarg);
		pjsip_method_init_np(&app.client.method, &temp);
	    }
	    break;

	case 'h':
	    usage();
	    return -1;

	case 's':
	    app.client.stateless = PJ_TRUE;
	    break;

	case OPT_REAL_SDP:
	    app.real_sdp = 1;
	    break;

	case 'v':
	    app.log_level++;
	    break;

	case 't':
	    app.client.timeout = my_atoi(pj_optarg);
	    if (app.client.timeout < 0 || app.client.timeout > 600) {
		PJ_LOG(3,(THIS_FILE, "Invalid --timeout %s", pj_optarg));
		return -1;
	    }
	    break;

	case 'w':
	    app.client.job_window = my_atoi(pj_optarg);
	    if (app.client.job_window <= 0) {
		PJ_LOG(3,(THIS_FILE, "Invalid --window %s", pj_optarg));
		return -1;
	    }
	    break;

	case 'T':
	    app.use_tcp = PJ_TRUE;
	    break;

	case 'd':
	    app.server.delay = my_atoi(pj_optarg);
	    if (app.server.delay > 3600) {
		PJ_LOG(3,(THIS_FILE, "I think --delay %s is too long", 
			  pj_optarg));
		return -1;
	    }
	    break;

	case OPT_TRYING:
	    app.server.send_trying = 1;
	    break;

	case OPT_RINGING:
	    app.server.send_ringing = 1;
	    break;

	default:
	    PJ_LOG(1,(THIS_FILE, 
		      "Invalid argument. Use --help to see help"));
	    return -1;
	}
    }

    if (pj_optind != argc) {

	if (verify_sip_url(argv[pj_optind]) != PJ_SUCCESS) {
	    PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind]));
	    return -1;
	}
	app.client.dst_uri = pj_str(argv[pj_optind]);
	
	pj_optind++;

    }

    if (pj_optind != argc) {
	PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind]));
	return -1;
    }

    return 0;
}
Beispiel #21
0
static void ui_call_transfer_replaces(pj_bool_t no_refersub)
{
    if (current_call == -1) {
	PJ_LOG(3,(THIS_FILE, "No current call"));
    } else {
	int call = current_call;
	int dst_call;
	pjsip_generic_string_hdr refer_sub;
	pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 };
	pj_str_t STR_FALSE = { "false", 5 };
	pjsua_call_id ids[PJSUA_MAX_CALLS];
	pjsua_call_info ci;
	pjsua_msg_data msg_data;
	char buf[128];
	unsigned i, count;

	count = PJ_ARRAY_SIZE(ids);
	pjsua_enum_calls(ids, &count);

	if (count <= 1) {
	    puts("There are no other calls");
	    return;
	}

	pjsua_call_get_info(current_call, &ci);
	printf("Transfer call [%d] %.*s to one of the following:\n",
	       current_call,
	       (int)ci.remote_info.slen, ci.remote_info.ptr);

	for (i=0; i<count; ++i) {
	    pjsua_call_info call_info;

	    if (ids[i] == call)
		continue;

	    pjsua_call_get_info(ids[i], &call_info);
	    printf("%d  %.*s [%.*s]\n",
		ids[i],
		(int)call_info.remote_info.slen,
		call_info.remote_info.ptr,
		(int)call_info.state_text.slen,
		call_info.state_text.ptr);
	}

	if (!simple_input("Enter call number to be replaced", buf, sizeof(buf)))
	    return;

	dst_call = my_atoi(buf);

	/* Check if call is still there. */

	if (call != current_call) {
	    puts("Call has been disconnected");
	    return;
	}

	/* Check that destination call is valid. */
	if (dst_call == call) {
	    puts("Destination call number must not be the same "
		"as the call being transferred");
	    return;
	}
	if (dst_call >= PJSUA_MAX_CALLS) {
	    puts("Invalid destination call number");
	    return;
	}
	if (!pjsua_call_is_active(dst_call)) {
	    puts("Invalid destination call number");
	    return;
	}

	pjsua_msg_data_init(&msg_data);
	if (no_refersub) {
	    /* Add Refer-Sub: false in outgoing REFER request */
	    pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB,
					   &STR_FALSE);
	    pj_list_push_back(&msg_data.hdr_list, &refer_sub);
	}

	pjsua_call_xfer_replaces(call, dst_call,
				 PJSUA_XFER_NO_REQUIRE_REPLACES,
				 &msg_data);
    }
}
bool ImportScript( const char* szFileName )
{
	char* str;
	int len;
	SCRIPT_OP* op;
	DWORD* cp = &code[0];
	BOOL bResult = FALSE;
	int line = 1;


	void* file = ReadInTextFile( szFileName );
	if( file == NULL ) goto lbl_end;


	// destroy previous string table
	micro_alloc_destroy();


//////////////////////////////////////////////////////////////
/************************************************************/
/************************************************************/
/////////////// part 1: compile /////////////////////////////
		
	str = (char*)file;

	// start off with 2 NULL entries just like the game
	WRITE_CODE( 0 ); WRITE_CODE( 0 );

	while( *str != '\0' )
	{	
		// get command
		len = GetTok( str );
		if( len != 0 )
		{
			op = in_command_set( str, len );
			if( op == NULL )
			{
				darkomen::detour::trace( "WHMTG: line %d: Unknown command. %s", line, str );
				goto lbl_end;
			}

			if( op->address != 0 ) // if not label
			{
				WRITE_CODE( op->address );
			}
			str += len; 

			// do args
			int count = 0;
			while( len = GetTok( str ) ) // loop until end of line
			{
				if( count < op->arg_cnt )
				{
					switch( op->arg_type[count] )
					{
						case 1: // int
						{
							DWORD dw;
							if( !my_atoi( str, len, &dw ) )
							{
								darkomen::detour::trace("WHMTG: line %d: bad formatting, expected integer value. Arg# %d.", line, count + 1);
								goto lbl_end;
							}
							WRITE_CODE( dw );
							str += len;
							break;
						}
						case 2: // text
						{

							if( str[0] != '\"' ) 
							{
								darkomen::detour::trace("WHMTG: line %d: bad formatting, expected text value."
									" Text must be enclosed within double quote(\") characters. Arg# %d.", line, count + 1 );
								goto lbl_end;
							}

							// find ending quote
							if( str[ len-1 ] != '\"' )
							{
								while( ( str[len] != '\"' ) && ( str[len] != '\r' ) && ( str[len] != '\n' ) && ( str[len] != '\0' ) )
								{
									len++;
								}
								if( str[len] == '\"' ) len++;
								else
								{
									darkomen::detour::trace("WHMTG: line %d: bad formatting, expected text value."
											" Text must be enclosed within double quote(\") characters. Arg# %d.", line, count + 1 );
									goto lbl_end;
								}
							}

							char* text = (char*) micro_alloc( len-1 );
							if( text == NULL )
							{
								darkomen::detour::trace("WHMTG: Internal Error (script line %d): Failed to allocate %d bytes. Arg# %d.", line, len - 1, count + 1);
								goto lbl_end;
							}
							memcpy( text, &str[1], len-2 );
							WRITE_CODE( (uintptr_t)text );
							str += len;
							break;
						}
						case 3: // jmp
						{
							char* text = (char*) micro_alloc( len+1 );
							if( text == NULL )
							{
								darkomen::detour::trace("WHMTG: Internal Error (script line %d): Failed to allocate %d bytes. Arg# %d.", line, len + 1, count + 1);
								goto lbl_end;
							}
							LABEL_ENTRY* le = (LABEL_ENTRY*) micro_alloc( sizeof(LABEL_ENTRY) );
							if( le == NULL )
							{
								darkomen::detour::trace("WHMTG: Internal Error (script line %d): Failed to allocate %d bytes. Arg# %d.", line, sizeof(LABEL_ENTRY), count + 1);
								goto lbl_end;
							}
							memcpy( text, str, len );
							le->name_len = len;
							le->name = text;
							le->addr = cp;
							le->next = jmps;
							jmps = le;
							WRITE_CODE( (uintptr_t)le->name ); // place-holder
							str += len;
							break;
						}
						case 4: // var
						{
							DWORD dw;			
							if( ( len < 4 ) || ( str[0] != 'v' ) || ( str[1] != 'a' ) || ( str[2] != 'r' ) || ( str[3] != '_' ) )
							{
								darkomen::detour::trace("WHMTG: line %d: bad formatting, expected var_ keyword. Arg# %d.", line, count + 1);
								goto lbl_end;
							}
							if( !my_atoi( &str[4], len - 4, &dw ) )
							{
								darkomen::detour::trace("WHMTG: line %d: bad formatting, unrecognized var. Arg# %d.", line, count + 1);
								goto lbl_end;
							}
							if( dw > 23 ) 
							{
								darkomen::detour::trace("WHMTG: line %d: var index is outside of range. Arg# %d.", line, count + 1);
								goto lbl_end;
							}
							WRITE_CODE( ( var_base + dw * 4 ) );
							str += len;
							break;
						}
						case 5: // cmp
						{
							DWORD dw = -1;
							if( len == 2 )
							{
								if( str[1] == '=' )
								{
									switch( *str )
									{
										case '=':
											dw = 1; 
											break;
										case '/': // fall-thru
										case '!':
											dw = 2;
											break;
									}
								}
								else
								{
									if( ( str[0] == '<' ) && ( str[1] == '>' ) )
									{	
										dw = 2;
									}
								}
							}
							if( len == 1 )
							{
								switch( *str )
								{
									case '=':
										dw = 1;
										break;
									case '<':
										dw = 3;
										break;
									case '>':
										dw = 4;
										break;
								}
							}
							if( dw == -1 )
							{
								darkomen::detour::trace("WHMTG: line %d: bad formatting, unrecognized relationship/comparision operator. Arg# %d.", line, count);
								goto lbl_end;
							}
							WRITE_CODE( dw );
							str += len;
							break;
						}
						case 6: // var_arg ( WHMTG_Speak )
						{
							DWORD num_arg_groups = 0;
							DWORD i = 0;
							for(;;)
							{
								DWORD dw;
								if( !my_atoi( str, len, &dw ) )
								{
									darkomen::detour::trace("WHMTG: line %d: bad formatting, expected integer value. Arg# %d.", line, i);
									goto lbl_end;
								}
								if( i == 0 ) num_arg_groups = dw;
								WRITE_CODE( dw );
								str += len;
								i++;
								if( i >= ( 2 + num_arg_groups * 4 ) ) break; // exit loop

								// else get next arg
								len = GetTok( str );
								if( len == 0 )
								{
									darkomen::detour::trace("WHMTG: line %d: %s, expected %d arguments, found %d.", line, op->name, 2 + (num_arg_groups * 4), i);
									goto lbl_end;
								}
							}
							break;
						}
						case 7: // label
						{	
							char* text = (char*) micro_alloc( len+1 );
							if( text == NULL )
							{
								darkomen::detour::trace("WHMTG: Internal Error (script line %d): Failed to allocate %d bytes. Arg# %d.", line, len + 1, count);
								goto lbl_end;
							}
							LABEL_ENTRY* le = (LABEL_ENTRY*) micro_alloc( sizeof(LABEL_ENTRY) );
							if( le == NULL )
							{
								darkomen::detour::trace("WHMTG: Internal Error (script line %d): Failed to allocate %d bytes. Arg# %d.", line, sizeof(LABEL_ENTRY), count);
								goto lbl_end;
							}
							memcpy( text, str, len );

							// jmp targets are aligned to 8
							if( (DWORD)cp & 4 ) WRITE_CODE( 0 ); // pad as per the game

							le->name_len = len;
							le->name = text;
							le->addr = cp;
							le->next = targets;
							targets = le;
							str += len;
							break;
						}
						default:
						{
								   darkomen::detour::trace("WHMTG: Internal Error (script line %d): unknown arg type. Arg# %d.", line, count);
							goto lbl_end;
						}
					}
				}
				count++;
			}
			if( count != op->arg_cnt )
			{
				darkomen::detour::trace("WHMTG: line %d: %s, expected %d arguments, found %d.", line, op->name, op->arg_cnt, count);
				goto lbl_end;
			}
		}

		// next line
		if( *str == '\r' ) str++;
		if( *str == '\n' ) str++;
		line++;
	}

	if( cp >= &code[_countof(code) - 1] )
	{
		darkomen::detour::trace("WHMTG: Error: Byte-code exceeds maximum size of %d bytes.", sizeof(code));
		goto lbl_end;
	}

	// end with a NULL entry because that is what the game does
	WRITE_CODE( 0 );

	EP_EndScript = cp - 1;
	EP_StartScript = &code[0];

//////////////////////////////////////////////////////////////
/************************************************************/
/************************************************************/
/////////////// part 2: link  ////////////////////////////////


	// find the entry points
	EP_NewGame = NULL;
	EP_Tutorial = NULL;
	EP_TheLivingGem = NULL;
	EP_HandyMan = NULL;
	EP_RideTheSrorm = NULL;
	EP_YouAndI = NULL;
	for( LABEL_ENTRY* t = targets; t != NULL; t = t->next ) 
	{
		switch( t->name_len ) 
		{
			case 7:
				if( !memcmp( t->name, "NEWGAME", 7 ) ) EP_NewGame = t->addr;
				else if( !memcmp( t->name, "YOUANDI", 7 ) ) EP_YouAndI = t->addr;
				break;
			case 8:
				if( !memcmp( t->name, "TUTORIAL", 8 ) ) EP_Tutorial = t->addr;
				else if( !memcmp( t->name, "HANDYMAN", 8 ) ) EP_HandyMan = t->addr;
				break;
			case 12:
				if( !memcmp( t->name, "THELIVINGGEM", 12 ) ) EP_TheLivingGem = t->addr;
				else if( !memcmp( t->name, "RIDETHESTORM", 12 ) ) EP_RideTheSrorm = t->addr;
				break;
		}
	}
	if( EP_NewGame == NULL ) EP_NewGame = EP_StartScript;
	if( EP_Tutorial == NULL ) EP_Tutorial = EP_NewGame;
	if( EP_TheLivingGem == NULL ) EP_TheLivingGem = EP_NewGame;
	if( EP_HandyMan == NULL ) EP_HandyMan = EP_NewGame;
	if( EP_RideTheSrorm == NULL ) EP_RideTheSrorm = EP_NewGame;
	if( EP_YouAndI == NULL ) EP_YouAndI = EP_NewGame;


	// link jmps with targets
	for( LABEL_ENTRY* j = jmps; j != NULL; j = j->next )
	{
		LABEL_ENTRY* t;
		for( t = targets; t != NULL; t = t->next ) 
		{
			if( j->name_len == t->name_len )
			{
				if( !memcmp( j->name, t->name, t->name_len ) )
				{
					//OutputDebugString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" );
					*j->addr = (DWORD)t->addr;
					break;
				}
			}
		}
		if( t == NULL )
		{
			darkomen::detour::trace("WHMTG: Error: LABEL %s not found.", j->name);
			goto lbl_end;
		}
	}


//////////////////////////////////////////////////////////////
/************************************************************/
/************************************************************/
/////////////// part 3: hook-in /////////////////////////////

	DWORD dwPrevProtect;

	// .text section
	if( VirtualProtect( (void*)0x0040E000, 0x1F000, PAGE_READWRITE, &dwPrevProtect ) )
	{
		*( (DWORD**)0x0040EFB4 ) = EP_StartScript;
		*( (DWORD**)0x0040EFCC ) = EP_EndScript;
		*( (DWORD**)0x0040EFAA ) = EP_StartScript;

		*( (DWORD**)0x00420F56 ) = EP_StartScript;
		*( (DWORD**)0x00420F8E ) = EP_EndScript;

		*( (DWORD**)0x00421B83 ) = EP_StartScript;
		*( (DWORD**)0x00421BC6 ) = EP_EndScript;

		*( (DWORD**)0x0042943F ) = EP_Tutorial;
		*( (DWORD**)0x0042C4F7 ) = EP_NewGame;

		VirtualProtect( (void*)0x0040E000, 0x1F000, dwPrevProtect, &dwPrevProtect );
	}

	// .data section
	*( (DWORD**)0x004D7134 ) = EP_TheLivingGem;
	*( (DWORD**)0x004D715C ) = EP_HandyMan;
	*( (DWORD**)0x004D7184 ) = EP_RideTheSrorm;
	*( (DWORD**)0x004D71AC ) = EP_YouAndI;

	bResult = TRUE;

	/*
		HANDLE hFile = CreateFile("dump.bin", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
		DWORD Written;
		WriteFile(hFile, code, sizeof( code ), &Written, NULL);
		CloseHandle(hFile);
	*/

lbl_end:
	if( file != NULL ) VirtualFree( file, 0, MEM_RELEASE );
	return !!bResult;
}
Beispiel #23
0
/*
 * Input URL.
 */
static void ui_input_url(const char *title, char *buf, pj_size_t len,
			 input_result *result)
{
    result->nb_result = PJSUA_APP_NO_NB;
    result->uri_result = NULL;

    print_buddy_list();

    printf("Choices:\n"
	   "   0         For current dialog.\n"
	   "  -1         All %d buddies in buddy list\n"
	   "  [1 -%2d]    Select from buddy list\n"
	   "  URL        An URL\n"
	   "  <Enter>    Empty input (or 'q') to cancel\n"
	   , pjsua_get_buddy_count(), pjsua_get_buddy_count());
    printf("%s: ", title);

    fflush(stdout);
    if (fgets(buf, (int)len, stdin) == NULL)
	return;
    len = strlen(buf);

    /* Left trim */
    while (pj_isspace(*buf)) {
	++buf;
	--len;
    }

    /* Remove trailing newlines */
    while (len && (buf[len-1] == '\r' || buf[len-1] == '\n'))
	buf[--len] = '\0';

    if (len == 0 || buf[0]=='q')
	return;

    if (pj_isdigit(*buf) || *buf=='-') {

	unsigned i;

	if (*buf=='-')
	    i = 1;
	else
	    i = 0;

	for (; i<len; ++i) {
	    if (!pj_isdigit(buf[i])) {
		puts("Invalid input");
		return;
	    }
	}

	result->nb_result = my_atoi(buf);

	if (result->nb_result >= 0 &&
	    result->nb_result <= (int)pjsua_get_buddy_count())
	{
	    return;
	}
	if (result->nb_result == -1)
	    return;

	puts("Invalid input");
	result->nb_result = PJSUA_APP_NO_NB;
	return;

    } else {
	pj_status_t status;

	if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) {
	    pjsua_perror(THIS_FILE, "Invalid URL", status);
	    return;
	}

	result->uri_result = buf;
    }
}
Beispiel #24
0
// 从文件中加载用户数据
bool CVechileMgr::LoadUserFromPath( const char *file )
{
	if ( file == NULL )
		return false ;

	char buf[1024] = {0};
	FILE *fp = NULL;
	fp = fopen( file, "r" );
	if (fp == NULL) {
		OUT_ERROR( NULL, 0, NULL, "Load sim user file %s failed", file ) ;
		return false;
	}

	int pos = _gps_vec.size() ;
	// 手机号: 省域:市域:车牌颜色:车牌号码:终端ID:终端型号
	int count = 0 ;
	while (fgets(buf, sizeof(buf), fp)) {
		unsigned int i = 0;
		while (i < sizeof(buf)) {
			if (!isspace(buf[i]))
				break;
			i++;
		}
		if (buf[i] == '#')
			continue;

		char temp[1024] = {0};
		for (int i = 0, j = 0; i < (int)strlen(buf); ++ i ) {
			if (buf[i] != ' ' && buf[i] != '\r' && buf[i] != '\n') {
				temp[j++] = buf[i];
			}
		}

		string line = temp;
		vector<string> vec;
		if ( ! splitvector( line, vec, ":" , 7 ) ){
			continue ;
		}

		_stVechile *p = new _stVechile ;

		srand( count ) ;

		p->ufd_         = 0 ;
		p->fd_          = 0 ;
		p->gps_pos_	    = rand() % pos ;
		p->last_access_ = share::Util::currentTimeUsec() ;
		p->last_gps_	= share::Util::currentTimeUsec() ;
		p->last_pic_	= 0 ;
		p->seq_id_		= 0 ;
		p->last_conn_   = 0 ;
		p->gps_count_   = 0 ;
		p->lgs_time_    = share::Util::currentTimeUsec() ;
		p->car_state_	= OFF_LINE ;
		// 手机号: 省域:市域:车牌颜色:车牌号码:终端ID:终端型号

		char phone[13] = {0} ;
		my_strrcpy( phone, 12, vec[0].c_str() ) ;

		sprintf( p->carnum_  , "%s" , vec[4].c_str() ) ;
		sprintf( p->termid_  , "%s" , vec[5].c_str() ) ;
		sprintf( p->phone    , "%s" , vec[0].c_str() ) ;
		sprintf( p->termtype , "%s" , vec[6].c_str() ) ;
		strtoBCD( phone, p->car_id_ ) ;

		p->_next = p->_pre = NULL ;
		p->carcolor		= my_atoi( vec[3].c_str() );
		p->cityid		= my_atoi( vec[2].c_str() );
		p->proid		= my_atoi( vec[1].c_str() );

		// 添加离线用户
		_car_queue.push( p ) ;

		++ count ;
	}
	fclose(fp);
	fp = NULL;

	_bench.IncBench( BENCH_ALL_USER, count ) ;

	return ( count > 0 ) ;
}
Beispiel #25
0
int main(int argc, char **argv)
{
    printf("%d\n", my_atoi(argv[1]));
    printf("%d\n", atoi(argv[1]));
    return 0;
}